In [2]:
from sympy import symbols
from sympy.core.trace import Tr
from sympy.matrices.matrices import Matrix
from IPython.core.display import display_pretty
from sympy.printing.latex import *

%load_ext sympyprinting

Basic Examples


In [3]:
a, b, c, d = symbols('a b c d'); 
A, B = symbols('A B', commutative=False)
t = Tr(A*B)

In [4]:
t


Out[4]:
$$\mbox{Tr}\left(A B\right)$$

In [5]:
latex(t)


Out[5]:
\mbox{Tr}\left(A B\right)

In [14]:
display_pretty(t)


Tr(ρ((❘1,1⟩, 0.5),(❘1,-1⟩, 0.5)))

Using Matrices


In [15]:
t = Tr ( Matrix([ [2,3], [3,4] ]))

In [16]:
t


Out[16]:
$$6$$

Example using modules in physics.quantum


In [7]:
from sympy.physics.quantum.density import Density
from sympy.physics.quantum.spin import (
    Jx, Jy, Jz, Jplus, Jminus, J2,
    JxBra, JyBra, JzBra,
    JxKet, JyKet, JzKet,
)

In [8]:
d = Density([JzKet(1,1),0.5],[JzKet(1,-1),0.5]); d


Out[8]:
$$\rho\left(\begin{pmatrix}{\left|1,1\right\rangle }, & 0.5\end{pmatrix},\begin{pmatrix}{\left|1,-1\right\rangle }, & 0.5\end{pmatrix}\right)$$

In [9]:
t = Tr(d)

In [10]:
t


Out[10]:
$$\mbox{Tr}\left(\rho\left(\begin{pmatrix}{\left|1,1\right\rangle }, & 0.5\end{pmatrix},\begin{pmatrix}{\left|1,-1\right\rangle }, & 0.5\end{pmatrix}\right)\right)$$

In [11]:
latex(t)


Out[11]:
\mbox{Tr}\left(\rho\left(\begin{pmatrix}{\left|1,1\right\rangle }, & 0.5\end{p
matrix},\begin{pmatrix}{\left|1,-1\right\rangle }, & 0.5\end{pmatrix}\right)\r
ight)

In [12]:
t.doit()


Out[12]:
$$1.0$$

In [12]: