applied-ai-018 commited on
Commit
4d5e55a
·
verified ·
1 Parent(s): f507358

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step120/zero/23.attention.dense.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step120/zero/23.attention.dense.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step120/zero/23.attention.dense.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step120/zero/4.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step120/zero/4.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  6. ckpts/universal/global_step80/zero/11.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  7. ckpts/universal/global_step80/zero/11.post_attention_layernorm.weight/fp32.pt +3 -0
  8. venv/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py +59 -0
  9. venv/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py +149 -0
  10. venv/lib/python3.10/site-packages/sympy/physics/quantum/boson.py +259 -0
  11. venv/lib/python3.10/site-packages/sympy/physics/quantum/cg.py +754 -0
  12. venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py +370 -0
  13. venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py +488 -0
  14. venv/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
  15. venv/lib/python3.10/site-packages/sympy/physics/quantum/constants.py +59 -0
  16. venv/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py +97 -0
  17. venv/lib/python3.10/site-packages/sympy/physics/quantum/density.py +319 -0
  18. venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py +1305 -0
  19. venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py +345 -0
  20. venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py +853 -0
  21. venv/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py +137 -0
  22. venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py +103 -0
  23. venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py +272 -0
  24. venv/lib/python3.10/site-packages/sympy/physics/quantum/operator.py +650 -0
  25. venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py +329 -0
  26. venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py +280 -0
  27. venv/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py +675 -0
  28. venv/lib/python3.10/site-packages/sympy/physics/quantum/piab.py +72 -0
  29. venv/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py +206 -0
  30. venv/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py +413 -0
  31. venv/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py +811 -0
  32. venv/lib/python3.10/site-packages/sympy/physics/quantum/represent.py +574 -0
  33. venv/lib/python3.10/site-packages/sympy/physics/quantum/sho1d.py +679 -0
  34. venv/lib/python3.10/site-packages/sympy/physics/quantum/shor.py +173 -0
  35. venv/lib/python3.10/site-packages/sympy/physics/quantum/spin.py +2149 -0
  36. venv/lib/python3.10/site-packages/sympy/physics/quantum/state.py +1014 -0
  37. venv/lib/python3.10/site-packages/sympy/physics/tests/__init__.py +0 -0
  38. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py +191 -0
  48. venv/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py +126 -0
  49. venv/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py +57 -0
  50. venv/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py +84 -0
ckpts/universal/global_step120/zero/23.attention.dense.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:426d6c6394407e9c24f4ddbc1dbe70edc996db8b8ea15f7ce8b3590d9dfb7fa2
3
+ size 16778396
ckpts/universal/global_step120/zero/23.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d57d535b9f12397255d4e01dd224d194a43fd2147c593b19a621270632756ff
3
+ size 16778411
ckpts/universal/global_step120/zero/23.attention.dense.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae266dafcf6748aef6a8fe8dd577aeeb93189c3f38405555ef20e3d43358e65d
3
+ size 16778317
ckpts/universal/global_step120/zero/4.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ae33f5ac7d6312d2d02e2afa76b205805a4d8b792c9b56974860cd06cfecf95
3
+ size 33555627
ckpts/universal/global_step120/zero/4.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c17fbe5bdd5a9e31ba468700ff65eae3a041e62403d3321b60d836a8e8068e59
3
+ size 33555533
ckpts/universal/global_step80/zero/11.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3336c200516023b0e733cf0c424b80a32509ef5cecb22de948fd3fc113786a31
3
+ size 9387
ckpts/universal/global_step80/zero/11.post_attention_layernorm.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:916cc8719b994251eb46cbea8c09b7edbec899ce039f0e1aef9a190db645af8d
3
+ size 9293
venv/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Names exposed by 'from sympy.physics.quantum import *'
2
+
3
+ __all__ = [
4
+ 'AntiCommutator',
5
+
6
+ 'qapply',
7
+
8
+ 'Commutator',
9
+
10
+ 'Dagger',
11
+
12
+ 'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace',
13
+ 'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2',
14
+ 'FockSpace',
15
+
16
+ 'InnerProduct',
17
+
18
+ 'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator',
19
+ 'OuterProduct', 'DifferentialOperator',
20
+
21
+ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result',
22
+ 'get_basis', 'enumerate_states',
23
+
24
+ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState',
25
+ 'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra',
26
+ 'OrthogonalState', 'Wavefunction',
27
+
28
+ 'TensorProduct', 'tensor_product_simp',
29
+
30
+ 'hbar', 'HBar',
31
+
32
+ ]
33
+ from .anticommutator import AntiCommutator
34
+
35
+ from .qapply import qapply
36
+
37
+ from .commutator import Commutator
38
+
39
+ from .dagger import Dagger
40
+
41
+ from .hilbert import (HilbertSpaceError, HilbertSpace,
42
+ TensorProductHilbertSpace, TensorPowerHilbertSpace,
43
+ DirectSumHilbertSpace, ComplexSpace, L2, FockSpace)
44
+
45
+ from .innerproduct import InnerProduct
46
+
47
+ from .operator import (Operator, HermitianOperator, UnitaryOperator,
48
+ IdentityOperator, OuterProduct, DifferentialOperator)
49
+
50
+ from .represent import (represent, rep_innerproduct, rep_expectation,
51
+ integrate_result, get_basis, enumerate_states)
52
+
53
+ from .state import (KetBase, BraBase, StateBase, State, Ket, Bra,
54
+ TimeDepState, TimeDepBra, TimeDepKet, OrthogonalKet,
55
+ OrthogonalBra, OrthogonalState, Wavefunction)
56
+
57
+ from .tensorproduct import TensorProduct, tensor_product_simp
58
+
59
+ from .constants import hbar, HBar
venv/lib/python3.10/site-packages/sympy/physics/quantum/anticommutator.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The anti-commutator: ``{A,B} = A*B + B*A``."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.numbers import Integer
6
+ from sympy.core.singleton import S
7
+ from sympy.printing.pretty.stringpict import prettyForm
8
+
9
+ from sympy.physics.quantum.operator import Operator
10
+ from sympy.physics.quantum.dagger import Dagger
11
+
12
+ __all__ = [
13
+ 'AntiCommutator'
14
+ ]
15
+
16
+ #-----------------------------------------------------------------------------
17
+ # Anti-commutator
18
+ #-----------------------------------------------------------------------------
19
+
20
+
21
+ class AntiCommutator(Expr):
22
+ """The standard anticommutator, in an unevaluated state.
23
+
24
+ Explanation
25
+ ===========
26
+
27
+ Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``.
28
+ This class returns the anticommutator in an unevaluated form. To evaluate
29
+ the anticommutator, use the ``.doit()`` method.
30
+
31
+ Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The
32
+ arguments of the anticommutator are put into canonical order using
33
+ ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``.
34
+
35
+ Parameters
36
+ ==========
37
+
38
+ A : Expr
39
+ The first argument of the anticommutator {A,B}.
40
+ B : Expr
41
+ The second argument of the anticommutator {A,B}.
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy import symbols
47
+ >>> from sympy.physics.quantum import AntiCommutator
48
+ >>> from sympy.physics.quantum import Operator, Dagger
49
+ >>> x, y = symbols('x,y')
50
+ >>> A = Operator('A')
51
+ >>> B = Operator('B')
52
+
53
+ Create an anticommutator and use ``doit()`` to multiply them out.
54
+
55
+ >>> ac = AntiCommutator(A,B); ac
56
+ {A,B}
57
+ >>> ac.doit()
58
+ A*B + B*A
59
+
60
+ The commutator orders it arguments in canonical order:
61
+
62
+ >>> ac = AntiCommutator(B,A); ac
63
+ {A,B}
64
+
65
+ Commutative constants are factored out:
66
+
67
+ >>> AntiCommutator(3*x*A,x*y*B)
68
+ 3*x**2*y*{A,B}
69
+
70
+ Adjoint operations applied to the anticommutator are properly applied to
71
+ the arguments:
72
+
73
+ >>> Dagger(AntiCommutator(A,B))
74
+ {Dagger(A),Dagger(B)}
75
+
76
+ References
77
+ ==========
78
+
79
+ .. [1] https://en.wikipedia.org/wiki/Commutator
80
+ """
81
+ is_commutative = False
82
+
83
+ def __new__(cls, A, B):
84
+ r = cls.eval(A, B)
85
+ if r is not None:
86
+ return r
87
+ obj = Expr.__new__(cls, A, B)
88
+ return obj
89
+
90
+ @classmethod
91
+ def eval(cls, a, b):
92
+ if not (a and b):
93
+ return S.Zero
94
+ if a == b:
95
+ return Integer(2)*a**2
96
+ if a.is_commutative or b.is_commutative:
97
+ return Integer(2)*a*b
98
+
99
+ # [xA,yB] -> xy*[A,B]
100
+ ca, nca = a.args_cnc()
101
+ cb, ncb = b.args_cnc()
102
+ c_part = ca + cb
103
+ if c_part:
104
+ return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
105
+
106
+ # Canonical ordering of arguments
107
+ #The Commutator [A,B] is on canonical form if A < B.
108
+ if a.compare(b) == 1:
109
+ return cls(b, a)
110
+
111
+ def doit(self, **hints):
112
+ """ Evaluate anticommutator """
113
+ A = self.args[0]
114
+ B = self.args[1]
115
+ if isinstance(A, Operator) and isinstance(B, Operator):
116
+ try:
117
+ comm = A._eval_anticommutator(B, **hints)
118
+ except NotImplementedError:
119
+ try:
120
+ comm = B._eval_anticommutator(A, **hints)
121
+ except NotImplementedError:
122
+ comm = None
123
+ if comm is not None:
124
+ return comm.doit(**hints)
125
+ return (A*B + B*A).doit(**hints)
126
+
127
+ def _eval_adjoint(self):
128
+ return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1]))
129
+
130
+ def _sympyrepr(self, printer, *args):
131
+ return "%s(%s,%s)" % (
132
+ self.__class__.__name__, printer._print(
133
+ self.args[0]), printer._print(self.args[1])
134
+ )
135
+
136
+ def _sympystr(self, printer, *args):
137
+ return "{%s,%s}" % (
138
+ printer._print(self.args[0]), printer._print(self.args[1]))
139
+
140
+ def _pretty(self, printer, *args):
141
+ pform = printer._print(self.args[0], *args)
142
+ pform = prettyForm(*pform.right(prettyForm(',')))
143
+ pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
144
+ pform = prettyForm(*pform.parens(left='{', right='}'))
145
+ return pform
146
+
147
+ def _latex(self, printer, *args):
148
+ return "\\left\\{%s,%s\\right\\}" % tuple([
149
+ printer._print(arg, *args) for arg in self.args])
venv/lib/python3.10/site-packages/sympy/physics/quantum/boson.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bosonic quantum operators."""
2
+
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.numbers import Integer
5
+ from sympy.core.singleton import S
6
+ from sympy.functions.elementary.complexes import conjugate
7
+ from sympy.functions.elementary.exponential import exp
8
+ from sympy.functions.elementary.miscellaneous import sqrt
9
+ from sympy.physics.quantum import Operator
10
+ from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator
11
+ from sympy.functions.special.tensor_functions import KroneckerDelta
12
+
13
+
14
+ __all__ = [
15
+ 'BosonOp',
16
+ 'BosonFockKet',
17
+ 'BosonFockBra',
18
+ 'BosonCoherentKet',
19
+ 'BosonCoherentBra'
20
+ ]
21
+
22
+
23
+ class BosonOp(Operator):
24
+ """A bosonic operator that satisfies [a, Dagger(a)] == 1.
25
+
26
+ Parameters
27
+ ==========
28
+
29
+ name : str
30
+ A string that labels the bosonic mode.
31
+
32
+ annihilation : bool
33
+ A bool that indicates if the bosonic operator is an annihilation (True,
34
+ default value) or creation operator (False)
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.physics.quantum import Dagger, Commutator
40
+ >>> from sympy.physics.quantum.boson import BosonOp
41
+ >>> a = BosonOp("a")
42
+ >>> Commutator(a, Dagger(a)).doit()
43
+ 1
44
+ """
45
+
46
+ @property
47
+ def name(self):
48
+ return self.args[0]
49
+
50
+ @property
51
+ def is_annihilation(self):
52
+ return bool(self.args[1])
53
+
54
+ @classmethod
55
+ def default_args(self):
56
+ return ("a", True)
57
+
58
+ def __new__(cls, *args, **hints):
59
+ if not len(args) in [1, 2]:
60
+ raise ValueError('1 or 2 parameters expected, got %s' % args)
61
+
62
+ if len(args) == 1:
63
+ args = (args[0], S.One)
64
+
65
+ if len(args) == 2:
66
+ args = (args[0], Integer(args[1]))
67
+
68
+ return Operator.__new__(cls, *args)
69
+
70
+ def _eval_commutator_BosonOp(self, other, **hints):
71
+ if self.name == other.name:
72
+ # [a^\dagger, a] = -1
73
+ if not self.is_annihilation and other.is_annihilation:
74
+ return S.NegativeOne
75
+
76
+ elif 'independent' in hints and hints['independent']:
77
+ # [a, b] = 0
78
+ return S.Zero
79
+
80
+ return None
81
+
82
+ def _eval_commutator_FermionOp(self, other, **hints):
83
+ return S.Zero
84
+
85
+ def _eval_anticommutator_BosonOp(self, other, **hints):
86
+ if 'independent' in hints and hints['independent']:
87
+ # {a, b} = 2 * a * b, because [a, b] = 0
88
+ return 2 * self * other
89
+
90
+ return None
91
+
92
+ def _eval_adjoint(self):
93
+ return BosonOp(str(self.name), not self.is_annihilation)
94
+
95
+ def __mul__(self, other):
96
+
97
+ if other == IdentityOperator(2):
98
+ return self
99
+
100
+ if isinstance(other, Mul):
101
+ args1 = tuple(arg for arg in other.args if arg.is_commutative)
102
+ args2 = tuple(arg for arg in other.args if not arg.is_commutative)
103
+ x = self
104
+ for y in args2:
105
+ x = x * y
106
+ return Mul(*args1) * x
107
+
108
+ return Mul(self, other)
109
+
110
+ def _print_contents_latex(self, printer, *args):
111
+ if self.is_annihilation:
112
+ return r'{%s}' % str(self.name)
113
+ else:
114
+ return r'{{%s}^\dagger}' % str(self.name)
115
+
116
+ def _print_contents(self, printer, *args):
117
+ if self.is_annihilation:
118
+ return r'%s' % str(self.name)
119
+ else:
120
+ return r'Dagger(%s)' % str(self.name)
121
+
122
+ def _print_contents_pretty(self, printer, *args):
123
+ from sympy.printing.pretty.stringpict import prettyForm
124
+ pform = printer._print(self.args[0], *args)
125
+ if self.is_annihilation:
126
+ return pform
127
+ else:
128
+ return pform**prettyForm('\N{DAGGER}')
129
+
130
+
131
+ class BosonFockKet(Ket):
132
+ """Fock state ket for a bosonic mode.
133
+
134
+ Parameters
135
+ ==========
136
+
137
+ n : Number
138
+ The Fock state number.
139
+
140
+ """
141
+
142
+ def __new__(cls, n):
143
+ return Ket.__new__(cls, n)
144
+
145
+ @property
146
+ def n(self):
147
+ return self.label[0]
148
+
149
+ @classmethod
150
+ def dual_class(self):
151
+ return BosonFockBra
152
+
153
+ @classmethod
154
+ def _eval_hilbert_space(cls, label):
155
+ return FockSpace()
156
+
157
+ def _eval_innerproduct_BosonFockBra(self, bra, **hints):
158
+ return KroneckerDelta(self.n, bra.n)
159
+
160
+ def _apply_from_right_to_BosonOp(self, op, **options):
161
+ if op.is_annihilation:
162
+ return sqrt(self.n) * BosonFockKet(self.n - 1)
163
+ else:
164
+ return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
165
+
166
+
167
+ class BosonFockBra(Bra):
168
+ """Fock state bra for a bosonic mode.
169
+
170
+ Parameters
171
+ ==========
172
+
173
+ n : Number
174
+ The Fock state number.
175
+
176
+ """
177
+
178
+ def __new__(cls, n):
179
+ return Bra.__new__(cls, n)
180
+
181
+ @property
182
+ def n(self):
183
+ return self.label[0]
184
+
185
+ @classmethod
186
+ def dual_class(self):
187
+ return BosonFockKet
188
+
189
+ @classmethod
190
+ def _eval_hilbert_space(cls, label):
191
+ return FockSpace()
192
+
193
+
194
+ class BosonCoherentKet(Ket):
195
+ """Coherent state ket for a bosonic mode.
196
+
197
+ Parameters
198
+ ==========
199
+
200
+ alpha : Number, Symbol
201
+ The complex amplitude of the coherent state.
202
+
203
+ """
204
+
205
+ def __new__(cls, alpha):
206
+ return Ket.__new__(cls, alpha)
207
+
208
+ @property
209
+ def alpha(self):
210
+ return self.label[0]
211
+
212
+ @classmethod
213
+ def dual_class(self):
214
+ return BosonCoherentBra
215
+
216
+ @classmethod
217
+ def _eval_hilbert_space(cls, label):
218
+ return HilbertSpace()
219
+
220
+ def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
221
+ if self.alpha == bra.alpha:
222
+ return S.One
223
+ else:
224
+ return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
225
+
226
+ def _apply_from_right_to_BosonOp(self, op, **options):
227
+ if op.is_annihilation:
228
+ return self.alpha * self
229
+ else:
230
+ return None
231
+
232
+
233
+ class BosonCoherentBra(Bra):
234
+ """Coherent state bra for a bosonic mode.
235
+
236
+ Parameters
237
+ ==========
238
+
239
+ alpha : Number, Symbol
240
+ The complex amplitude of the coherent state.
241
+
242
+ """
243
+
244
+ def __new__(cls, alpha):
245
+ return Bra.__new__(cls, alpha)
246
+
247
+ @property
248
+ def alpha(self):
249
+ return self.label[0]
250
+
251
+ @classmethod
252
+ def dual_class(self):
253
+ return BosonCoherentKet
254
+
255
+ def _apply_operator_BosonOp(self, op, **options):
256
+ if not op.is_annihilation:
257
+ return self.alpha * self
258
+ else:
259
+ return None
venv/lib/python3.10/site-packages/sympy/physics/quantum/cg.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #TODO:
2
+ # -Implement Clebsch-Gordan symmetries
3
+ # -Improve simplification method
4
+ # -Implement new simplifications
5
+ """Clebsch-Gordon Coefficients."""
6
+
7
+ from sympy.concrete.summations import Sum
8
+ from sympy.core.add import Add
9
+ from sympy.core.expr import Expr
10
+ from sympy.core.function import expand
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.power import Pow
13
+ from sympy.core.relational import Eq
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import (Wild, symbols)
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.elementary.miscellaneous import sqrt
18
+ from sympy.functions.elementary.piecewise import Piecewise
19
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
20
+
21
+ from sympy.functions.special.tensor_functions import KroneckerDelta
22
+ from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
23
+ from sympy.printing.precedence import PRECEDENCE
24
+
25
+ __all__ = [
26
+ 'CG',
27
+ 'Wigner3j',
28
+ 'Wigner6j',
29
+ 'Wigner9j',
30
+ 'cg_simp'
31
+ ]
32
+
33
+ #-----------------------------------------------------------------------------
34
+ # CG Coefficients
35
+ #-----------------------------------------------------------------------------
36
+
37
+
38
+ class Wigner3j(Expr):
39
+ """Class for the Wigner-3j symbols.
40
+
41
+ Explanation
42
+ ===========
43
+
44
+ Wigner 3j-symbols are coefficients determined by the coupling of
45
+ two angular momenta. When created, they are expressed as symbolic
46
+ quantities that, for numerical parameters, can be evaluated using the
47
+ ``.doit()`` method [1]_.
48
+
49
+ Parameters
50
+ ==========
51
+
52
+ j1, m1, j2, m2, j3, m3 : Number, Symbol
53
+ Terms determining the angular momentum of coupled angular momentum
54
+ systems.
55
+
56
+ Examples
57
+ ========
58
+
59
+ Declare a Wigner-3j coefficient and calculate its value
60
+
61
+ >>> from sympy.physics.quantum.cg import Wigner3j
62
+ >>> w3j = Wigner3j(6,0,4,0,2,0)
63
+ >>> w3j
64
+ Wigner3j(6, 0, 4, 0, 2, 0)
65
+ >>> w3j.doit()
66
+ sqrt(715)/143
67
+
68
+ See Also
69
+ ========
70
+
71
+ CG: Clebsch-Gordan coefficients
72
+
73
+ References
74
+ ==========
75
+
76
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
77
+ """
78
+
79
+ is_commutative = True
80
+
81
+ def __new__(cls, j1, m1, j2, m2, j3, m3):
82
+ args = map(sympify, (j1, m1, j2, m2, j3, m3))
83
+ return Expr.__new__(cls, *args)
84
+
85
+ @property
86
+ def j1(self):
87
+ return self.args[0]
88
+
89
+ @property
90
+ def m1(self):
91
+ return self.args[1]
92
+
93
+ @property
94
+ def j2(self):
95
+ return self.args[2]
96
+
97
+ @property
98
+ def m2(self):
99
+ return self.args[3]
100
+
101
+ @property
102
+ def j3(self):
103
+ return self.args[4]
104
+
105
+ @property
106
+ def m3(self):
107
+ return self.args[5]
108
+
109
+ @property
110
+ def is_symbolic(self):
111
+ return not all(arg.is_number for arg in self.args)
112
+
113
+ # This is modified from the _print_Matrix method
114
+ def _pretty(self, printer, *args):
115
+ m = ((printer._print(self.j1), printer._print(self.m1)),
116
+ (printer._print(self.j2), printer._print(self.m2)),
117
+ (printer._print(self.j3), printer._print(self.m3)))
118
+ hsep = 2
119
+ vsep = 1
120
+ maxw = [-1]*3
121
+ for j in range(3):
122
+ maxw[j] = max([ m[j][i].width() for i in range(2) ])
123
+ D = None
124
+ for i in range(2):
125
+ D_row = None
126
+ for j in range(3):
127
+ s = m[j][i]
128
+ wdelta = maxw[j] - s.width()
129
+ wleft = wdelta //2
130
+ wright = wdelta - wleft
131
+
132
+ s = prettyForm(*s.right(' '*wright))
133
+ s = prettyForm(*s.left(' '*wleft))
134
+
135
+ if D_row is None:
136
+ D_row = s
137
+ continue
138
+ D_row = prettyForm(*D_row.right(' '*hsep))
139
+ D_row = prettyForm(*D_row.right(s))
140
+ if D is None:
141
+ D = D_row
142
+ continue
143
+ for _ in range(vsep):
144
+ D = prettyForm(*D.below(' '))
145
+ D = prettyForm(*D.below(D_row))
146
+ D = prettyForm(*D.parens())
147
+ return D
148
+
149
+ def _latex(self, printer, *args):
150
+ label = map(printer._print, (self.j1, self.j2, self.j3,
151
+ self.m1, self.m2, self.m3))
152
+ return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
153
+ tuple(label)
154
+
155
+ def doit(self, **hints):
156
+ if self.is_symbolic:
157
+ raise ValueError("Coefficients must be numerical")
158
+ return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
159
+
160
+
161
+ class CG(Wigner3j):
162
+ r"""Class for Clebsch-Gordan coefficient.
163
+
164
+ Explanation
165
+ ===========
166
+
167
+ Clebsch-Gordan coefficients describe the angular momentum coupling between
168
+ two systems. The coefficients give the expansion of a coupled total angular
169
+ momentum state and an uncoupled tensor product state. The Clebsch-Gordan
170
+ coefficients are defined as [1]_:
171
+
172
+ .. math ::
173
+ C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ j1, m1, j2, m2 : Number, Symbol
179
+ Angular momenta of states 1 and 2.
180
+
181
+ j3, m3: Number, Symbol
182
+ Total angular momentum of the coupled system.
183
+
184
+ Examples
185
+ ========
186
+
187
+ Define a Clebsch-Gordan coefficient and evaluate its value
188
+
189
+ >>> from sympy.physics.quantum.cg import CG
190
+ >>> from sympy import S
191
+ >>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
192
+ >>> cg
193
+ CG(3/2, 3/2, 1/2, -1/2, 1, 1)
194
+ >>> cg.doit()
195
+ sqrt(3)/2
196
+ >>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
197
+ sqrt(2)/2
198
+
199
+
200
+ Compare [2]_.
201
+
202
+ See Also
203
+ ========
204
+
205
+ Wigner3j: Wigner-3j symbols
206
+
207
+ References
208
+ ==========
209
+
210
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
211
+ .. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
212
+ <https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
213
+ in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
214
+ 2020, 083C01 (2020).
215
+ """
216
+ precedence = PRECEDENCE["Pow"] - 1
217
+
218
+ def doit(self, **hints):
219
+ if self.is_symbolic:
220
+ raise ValueError("Coefficients must be numerical")
221
+ return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
222
+
223
+ def _pretty(self, printer, *args):
224
+ bot = printer._print_seq(
225
+ (self.j1, self.m1, self.j2, self.m2), delimiter=',')
226
+ top = printer._print_seq((self.j3, self.m3), delimiter=',')
227
+
228
+ pad = max(top.width(), bot.width())
229
+ bot = prettyForm(*bot.left(' '))
230
+ top = prettyForm(*top.left(' '))
231
+
232
+ if not pad == bot.width():
233
+ bot = prettyForm(*bot.right(' '*(pad - bot.width())))
234
+ if not pad == top.width():
235
+ top = prettyForm(*top.right(' '*(pad - top.width())))
236
+ s = stringPict('C' + ' '*pad)
237
+ s = prettyForm(*s.below(bot))
238
+ s = prettyForm(*s.above(top))
239
+ return s
240
+
241
+ def _latex(self, printer, *args):
242
+ label = map(printer._print, (self.j3, self.m3, self.j1,
243
+ self.m1, self.j2, self.m2))
244
+ return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
245
+
246
+
247
+ class Wigner6j(Expr):
248
+ """Class for the Wigner-6j symbols
249
+
250
+ See Also
251
+ ========
252
+
253
+ Wigner3j: Wigner-3j symbols
254
+
255
+ """
256
+ def __new__(cls, j1, j2, j12, j3, j, j23):
257
+ args = map(sympify, (j1, j2, j12, j3, j, j23))
258
+ return Expr.__new__(cls, *args)
259
+
260
+ @property
261
+ def j1(self):
262
+ return self.args[0]
263
+
264
+ @property
265
+ def j2(self):
266
+ return self.args[1]
267
+
268
+ @property
269
+ def j12(self):
270
+ return self.args[2]
271
+
272
+ @property
273
+ def j3(self):
274
+ return self.args[3]
275
+
276
+ @property
277
+ def j(self):
278
+ return self.args[4]
279
+
280
+ @property
281
+ def j23(self):
282
+ return self.args[5]
283
+
284
+ @property
285
+ def is_symbolic(self):
286
+ return not all(arg.is_number for arg in self.args)
287
+
288
+ # This is modified from the _print_Matrix method
289
+ def _pretty(self, printer, *args):
290
+ m = ((printer._print(self.j1), printer._print(self.j3)),
291
+ (printer._print(self.j2), printer._print(self.j)),
292
+ (printer._print(self.j12), printer._print(self.j23)))
293
+ hsep = 2
294
+ vsep = 1
295
+ maxw = [-1]*3
296
+ for j in range(3):
297
+ maxw[j] = max([ m[j][i].width() for i in range(2) ])
298
+ D = None
299
+ for i in range(2):
300
+ D_row = None
301
+ for j in range(3):
302
+ s = m[j][i]
303
+ wdelta = maxw[j] - s.width()
304
+ wleft = wdelta //2
305
+ wright = wdelta - wleft
306
+
307
+ s = prettyForm(*s.right(' '*wright))
308
+ s = prettyForm(*s.left(' '*wleft))
309
+
310
+ if D_row is None:
311
+ D_row = s
312
+ continue
313
+ D_row = prettyForm(*D_row.right(' '*hsep))
314
+ D_row = prettyForm(*D_row.right(s))
315
+ if D is None:
316
+ D = D_row
317
+ continue
318
+ for _ in range(vsep):
319
+ D = prettyForm(*D.below(' '))
320
+ D = prettyForm(*D.below(D_row))
321
+ D = prettyForm(*D.parens(left='{', right='}'))
322
+ return D
323
+
324
+ def _latex(self, printer, *args):
325
+ label = map(printer._print, (self.j1, self.j2, self.j12,
326
+ self.j3, self.j, self.j23))
327
+ return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
328
+ tuple(label)
329
+
330
+ def doit(self, **hints):
331
+ if self.is_symbolic:
332
+ raise ValueError("Coefficients must be numerical")
333
+ return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
334
+
335
+
336
+ class Wigner9j(Expr):
337
+ """Class for the Wigner-9j symbols
338
+
339
+ See Also
340
+ ========
341
+
342
+ Wigner3j: Wigner-3j symbols
343
+
344
+ """
345
+ def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
346
+ args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
347
+ return Expr.__new__(cls, *args)
348
+
349
+ @property
350
+ def j1(self):
351
+ return self.args[0]
352
+
353
+ @property
354
+ def j2(self):
355
+ return self.args[1]
356
+
357
+ @property
358
+ def j12(self):
359
+ return self.args[2]
360
+
361
+ @property
362
+ def j3(self):
363
+ return self.args[3]
364
+
365
+ @property
366
+ def j4(self):
367
+ return self.args[4]
368
+
369
+ @property
370
+ def j34(self):
371
+ return self.args[5]
372
+
373
+ @property
374
+ def j13(self):
375
+ return self.args[6]
376
+
377
+ @property
378
+ def j24(self):
379
+ return self.args[7]
380
+
381
+ @property
382
+ def j(self):
383
+ return self.args[8]
384
+
385
+ @property
386
+ def is_symbolic(self):
387
+ return not all(arg.is_number for arg in self.args)
388
+
389
+ # This is modified from the _print_Matrix method
390
+ def _pretty(self, printer, *args):
391
+ m = (
392
+ (printer._print(
393
+ self.j1), printer._print(self.j3), printer._print(self.j13)),
394
+ (printer._print(
395
+ self.j2), printer._print(self.j4), printer._print(self.j24)),
396
+ (printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
397
+ hsep = 2
398
+ vsep = 1
399
+ maxw = [-1]*3
400
+ for j in range(3):
401
+ maxw[j] = max([ m[j][i].width() for i in range(3) ])
402
+ D = None
403
+ for i in range(3):
404
+ D_row = None
405
+ for j in range(3):
406
+ s = m[j][i]
407
+ wdelta = maxw[j] - s.width()
408
+ wleft = wdelta //2
409
+ wright = wdelta - wleft
410
+
411
+ s = prettyForm(*s.right(' '*wright))
412
+ s = prettyForm(*s.left(' '*wleft))
413
+
414
+ if D_row is None:
415
+ D_row = s
416
+ continue
417
+ D_row = prettyForm(*D_row.right(' '*hsep))
418
+ D_row = prettyForm(*D_row.right(s))
419
+ if D is None:
420
+ D = D_row
421
+ continue
422
+ for _ in range(vsep):
423
+ D = prettyForm(*D.below(' '))
424
+ D = prettyForm(*D.below(D_row))
425
+ D = prettyForm(*D.parens(left='{', right='}'))
426
+ return D
427
+
428
+ def _latex(self, printer, *args):
429
+ label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
430
+ self.j4, self.j34, self.j13, self.j24, self.j))
431
+ return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
432
+ tuple(label)
433
+
434
+ def doit(self, **hints):
435
+ if self.is_symbolic:
436
+ raise ValueError("Coefficients must be numerical")
437
+ return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
438
+
439
+
440
+ def cg_simp(e):
441
+ """Simplify and combine CG coefficients.
442
+
443
+ Explanation
444
+ ===========
445
+
446
+ This function uses various symmetry and properties of sums and
447
+ products of Clebsch-Gordan coefficients to simplify statements
448
+ involving these terms [1]_.
449
+
450
+ Examples
451
+ ========
452
+
453
+ Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
454
+ 2*a+1
455
+
456
+ >>> from sympy.physics.quantum.cg import CG, cg_simp
457
+ >>> a = CG(1,1,0,0,1,1)
458
+ >>> b = CG(1,0,0,0,1,0)
459
+ >>> c = CG(1,-1,0,0,1,-1)
460
+ >>> cg_simp(a+b+c)
461
+ 3
462
+
463
+ See Also
464
+ ========
465
+
466
+ CG: Clebsh-Gordan coefficients
467
+
468
+ References
469
+ ==========
470
+
471
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
472
+ """
473
+ if isinstance(e, Add):
474
+ return _cg_simp_add(e)
475
+ elif isinstance(e, Sum):
476
+ return _cg_simp_sum(e)
477
+ elif isinstance(e, Mul):
478
+ return Mul(*[cg_simp(arg) for arg in e.args])
479
+ elif isinstance(e, Pow):
480
+ return Pow(cg_simp(e.base), e.exp)
481
+ else:
482
+ return e
483
+
484
+
485
+ def _cg_simp_add(e):
486
+ #TODO: Improve simplification method
487
+ """Takes a sum of terms involving Clebsch-Gordan coefficients and
488
+ simplifies the terms.
489
+
490
+ Explanation
491
+ ===========
492
+
493
+ First, we create two lists, cg_part, which is all the terms involving CG
494
+ coefficients, and other_part, which is all other terms. The cg_part list
495
+ is then passed to the simplification methods, which return the new cg_part
496
+ and any additional terms that are added to other_part
497
+ """
498
+ cg_part = []
499
+ other_part = []
500
+
501
+ e = expand(e)
502
+ for arg in e.args:
503
+ if arg.has(CG):
504
+ if isinstance(arg, Sum):
505
+ other_part.append(_cg_simp_sum(arg))
506
+ elif isinstance(arg, Mul):
507
+ terms = 1
508
+ for term in arg.args:
509
+ if isinstance(term, Sum):
510
+ terms *= _cg_simp_sum(term)
511
+ else:
512
+ terms *= term
513
+ if terms.has(CG):
514
+ cg_part.append(terms)
515
+ else:
516
+ other_part.append(terms)
517
+ else:
518
+ cg_part.append(arg)
519
+ else:
520
+ other_part.append(arg)
521
+
522
+ cg_part, other = _check_varsh_871_1(cg_part)
523
+ other_part.append(other)
524
+ cg_part, other = _check_varsh_871_2(cg_part)
525
+ other_part.append(other)
526
+ cg_part, other = _check_varsh_872_9(cg_part)
527
+ other_part.append(other)
528
+ return Add(*cg_part) + Add(*other_part)
529
+
530
+
531
+ def _check_varsh_871_1(term_list):
532
+ # Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
533
+ a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
534
+ expr = lt*CG(a, alpha, b, 0, a, alpha)
535
+ simp = (2*a + 1)*KroneckerDelta(b, 0)
536
+ sign = lt/abs(lt)
537
+ build_expr = 2*a + 1
538
+ index_expr = a + alpha
539
+ return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
540
+
541
+
542
+ def _check_varsh_871_2(term_list):
543
+ # Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
544
+ a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
545
+ expr = lt*CG(a, alpha, a, -alpha, c, 0)
546
+ simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
547
+ sign = (-1)**(a - alpha)*lt/abs(lt)
548
+ build_expr = 2*a + 1
549
+ index_expr = a + alpha
550
+ return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
551
+
552
+
553
+ def _check_varsh_872_9(term_list):
554
+ # Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
555
+ a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
556
+ 'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
557
+ # Case alpha==alphap, beta==betap
558
+
559
+ # For numerical alpha,beta
560
+ expr = lt*CG(a, alpha, b, beta, c, gamma)**2
561
+ simp = S.One
562
+ sign = lt/abs(lt)
563
+ x = abs(a - b)
564
+ y = abs(alpha + beta)
565
+ build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
566
+ index_expr = a + b - c
567
+ term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
568
+
569
+ # For symbolic alpha,beta
570
+ x = abs(a - b)
571
+ y = a + b
572
+ build_expr = (y + 1 - x)*(x + y + 1)
573
+ index_expr = (c - x)*(x + c) + c + gamma
574
+ term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
575
+
576
+ # Case alpha!=alphap or beta!=betap
577
+ # Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
578
+ # For numerical alpha,alphap,beta,betap
579
+ expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
580
+ simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
581
+ sign = S.One
582
+ x = abs(a - b)
583
+ y = abs(alpha + beta)
584
+ build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
585
+ index_expr = a + b - c
586
+ term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
587
+
588
+ # For symbolic alpha,alphap,beta,betap
589
+ x = abs(a - b)
590
+ y = a + b
591
+ build_expr = (y + 1 - x)*(x + y + 1)
592
+ index_expr = (c - x)*(x + c) + c + gamma
593
+ term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
594
+
595
+ return term_list, other1 + other2 + other4
596
+
597
+
598
+ def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
599
+ """ Checks for simplifications that can be made, returning a tuple of the
600
+ simplified list of terms and any terms generated by simplification.
601
+
602
+ Parameters
603
+ ==========
604
+
605
+ expr: expression
606
+ The expression with Wild terms that will be matched to the terms in
607
+ the sum
608
+
609
+ simp: expression
610
+ The expression with Wild terms that is substituted in place of the CG
611
+ terms in the case of simplification
612
+
613
+ sign: expression
614
+ The expression with Wild terms denoting the sign that is on expr that
615
+ must match
616
+
617
+ lt: expression
618
+ The expression with Wild terms that gives the leading term of the
619
+ matched expr
620
+
621
+ term_list: list
622
+ A list of all of the terms is the sum to be simplified
623
+
624
+ variables: list
625
+ A list of all the variables that appears in expr
626
+
627
+ dep_variables: list
628
+ A list of the variables that must match for all the terms in the sum,
629
+ i.e. the dependent variables
630
+
631
+ build_index_expr: expression
632
+ Expression with Wild terms giving the number of elements in cg_index
633
+
634
+ index_expr: expression
635
+ Expression with Wild terms giving the index terms have when storing
636
+ them to cg_index
637
+
638
+ """
639
+ other_part = 0
640
+ i = 0
641
+ while i < len(term_list):
642
+ sub_1 = _check_cg(term_list[i], expr, len(variables))
643
+ if sub_1 is None:
644
+ i += 1
645
+ continue
646
+ if not build_index_expr.subs(sub_1).is_number:
647
+ i += 1
648
+ continue
649
+ sub_dep = [(x, sub_1[x]) for x in dep_variables]
650
+ cg_index = [None]*build_index_expr.subs(sub_1)
651
+ for j in range(i, len(term_list)):
652
+ sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
653
+ if sub_2 is None:
654
+ continue
655
+ if not index_expr.subs(sub_dep).subs(sub_2).is_number:
656
+ continue
657
+ cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
658
+ if not any(i is None for i in cg_index):
659
+ min_lt = min(*[ abs(term[2]) for term in cg_index ])
660
+ indices = [ term[0] for term in cg_index]
661
+ indices.sort()
662
+ indices.reverse()
663
+ [ term_list.pop(j) for j in indices ]
664
+ for term in cg_index:
665
+ if abs(term[2]) > min_lt:
666
+ term_list.append( (term[2] - min_lt*term[3])*term[1] )
667
+ other_part += min_lt*(sign*simp).subs(sub_1)
668
+ else:
669
+ i += 1
670
+ return term_list, other_part
671
+
672
+
673
+ def _check_cg(cg_term, expr, length, sign=None):
674
+ """Checks whether a term matches the given expression"""
675
+ # TODO: Check for symmetries
676
+ matches = cg_term.match(expr)
677
+ if matches is None:
678
+ return
679
+ if sign is not None:
680
+ if not isinstance(sign, tuple):
681
+ raise TypeError('sign must be a tuple')
682
+ if not sign[0] == (sign[1]).subs(matches):
683
+ return
684
+ if len(matches) == length:
685
+ return matches
686
+
687
+
688
+ def _cg_simp_sum(e):
689
+ e = _check_varsh_sum_871_1(e)
690
+ e = _check_varsh_sum_871_2(e)
691
+ e = _check_varsh_sum_872_4(e)
692
+ return e
693
+
694
+
695
+ def _check_varsh_sum_871_1(e):
696
+ a = Wild('a')
697
+ alpha = symbols('alpha')
698
+ b = Wild('b')
699
+ match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
700
+ if match is not None and len(match) == 2:
701
+ return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
702
+ return e
703
+
704
+
705
+ def _check_varsh_sum_871_2(e):
706
+ a = Wild('a')
707
+ alpha = symbols('alpha')
708
+ c = Wild('c')
709
+ match = e.match(
710
+ Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
711
+ if match is not None and len(match) == 2:
712
+ return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
713
+ return e
714
+
715
+
716
+ def _check_varsh_sum_872_4(e):
717
+ alpha = symbols('alpha')
718
+ beta = symbols('beta')
719
+ a = Wild('a')
720
+ b = Wild('b')
721
+ c = Wild('c')
722
+ cp = Wild('cp')
723
+ gamma = Wild('gamma')
724
+ gammap = Wild('gammap')
725
+ cg1 = CG(a, alpha, b, beta, c, gamma)
726
+ cg2 = CG(a, alpha, b, beta, cp, gammap)
727
+ match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
728
+ if match1 is not None and len(match1) == 6:
729
+ return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
730
+ match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
731
+ if match2 is not None and len(match2) == 4:
732
+ return S.One
733
+ return e
734
+
735
+
736
+ def _cg_list(term):
737
+ if isinstance(term, CG):
738
+ return (term,), 1, 1
739
+ cg = []
740
+ coeff = 1
741
+ if not isinstance(term, (Mul, Pow)):
742
+ raise NotImplementedError('term must be CG, Add, Mul or Pow')
743
+ if isinstance(term, Pow) and term.exp.is_number:
744
+ if term.exp.is_number:
745
+ [ cg.append(term.base) for _ in range(term.exp) ]
746
+ else:
747
+ return (term,), 1, 1
748
+ if isinstance(term, Mul):
749
+ for arg in term.args:
750
+ if isinstance(arg, CG):
751
+ cg.append(arg)
752
+ else:
753
+ coeff *= arg
754
+ return cg, coeff, coeff/abs(coeff)
venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitplot.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Matplotlib based plotting of quantum circuits.
2
+
3
+ Todo:
4
+
5
+ * Optimize printing of large circuits.
6
+ * Get this to work with single gates.
7
+ * Do a better job checking the form of circuits to make sure it is a Mul of
8
+ Gates.
9
+ * Get multi-target gates plotting.
10
+ * Get initial and final states to plot.
11
+ * Get measurements to plot. Might need to rethink measurement as a gate
12
+ issue.
13
+ * Get scale and figsize to be handled in a better way.
14
+ * Write some tests/examples!
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from sympy.core.mul import Mul
20
+ from sympy.external import import_module
21
+ from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS
22
+
23
+
24
+ __all__ = [
25
+ 'CircuitPlot',
26
+ 'circuit_plot',
27
+ 'labeller',
28
+ 'Mz',
29
+ 'Mx',
30
+ 'CreateOneQubitGate',
31
+ 'CreateCGate',
32
+ ]
33
+
34
+ np = import_module('numpy')
35
+ matplotlib = import_module(
36
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
37
+ catch=(RuntimeError,)) # This is raised in environments that have no display.
38
+
39
+ if np and matplotlib:
40
+ pyplot = matplotlib.pyplot
41
+ Line2D = matplotlib.lines.Line2D
42
+ Circle = matplotlib.patches.Circle
43
+
44
+ #from matplotlib import rc
45
+ #rc('text',usetex=True)
46
+
47
+ class CircuitPlot:
48
+ """A class for managing a circuit plot."""
49
+
50
+ scale = 1.0
51
+ fontsize = 20.0
52
+ linewidth = 1.0
53
+ control_radius = 0.05
54
+ not_radius = 0.15
55
+ swap_delta = 0.05
56
+ labels: list[str] = []
57
+ inits: dict[str, str] = {}
58
+ label_buffer = 0.5
59
+
60
+ def __init__(self, c, nqubits, **kwargs):
61
+ if not np or not matplotlib:
62
+ raise ImportError('numpy or matplotlib not available.')
63
+ self.circuit = c
64
+ self.ngates = len(self.circuit.args)
65
+ self.nqubits = nqubits
66
+ self.update(kwargs)
67
+ self._create_grid()
68
+ self._create_figure()
69
+ self._plot_wires()
70
+ self._plot_gates()
71
+ self._finish()
72
+
73
+ def update(self, kwargs):
74
+ """Load the kwargs into the instance dict."""
75
+ self.__dict__.update(kwargs)
76
+
77
+ def _create_grid(self):
78
+ """Create the grid of wires."""
79
+ scale = self.scale
80
+ wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float)
81
+ gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float)
82
+ self._wire_grid = wire_grid
83
+ self._gate_grid = gate_grid
84
+
85
+ def _create_figure(self):
86
+ """Create the main matplotlib figure."""
87
+ self._figure = pyplot.figure(
88
+ figsize=(self.ngates*self.scale, self.nqubits*self.scale),
89
+ facecolor='w',
90
+ edgecolor='w'
91
+ )
92
+ ax = self._figure.add_subplot(
93
+ 1, 1, 1,
94
+ frameon=True
95
+ )
96
+ ax.set_axis_off()
97
+ offset = 0.5*self.scale
98
+ ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset)
99
+ ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset)
100
+ ax.set_aspect('equal')
101
+ self._axes = ax
102
+
103
+ def _plot_wires(self):
104
+ """Plot the wires of the circuit diagram."""
105
+ xstart = self._gate_grid[0]
106
+ xstop = self._gate_grid[-1]
107
+ xdata = (xstart - self.scale, xstop + self.scale)
108
+ for i in range(self.nqubits):
109
+ ydata = (self._wire_grid[i], self._wire_grid[i])
110
+ line = Line2D(
111
+ xdata, ydata,
112
+ color='k',
113
+ lw=self.linewidth
114
+ )
115
+ self._axes.add_line(line)
116
+ if self.labels:
117
+ init_label_buffer = 0
118
+ if self.inits.get(self.labels[i]): init_label_buffer = 0.25
119
+ self._axes.text(
120
+ xdata[0]-self.label_buffer-init_label_buffer,ydata[0],
121
+ render_label(self.labels[i],self.inits),
122
+ size=self.fontsize,
123
+ color='k',ha='center',va='center')
124
+ self._plot_measured_wires()
125
+
126
+ def _plot_measured_wires(self):
127
+ ismeasured = self._measurements()
128
+ xstop = self._gate_grid[-1]
129
+ dy = 0.04 # amount to shift wires when doubled
130
+ # Plot doubled wires after they are measured
131
+ for im in ismeasured:
132
+ xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale)
133
+ ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy)
134
+ line = Line2D(
135
+ xdata, ydata,
136
+ color='k',
137
+ lw=self.linewidth
138
+ )
139
+ self._axes.add_line(line)
140
+ # Also double any controlled lines off these wires
141
+ for i,g in enumerate(self._gates()):
142
+ if isinstance(g, (CGate, CGateS)):
143
+ wires = g.controls + g.targets
144
+ for wire in wires:
145
+ if wire in ismeasured and \
146
+ self._gate_grid[i] > self._gate_grid[ismeasured[wire]]:
147
+ ydata = min(wires), max(wires)
148
+ xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy
149
+ line = Line2D(
150
+ xdata, ydata,
151
+ color='k',
152
+ lw=self.linewidth
153
+ )
154
+ self._axes.add_line(line)
155
+ def _gates(self):
156
+ """Create a list of all gates in the circuit plot."""
157
+ gates = []
158
+ if isinstance(self.circuit, Mul):
159
+ for g in reversed(self.circuit.args):
160
+ if isinstance(g, Gate):
161
+ gates.append(g)
162
+ elif isinstance(self.circuit, Gate):
163
+ gates.append(self.circuit)
164
+ return gates
165
+
166
+ def _plot_gates(self):
167
+ """Iterate through the gates and plot each of them."""
168
+ for i, gate in enumerate(self._gates()):
169
+ gate.plot_gate(self, i)
170
+
171
+ def _measurements(self):
172
+ """Return a dict ``{i:j}`` where i is the index of the wire that has
173
+ been measured, and j is the gate where the wire is measured.
174
+ """
175
+ ismeasured = {}
176
+ for i,g in enumerate(self._gates()):
177
+ if getattr(g,'measurement',False):
178
+ for target in g.targets:
179
+ if target in ismeasured:
180
+ if ismeasured[target] > i:
181
+ ismeasured[target] = i
182
+ else:
183
+ ismeasured[target] = i
184
+ return ismeasured
185
+
186
+ def _finish(self):
187
+ # Disable clipping to make panning work well for large circuits.
188
+ for o in self._figure.findobj():
189
+ o.set_clip_on(False)
190
+
191
+ def one_qubit_box(self, t, gate_idx, wire_idx):
192
+ """Draw a box for a single qubit gate."""
193
+ x = self._gate_grid[gate_idx]
194
+ y = self._wire_grid[wire_idx]
195
+ self._axes.text(
196
+ x, y, t,
197
+ color='k',
198
+ ha='center',
199
+ va='center',
200
+ bbox={"ec": 'k', "fc": 'w', "fill": True, "lw": self.linewidth},
201
+ size=self.fontsize
202
+ )
203
+
204
+ def two_qubit_box(self, t, gate_idx, wire_idx):
205
+ """Draw a box for a two qubit gate. Does not work yet.
206
+ """
207
+ # x = self._gate_grid[gate_idx]
208
+ # y = self._wire_grid[wire_idx]+0.5
209
+ print(self._gate_grid)
210
+ print(self._wire_grid)
211
+ # unused:
212
+ # obj = self._axes.text(
213
+ # x, y, t,
214
+ # color='k',
215
+ # ha='center',
216
+ # va='center',
217
+ # bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth),
218
+ # size=self.fontsize
219
+ # )
220
+
221
+ def control_line(self, gate_idx, min_wire, max_wire):
222
+ """Draw a vertical control line."""
223
+ xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx])
224
+ ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire])
225
+ line = Line2D(
226
+ xdata, ydata,
227
+ color='k',
228
+ lw=self.linewidth
229
+ )
230
+ self._axes.add_line(line)
231
+
232
+ def control_point(self, gate_idx, wire_idx):
233
+ """Draw a control point."""
234
+ x = self._gate_grid[gate_idx]
235
+ y = self._wire_grid[wire_idx]
236
+ radius = self.control_radius
237
+ c = Circle(
238
+ (x, y),
239
+ radius*self.scale,
240
+ ec='k',
241
+ fc='k',
242
+ fill=True,
243
+ lw=self.linewidth
244
+ )
245
+ self._axes.add_patch(c)
246
+
247
+ def not_point(self, gate_idx, wire_idx):
248
+ """Draw a NOT gates as the circle with plus in the middle."""
249
+ x = self._gate_grid[gate_idx]
250
+ y = self._wire_grid[wire_idx]
251
+ radius = self.not_radius
252
+ c = Circle(
253
+ (x, y),
254
+ radius,
255
+ ec='k',
256
+ fc='w',
257
+ fill=False,
258
+ lw=self.linewidth
259
+ )
260
+ self._axes.add_patch(c)
261
+ l = Line2D(
262
+ (x, x), (y - radius, y + radius),
263
+ color='k',
264
+ lw=self.linewidth
265
+ )
266
+ self._axes.add_line(l)
267
+
268
+ def swap_point(self, gate_idx, wire_idx):
269
+ """Draw a swap point as a cross."""
270
+ x = self._gate_grid[gate_idx]
271
+ y = self._wire_grid[wire_idx]
272
+ d = self.swap_delta
273
+ l1 = Line2D(
274
+ (x - d, x + d),
275
+ (y - d, y + d),
276
+ color='k',
277
+ lw=self.linewidth
278
+ )
279
+ l2 = Line2D(
280
+ (x - d, x + d),
281
+ (y + d, y - d),
282
+ color='k',
283
+ lw=self.linewidth
284
+ )
285
+ self._axes.add_line(l1)
286
+ self._axes.add_line(l2)
287
+
288
+ def circuit_plot(c, nqubits, **kwargs):
289
+ """Draw the circuit diagram for the circuit with nqubits.
290
+
291
+ Parameters
292
+ ==========
293
+
294
+ c : circuit
295
+ The circuit to plot. Should be a product of Gate instances.
296
+ nqubits : int
297
+ The number of qubits to include in the circuit. Must be at least
298
+ as big as the largest ``min_qubits`` of the gates.
299
+ """
300
+ return CircuitPlot(c, nqubits, **kwargs)
301
+
302
+ def render_label(label, inits={}):
303
+ """Slightly more flexible way to render labels.
304
+
305
+ >>> from sympy.physics.quantum.circuitplot import render_label
306
+ >>> render_label('q0')
307
+ '$\\\\left|q0\\\\right\\\\rangle$'
308
+ >>> render_label('q0', {'q0':'0'})
309
+ '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$'
310
+ """
311
+ init = inits.get(label)
312
+ if init:
313
+ return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init)
314
+ return r'$\left|%s\right\rangle$' % label
315
+
316
+ def labeller(n, symbol='q'):
317
+ """Autogenerate labels for wires of quantum circuits.
318
+
319
+ Parameters
320
+ ==========
321
+
322
+ n : int
323
+ number of qubits in the circuit.
324
+ symbol : string
325
+ A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc.
326
+
327
+ >>> from sympy.physics.quantum.circuitplot import labeller
328
+ >>> labeller(2)
329
+ ['q_1', 'q_0']
330
+ >>> labeller(3,'j')
331
+ ['j_2', 'j_1', 'j_0']
332
+ """
333
+ return ['%s_%d' % (symbol,n-i-1) for i in range(n)]
334
+
335
+ class Mz(OneQubitGate):
336
+ """Mock-up of a z measurement gate.
337
+
338
+ This is in circuitplot rather than gate.py because it's not a real
339
+ gate, it just draws one.
340
+ """
341
+ measurement = True
342
+ gate_name='Mz'
343
+ gate_name_latex='M_z'
344
+
345
+ class Mx(OneQubitGate):
346
+ """Mock-up of an x measurement gate.
347
+
348
+ This is in circuitplot rather than gate.py because it's not a real
349
+ gate, it just draws one.
350
+ """
351
+ measurement = True
352
+ gate_name='Mx'
353
+ gate_name_latex='M_x'
354
+
355
+ class CreateOneQubitGate(type):
356
+ def __new__(mcl, name, latexname=None):
357
+ if not latexname:
358
+ latexname = name
359
+ return type(name + "Gate", (OneQubitGate,),
360
+ {'gate_name': name, 'gate_name_latex': latexname})
361
+
362
+ def CreateCGate(name, latexname=None):
363
+ """Use a lexical closure to make a controlled gate.
364
+ """
365
+ if not latexname:
366
+ latexname = name
367
+ onequbitgate = CreateOneQubitGate(name, latexname)
368
+ def ControlledGate(ctrls,target):
369
+ return CGate(tuple(ctrls),onequbitgate(target))
370
+ return ControlledGate
venv/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Primitive circuit operations on quantum circuits."""
2
+
3
+ from functools import reduce
4
+
5
+ from sympy.core.sorting import default_sort_key
6
+ from sympy.core.containers import Tuple
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.symbol import Symbol
9
+ from sympy.core.sympify import sympify
10
+ from sympy.utilities import numbered_symbols
11
+ from sympy.physics.quantum.gate import Gate
12
+
13
+ __all__ = [
14
+ 'kmp_table',
15
+ 'find_subcircuit',
16
+ 'replace_subcircuit',
17
+ 'convert_to_symbolic_indices',
18
+ 'convert_to_real_indices',
19
+ 'random_reduce',
20
+ 'random_insert'
21
+ ]
22
+
23
+
24
+ def kmp_table(word):
25
+ """Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
26
+
27
+ Note: This is applicable to strings or
28
+ quantum circuits represented as tuples.
29
+ """
30
+
31
+ # Current position in subcircuit
32
+ pos = 2
33
+ # Beginning position of candidate substring that
34
+ # may reappear later in word
35
+ cnd = 0
36
+ # The 'partial match' table that helps one determine
37
+ # the next location to start substring search
38
+ table = []
39
+ table.append(-1)
40
+ table.append(0)
41
+
42
+ while pos < len(word):
43
+ if word[pos - 1] == word[cnd]:
44
+ cnd = cnd + 1
45
+ table.append(cnd)
46
+ pos = pos + 1
47
+ elif cnd > 0:
48
+ cnd = table[cnd]
49
+ else:
50
+ table.append(0)
51
+ pos = pos + 1
52
+
53
+ return table
54
+
55
+
56
+ def find_subcircuit(circuit, subcircuit, start=0, end=0):
57
+ """Finds the subcircuit in circuit, if it exists.
58
+
59
+ Explanation
60
+ ===========
61
+
62
+ If the subcircuit exists, the index of the start of
63
+ the subcircuit in circuit is returned; otherwise,
64
+ -1 is returned. The algorithm that is implemented
65
+ is the Knuth-Morris-Pratt algorithm.
66
+
67
+ Parameters
68
+ ==========
69
+
70
+ circuit : tuple, Gate or Mul
71
+ A tuple of Gates or Mul representing a quantum circuit
72
+ subcircuit : tuple, Gate or Mul
73
+ A tuple of Gates or Mul to find in circuit
74
+ start : int
75
+ The location to start looking for subcircuit.
76
+ If start is the same or past end, -1 is returned.
77
+ end : int
78
+ The last place to look for a subcircuit. If end
79
+ is less than 1 (one), then the length of circuit
80
+ is taken to be end.
81
+
82
+ Examples
83
+ ========
84
+
85
+ Find the first instance of a subcircuit:
86
+
87
+ >>> from sympy.physics.quantum.circuitutils import find_subcircuit
88
+ >>> from sympy.physics.quantum.gate import X, Y, Z, H
89
+ >>> circuit = X(0)*Z(0)*Y(0)*H(0)
90
+ >>> subcircuit = Z(0)*Y(0)
91
+ >>> find_subcircuit(circuit, subcircuit)
92
+ 1
93
+
94
+ Find the first instance starting at a specific position:
95
+
96
+ >>> find_subcircuit(circuit, subcircuit, start=1)
97
+ 1
98
+
99
+ >>> find_subcircuit(circuit, subcircuit, start=2)
100
+ -1
101
+
102
+ >>> circuit = circuit*subcircuit
103
+ >>> find_subcircuit(circuit, subcircuit, start=2)
104
+ 4
105
+
106
+ Find the subcircuit within some interval:
107
+
108
+ >>> find_subcircuit(circuit, subcircuit, start=2, end=2)
109
+ -1
110
+ """
111
+
112
+ if isinstance(circuit, Mul):
113
+ circuit = circuit.args
114
+
115
+ if isinstance(subcircuit, Mul):
116
+ subcircuit = subcircuit.args
117
+
118
+ if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
119
+ return -1
120
+
121
+ if end < 1:
122
+ end = len(circuit)
123
+
124
+ # Location in circuit
125
+ pos = start
126
+ # Location in the subcircuit
127
+ index = 0
128
+ # 'Partial match' table
129
+ table = kmp_table(subcircuit)
130
+
131
+ while (pos + index) < end:
132
+ if subcircuit[index] == circuit[pos + index]:
133
+ index = index + 1
134
+ else:
135
+ pos = pos + index - table[index]
136
+ index = table[index] if table[index] > -1 else 0
137
+
138
+ if index == len(subcircuit):
139
+ return pos
140
+
141
+ return -1
142
+
143
+
144
+ def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
145
+ """Replaces a subcircuit with another subcircuit in circuit,
146
+ if it exists.
147
+
148
+ Explanation
149
+ ===========
150
+
151
+ If multiple instances of subcircuit exists, the first instance is
152
+ replaced. The position to being searching from (if different from
153
+ 0) may be optionally given. If subcircuit cannot be found, circuit
154
+ is returned.
155
+
156
+ Parameters
157
+ ==========
158
+
159
+ circuit : tuple, Gate or Mul
160
+ A quantum circuit.
161
+ subcircuit : tuple, Gate or Mul
162
+ The circuit to be replaced.
163
+ replace : tuple, Gate or Mul
164
+ The replacement circuit.
165
+ pos : int
166
+ The location to start search and replace
167
+ subcircuit, if it exists. This may be used
168
+ if it is known beforehand that multiple
169
+ instances exist, and it is desirable to
170
+ replace a specific instance. If a negative number
171
+ is given, pos will be defaulted to 0.
172
+
173
+ Examples
174
+ ========
175
+
176
+ Find and remove the subcircuit:
177
+
178
+ >>> from sympy.physics.quantum.circuitutils import replace_subcircuit
179
+ >>> from sympy.physics.quantum.gate import X, Y, Z, H
180
+ >>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
181
+ >>> subcircuit = Z(0)*Y(0)
182
+ >>> replace_subcircuit(circuit, subcircuit)
183
+ (X(0), H(0), X(0), H(0), Y(0))
184
+
185
+ Remove the subcircuit given a starting search point:
186
+
187
+ >>> replace_subcircuit(circuit, subcircuit, pos=1)
188
+ (X(0), H(0), X(0), H(0), Y(0))
189
+
190
+ >>> replace_subcircuit(circuit, subcircuit, pos=2)
191
+ (X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
192
+
193
+ Replace the subcircuit:
194
+
195
+ >>> replacement = H(0)*Z(0)
196
+ >>> replace_subcircuit(circuit, subcircuit, replace=replacement)
197
+ (X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
198
+ """
199
+
200
+ if pos < 0:
201
+ pos = 0
202
+
203
+ if isinstance(circuit, Mul):
204
+ circuit = circuit.args
205
+
206
+ if isinstance(subcircuit, Mul):
207
+ subcircuit = subcircuit.args
208
+
209
+ if isinstance(replace, Mul):
210
+ replace = replace.args
211
+ elif replace is None:
212
+ replace = ()
213
+
214
+ # Look for the subcircuit starting at pos
215
+ loc = find_subcircuit(circuit, subcircuit, start=pos)
216
+
217
+ # If subcircuit was found
218
+ if loc > -1:
219
+ # Get the gates to the left of subcircuit
220
+ left = circuit[0:loc]
221
+ # Get the gates to the right of subcircuit
222
+ right = circuit[loc + len(subcircuit):len(circuit)]
223
+ # Recombine the left and right side gates into a circuit
224
+ circuit = left + replace + right
225
+
226
+ return circuit
227
+
228
+
229
+ def _sympify_qubit_map(mapping):
230
+ new_map = {}
231
+ for key in mapping:
232
+ new_map[key] = sympify(mapping[key])
233
+ return new_map
234
+
235
+
236
+ def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
237
+ """Returns the circuit with symbolic indices and the
238
+ dictionary mapping symbolic indices to real indices.
239
+
240
+ The mapping is 1 to 1 and onto (bijective).
241
+
242
+ Parameters
243
+ ==========
244
+
245
+ seq : tuple, Gate/Integer/tuple or Mul
246
+ A tuple of Gate, Integer, or tuple objects, or a Mul
247
+ start : Symbol
248
+ An optional starting symbolic index
249
+ gen : object
250
+ An optional numbered symbol generator
251
+ qubit_map : dict
252
+ An existing mapping of symbolic indices to real indices
253
+
254
+ All symbolic indices have the format 'i#', where # is
255
+ some number >= 0.
256
+ """
257
+
258
+ if isinstance(seq, Mul):
259
+ seq = seq.args
260
+
261
+ # A numbered symbol generator
262
+ index_gen = numbered_symbols(prefix='i', start=-1)
263
+ cur_ndx = next(index_gen)
264
+
265
+ # keys are symbolic indices; values are real indices
266
+ ndx_map = {}
267
+
268
+ def create_inverse_map(symb_to_real_map):
269
+ rev_items = lambda item: (item[1], item[0])
270
+ return dict(map(rev_items, symb_to_real_map.items()))
271
+
272
+ if start is not None:
273
+ if not isinstance(start, Symbol):
274
+ msg = 'Expected Symbol for starting index, got %r.' % start
275
+ raise TypeError(msg)
276
+ cur_ndx = start
277
+
278
+ if gen is not None:
279
+ if not isinstance(gen, numbered_symbols().__class__):
280
+ msg = 'Expected a generator, got %r.' % gen
281
+ raise TypeError(msg)
282
+ index_gen = gen
283
+
284
+ if qubit_map is not None:
285
+ if not isinstance(qubit_map, dict):
286
+ msg = ('Expected dict for existing map, got ' +
287
+ '%r.' % qubit_map)
288
+ raise TypeError(msg)
289
+ ndx_map = qubit_map
290
+
291
+ ndx_map = _sympify_qubit_map(ndx_map)
292
+ # keys are real indices; keys are symbolic indices
293
+ inv_map = create_inverse_map(ndx_map)
294
+
295
+ sym_seq = ()
296
+ for item in seq:
297
+ # Nested items, so recurse
298
+ if isinstance(item, Gate):
299
+ result = convert_to_symbolic_indices(item.args,
300
+ qubit_map=ndx_map,
301
+ start=cur_ndx,
302
+ gen=index_gen)
303
+ sym_item, new_map, cur_ndx, index_gen = result
304
+ ndx_map.update(new_map)
305
+ inv_map = create_inverse_map(ndx_map)
306
+
307
+ elif isinstance(item, (tuple, Tuple)):
308
+ result = convert_to_symbolic_indices(item,
309
+ qubit_map=ndx_map,
310
+ start=cur_ndx,
311
+ gen=index_gen)
312
+ sym_item, new_map, cur_ndx, index_gen = result
313
+ ndx_map.update(new_map)
314
+ inv_map = create_inverse_map(ndx_map)
315
+
316
+ elif item in inv_map:
317
+ sym_item = inv_map[item]
318
+
319
+ else:
320
+ cur_ndx = next(gen)
321
+ ndx_map[cur_ndx] = item
322
+ inv_map[item] = cur_ndx
323
+ sym_item = cur_ndx
324
+
325
+ if isinstance(item, Gate):
326
+ sym_item = item.__class__(*sym_item)
327
+
328
+ sym_seq = sym_seq + (sym_item,)
329
+
330
+ return sym_seq, ndx_map, cur_ndx, index_gen
331
+
332
+
333
+ def convert_to_real_indices(seq, qubit_map):
334
+ """Returns the circuit with real indices.
335
+
336
+ Parameters
337
+ ==========
338
+
339
+ seq : tuple, Gate/Integer/tuple or Mul
340
+ A tuple of Gate, Integer, or tuple objects or a Mul
341
+ qubit_map : dict
342
+ A dictionary mapping symbolic indices to real indices.
343
+
344
+ Examples
345
+ ========
346
+
347
+ Change the symbolic indices to real integers:
348
+
349
+ >>> from sympy import symbols
350
+ >>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
351
+ >>> from sympy.physics.quantum.gate import X, Y, H
352
+ >>> i0, i1 = symbols('i:2')
353
+ >>> index_map = {i0 : 0, i1 : 1}
354
+ >>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
355
+ (X(0), Y(1), H(0), X(1))
356
+ """
357
+
358
+ if isinstance(seq, Mul):
359
+ seq = seq.args
360
+
361
+ if not isinstance(qubit_map, dict):
362
+ msg = 'Expected dict for qubit_map, got %r.' % qubit_map
363
+ raise TypeError(msg)
364
+
365
+ qubit_map = _sympify_qubit_map(qubit_map)
366
+ real_seq = ()
367
+ for item in seq:
368
+ # Nested items, so recurse
369
+ if isinstance(item, Gate):
370
+ real_item = convert_to_real_indices(item.args, qubit_map)
371
+
372
+ elif isinstance(item, (tuple, Tuple)):
373
+ real_item = convert_to_real_indices(item, qubit_map)
374
+
375
+ else:
376
+ real_item = qubit_map[item]
377
+
378
+ if isinstance(item, Gate):
379
+ real_item = item.__class__(*real_item)
380
+
381
+ real_seq = real_seq + (real_item,)
382
+
383
+ return real_seq
384
+
385
+
386
+ def random_reduce(circuit, gate_ids, seed=None):
387
+ """Shorten the length of a quantum circuit.
388
+
389
+ Explanation
390
+ ===========
391
+
392
+ random_reduce looks for circuit identities in circuit, randomly chooses
393
+ one to remove, and returns a shorter yet equivalent circuit. If no
394
+ identities are found, the same circuit is returned.
395
+
396
+ Parameters
397
+ ==========
398
+
399
+ circuit : Gate tuple of Mul
400
+ A tuple of Gates representing a quantum circuit
401
+ gate_ids : list, GateIdentity
402
+ List of gate identities to find in circuit
403
+ seed : int or list
404
+ seed used for _randrange; to override the random selection, provide a
405
+ list of integers: the elements of gate_ids will be tested in the order
406
+ given by the list
407
+
408
+ """
409
+ from sympy.core.random import _randrange
410
+
411
+ if not gate_ids:
412
+ return circuit
413
+
414
+ if isinstance(circuit, Mul):
415
+ circuit = circuit.args
416
+
417
+ ids = flatten_ids(gate_ids)
418
+
419
+ # Create the random integer generator with the seed
420
+ randrange = _randrange(seed)
421
+
422
+ # Look for an identity in the circuit
423
+ while ids:
424
+ i = randrange(len(ids))
425
+ id = ids.pop(i)
426
+ if find_subcircuit(circuit, id) != -1:
427
+ break
428
+ else:
429
+ # no identity was found
430
+ return circuit
431
+
432
+ # return circuit with the identity removed
433
+ return replace_subcircuit(circuit, id)
434
+
435
+
436
+ def random_insert(circuit, choices, seed=None):
437
+ """Insert a circuit into another quantum circuit.
438
+
439
+ Explanation
440
+ ===========
441
+
442
+ random_insert randomly chooses a location in the circuit to insert
443
+ a randomly selected circuit from amongst the given choices.
444
+
445
+ Parameters
446
+ ==========
447
+
448
+ circuit : Gate tuple or Mul
449
+ A tuple or Mul of Gates representing a quantum circuit
450
+ choices : list
451
+ Set of circuit choices
452
+ seed : int or list
453
+ seed used for _randrange; to override the random selections, give
454
+ a list two integers, [i, j] where i is the circuit location where
455
+ choice[j] will be inserted.
456
+
457
+ Notes
458
+ =====
459
+
460
+ Indices for insertion should be [0, n] if n is the length of the
461
+ circuit.
462
+ """
463
+ from sympy.core.random import _randrange
464
+
465
+ if not choices:
466
+ return circuit
467
+
468
+ if isinstance(circuit, Mul):
469
+ circuit = circuit.args
470
+
471
+ # get the location in the circuit and the element to insert from choices
472
+ randrange = _randrange(seed)
473
+ loc = randrange(len(circuit) + 1)
474
+ choice = choices[randrange(len(choices))]
475
+
476
+ circuit = list(circuit)
477
+ circuit[loc: loc] = choice
478
+ return tuple(circuit)
479
+
480
+ # Flatten the GateIdentity objects (with gate rules) into one single list
481
+
482
+
483
+ def flatten_ids(ids):
484
+ collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
485
+ key=default_sort_key)
486
+ ids = reduce(collapse, ids, [])
487
+ ids.sort(key=default_sort_key)
488
+ return ids
venv/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The commutator: [A,B] = A*B - B*A."""
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.printing.pretty.stringpict import prettyForm
9
+
10
+ from sympy.physics.quantum.dagger import Dagger
11
+ from sympy.physics.quantum.operator import Operator
12
+
13
+
14
+ __all__ = [
15
+ 'Commutator'
16
+ ]
17
+
18
+ #-----------------------------------------------------------------------------
19
+ # Commutator
20
+ #-----------------------------------------------------------------------------
21
+
22
+
23
+ class Commutator(Expr):
24
+ """The standard commutator, in an unevaluated state.
25
+
26
+ Explanation
27
+ ===========
28
+
29
+ Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
30
+ class returns the commutator in an unevaluated form. To evaluate the
31
+ commutator, use the ``.doit()`` method.
32
+
33
+ Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
34
+ arguments of the commutator are put into canonical order using ``__cmp__``.
35
+ If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
36
+
37
+ Parameters
38
+ ==========
39
+
40
+ A : Expr
41
+ The first argument of the commutator [A,B].
42
+ B : Expr
43
+ The second argument of the commutator [A,B].
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy.physics.quantum import Commutator, Dagger, Operator
49
+ >>> from sympy.abc import x, y
50
+ >>> A = Operator('A')
51
+ >>> B = Operator('B')
52
+ >>> C = Operator('C')
53
+
54
+ Create a commutator and use ``.doit()`` to evaluate it:
55
+
56
+ >>> comm = Commutator(A, B)
57
+ >>> comm
58
+ [A,B]
59
+ >>> comm.doit()
60
+ A*B - B*A
61
+
62
+ The commutator orders it arguments in canonical order:
63
+
64
+ >>> comm = Commutator(B, A); comm
65
+ -[A,B]
66
+
67
+ Commutative constants are factored out:
68
+
69
+ >>> Commutator(3*x*A, x*y*B)
70
+ 3*x**2*y*[A,B]
71
+
72
+ Using ``.expand(commutator=True)``, the standard commutator expansion rules
73
+ can be applied:
74
+
75
+ >>> Commutator(A+B, C).expand(commutator=True)
76
+ [A,C] + [B,C]
77
+ >>> Commutator(A, B+C).expand(commutator=True)
78
+ [A,B] + [A,C]
79
+ >>> Commutator(A*B, C).expand(commutator=True)
80
+ [A,C]*B + A*[B,C]
81
+ >>> Commutator(A, B*C).expand(commutator=True)
82
+ [A,B]*C + B*[A,C]
83
+
84
+ Adjoint operations applied to the commutator are properly applied to the
85
+ arguments:
86
+
87
+ >>> Dagger(Commutator(A, B))
88
+ -[Dagger(A),Dagger(B)]
89
+
90
+ References
91
+ ==========
92
+
93
+ .. [1] https://en.wikipedia.org/wiki/Commutator
94
+ """
95
+ is_commutative = False
96
+
97
+ def __new__(cls, A, B):
98
+ r = cls.eval(A, B)
99
+ if r is not None:
100
+ return r
101
+ obj = Expr.__new__(cls, A, B)
102
+ return obj
103
+
104
+ @classmethod
105
+ def eval(cls, a, b):
106
+ if not (a and b):
107
+ return S.Zero
108
+ if a == b:
109
+ return S.Zero
110
+ if a.is_commutative or b.is_commutative:
111
+ return S.Zero
112
+
113
+ # [xA,yB] -> xy*[A,B]
114
+ ca, nca = a.args_cnc()
115
+ cb, ncb = b.args_cnc()
116
+ c_part = ca + cb
117
+ if c_part:
118
+ return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
119
+
120
+ # Canonical ordering of arguments
121
+ # The Commutator [A, B] is in canonical form if A < B.
122
+ if a.compare(b) == 1:
123
+ return S.NegativeOne*cls(b, a)
124
+
125
+ def _expand_pow(self, A, B, sign):
126
+ exp = A.exp
127
+ if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
128
+ # nothing to do
129
+ return self
130
+ base = A.base
131
+ if exp.is_negative:
132
+ base = A.base**-1
133
+ exp = -exp
134
+ comm = Commutator(base, B).expand(commutator=True)
135
+
136
+ result = base**(exp - 1) * comm
137
+ for i in range(1, exp):
138
+ result += base**(exp - 1 - i) * comm * base**i
139
+ return sign*result.expand()
140
+
141
+ def _eval_expand_commutator(self, **hints):
142
+ A = self.args[0]
143
+ B = self.args[1]
144
+
145
+ if isinstance(A, Add):
146
+ # [A + B, C] -> [A, C] + [B, C]
147
+ sargs = []
148
+ for term in A.args:
149
+ comm = Commutator(term, B)
150
+ if isinstance(comm, Commutator):
151
+ comm = comm._eval_expand_commutator()
152
+ sargs.append(comm)
153
+ return Add(*sargs)
154
+ elif isinstance(B, Add):
155
+ # [A, B + C] -> [A, B] + [A, C]
156
+ sargs = []
157
+ for term in B.args:
158
+ comm = Commutator(A, term)
159
+ if isinstance(comm, Commutator):
160
+ comm = comm._eval_expand_commutator()
161
+ sargs.append(comm)
162
+ return Add(*sargs)
163
+ elif isinstance(A, Mul):
164
+ # [A*B, C] -> A*[B, C] + [A, C]*B
165
+ a = A.args[0]
166
+ b = Mul(*A.args[1:])
167
+ c = B
168
+ comm1 = Commutator(b, c)
169
+ comm2 = Commutator(a, c)
170
+ if isinstance(comm1, Commutator):
171
+ comm1 = comm1._eval_expand_commutator()
172
+ if isinstance(comm2, Commutator):
173
+ comm2 = comm2._eval_expand_commutator()
174
+ first = Mul(a, comm1)
175
+ second = Mul(comm2, b)
176
+ return Add(first, second)
177
+ elif isinstance(B, Mul):
178
+ # [A, B*C] -> [A, B]*C + B*[A, C]
179
+ a = A
180
+ b = B.args[0]
181
+ c = Mul(*B.args[1:])
182
+ comm1 = Commutator(a, b)
183
+ comm2 = Commutator(a, c)
184
+ if isinstance(comm1, Commutator):
185
+ comm1 = comm1._eval_expand_commutator()
186
+ if isinstance(comm2, Commutator):
187
+ comm2 = comm2._eval_expand_commutator()
188
+ first = Mul(comm1, c)
189
+ second = Mul(b, comm2)
190
+ return Add(first, second)
191
+ elif isinstance(A, Pow):
192
+ # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
193
+ return self._expand_pow(A, B, 1)
194
+ elif isinstance(B, Pow):
195
+ # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
196
+ return self._expand_pow(B, A, -1)
197
+
198
+ # No changes, so return self
199
+ return self
200
+
201
+ def doit(self, **hints):
202
+ """ Evaluate commutator """
203
+ A = self.args[0]
204
+ B = self.args[1]
205
+ if isinstance(A, Operator) and isinstance(B, Operator):
206
+ try:
207
+ comm = A._eval_commutator(B, **hints)
208
+ except NotImplementedError:
209
+ try:
210
+ comm = -1*B._eval_commutator(A, **hints)
211
+ except NotImplementedError:
212
+ comm = None
213
+ if comm is not None:
214
+ return comm.doit(**hints)
215
+ return (A*B - B*A).doit(**hints)
216
+
217
+ def _eval_adjoint(self):
218
+ return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
219
+
220
+ def _sympyrepr(self, printer, *args):
221
+ return "%s(%s,%s)" % (
222
+ self.__class__.__name__, printer._print(
223
+ self.args[0]), printer._print(self.args[1])
224
+ )
225
+
226
+ def _sympystr(self, printer, *args):
227
+ return "[%s,%s]" % (
228
+ printer._print(self.args[0]), printer._print(self.args[1]))
229
+
230
+ def _pretty(self, printer, *args):
231
+ pform = printer._print(self.args[0], *args)
232
+ pform = prettyForm(*pform.right(prettyForm(',')))
233
+ pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
234
+ pform = prettyForm(*pform.parens(left='[', right=']'))
235
+ return pform
236
+
237
+ def _latex(self, printer, *args):
238
+ return "\\left[%s,%s\\right]" % tuple([
239
+ printer._print(arg, *args) for arg in self.args])
venv/lib/python3.10/site-packages/sympy/physics/quantum/constants.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Constants (like hbar) related to quantum mechanics."""
2
+
3
+ from sympy.core.numbers import NumberSymbol
4
+ from sympy.core.singleton import Singleton
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ import mpmath.libmp as mlib
7
+
8
+ #-----------------------------------------------------------------------------
9
+ # Constants
10
+ #-----------------------------------------------------------------------------
11
+
12
+ __all__ = [
13
+ 'hbar',
14
+ 'HBar',
15
+ ]
16
+
17
+
18
+ class HBar(NumberSymbol, metaclass=Singleton):
19
+ """Reduced Plank's constant in numerical and symbolic form [1]_.
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.physics.quantum.constants import hbar
25
+ >>> hbar.evalf()
26
+ 1.05457162000000e-34
27
+
28
+ References
29
+ ==========
30
+
31
+ .. [1] https://en.wikipedia.org/wiki/Planck_constant
32
+ """
33
+
34
+ is_real = True
35
+ is_positive = True
36
+ is_negative = False
37
+ is_irrational = True
38
+
39
+ __slots__ = ()
40
+
41
+ def _as_mpf_val(self, prec):
42
+ return mlib.from_float(1.05457162e-34, prec)
43
+
44
+ def _sympyrepr(self, printer, *args):
45
+ return 'HBar()'
46
+
47
+ def _sympystr(self, printer, *args):
48
+ return 'hbar'
49
+
50
+ def _pretty(self, printer, *args):
51
+ if printer._use_unicode:
52
+ return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}')
53
+ return prettyForm('hbar')
54
+
55
+ def _latex(self, printer, *args):
56
+ return r'\hbar'
57
+
58
+ # Create an instance for everyone to use.
59
+ hbar = HBar()
venv/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hermitian conjugation."""
2
+
3
+ from sympy.core import Expr, Mul
4
+ from sympy.functions.elementary.complexes import adjoint
5
+
6
+ __all__ = [
7
+ 'Dagger'
8
+ ]
9
+
10
+
11
+ class Dagger(adjoint):
12
+ """General Hermitian conjugate operation.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ Take the Hermetian conjugate of an argument [1]_. For matrices this
18
+ operation is equivalent to transpose and complex conjugate [2]_.
19
+
20
+ Parameters
21
+ ==========
22
+
23
+ arg : Expr
24
+ The SymPy expression that we want to take the dagger of.
25
+
26
+ Examples
27
+ ========
28
+
29
+ Daggering various quantum objects:
30
+
31
+ >>> from sympy.physics.quantum.dagger import Dagger
32
+ >>> from sympy.physics.quantum.state import Ket, Bra
33
+ >>> from sympy.physics.quantum.operator import Operator
34
+ >>> Dagger(Ket('psi'))
35
+ <psi|
36
+ >>> Dagger(Bra('phi'))
37
+ |phi>
38
+ >>> Dagger(Operator('A'))
39
+ Dagger(A)
40
+
41
+ Inner and outer products::
42
+
43
+ >>> from sympy.physics.quantum import InnerProduct, OuterProduct
44
+ >>> Dagger(InnerProduct(Bra('a'), Ket('b')))
45
+ <b|a>
46
+ >>> Dagger(OuterProduct(Ket('a'), Bra('b')))
47
+ |b><a|
48
+
49
+ Powers, sums and products::
50
+
51
+ >>> A = Operator('A')
52
+ >>> B = Operator('B')
53
+ >>> Dagger(A*B)
54
+ Dagger(B)*Dagger(A)
55
+ >>> Dagger(A+B)
56
+ Dagger(A) + Dagger(B)
57
+ >>> Dagger(A**2)
58
+ Dagger(A)**2
59
+
60
+ Dagger also seamlessly handles complex numbers and matrices::
61
+
62
+ >>> from sympy import Matrix, I
63
+ >>> m = Matrix([[1,I],[2,I]])
64
+ >>> m
65
+ Matrix([
66
+ [1, I],
67
+ [2, I]])
68
+ >>> Dagger(m)
69
+ Matrix([
70
+ [ 1, 2],
71
+ [-I, -I]])
72
+
73
+ References
74
+ ==========
75
+
76
+ .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
77
+ .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
78
+ """
79
+
80
+ def __new__(cls, arg):
81
+ if hasattr(arg, 'adjoint'):
82
+ obj = arg.adjoint()
83
+ elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose'):
84
+ obj = arg.conjugate().transpose()
85
+ if obj is not None:
86
+ return obj
87
+ return Expr.__new__(cls, arg)
88
+
89
+ def __mul__(self, other):
90
+ from sympy.physics.quantum import IdentityOperator
91
+ if isinstance(other, IdentityOperator):
92
+ return self
93
+
94
+ return Mul(self, other)
95
+
96
+ adjoint.__name__ = "Dagger"
97
+ adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
venv/lib/python3.10/site-packages/sympy/physics/quantum/density.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.function import expand
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.singleton import S
8
+ from sympy.functions.elementary.exponential import log
9
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
10
+ from sympy.printing.pretty.stringpict import prettyForm
11
+ from sympy.physics.quantum.dagger import Dagger
12
+ from sympy.physics.quantum.operator import HermitianOperator
13
+ from sympy.physics.quantum.represent import represent
14
+ from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy
15
+ from sympy.physics.quantum.tensorproduct import TensorProduct, tensor_product_simp
16
+ from sympy.physics.quantum.trace import Tr
17
+
18
+
19
+ class Density(HermitianOperator):
20
+ """Density operator for representing mixed states.
21
+
22
+ TODO: Density operator support for Qubits
23
+
24
+ Parameters
25
+ ==========
26
+
27
+ values : tuples/lists
28
+ Each tuple/list should be of form (state, prob) or [state,prob]
29
+
30
+ Examples
31
+ ========
32
+
33
+ Create a density operator with 2 states represented by Kets.
34
+
35
+ >>> from sympy.physics.quantum.state import Ket
36
+ >>> from sympy.physics.quantum.density import Density
37
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
38
+ >>> d
39
+ Density((|0>, 0.5),(|1>, 0.5))
40
+
41
+ """
42
+ @classmethod
43
+ def _eval_args(cls, args):
44
+ # call this to qsympify the args
45
+ args = super()._eval_args(args)
46
+
47
+ for arg in args:
48
+ # Check if arg is a tuple
49
+ if not (isinstance(arg, Tuple) and len(arg) == 2):
50
+ raise ValueError("Each argument should be of form [state,prob]"
51
+ " or ( state, prob )")
52
+
53
+ return args
54
+
55
+ def states(self):
56
+ """Return list of all states.
57
+
58
+ Examples
59
+ ========
60
+
61
+ >>> from sympy.physics.quantum.state import Ket
62
+ >>> from sympy.physics.quantum.density import Density
63
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
64
+ >>> d.states()
65
+ (|0>, |1>)
66
+
67
+ """
68
+ return Tuple(*[arg[0] for arg in self.args])
69
+
70
+ def probs(self):
71
+ """Return list of all probabilities.
72
+
73
+ Examples
74
+ ========
75
+
76
+ >>> from sympy.physics.quantum.state import Ket
77
+ >>> from sympy.physics.quantum.density import Density
78
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
79
+ >>> d.probs()
80
+ (0.5, 0.5)
81
+
82
+ """
83
+ return Tuple(*[arg[1] for arg in self.args])
84
+
85
+ def get_state(self, index):
86
+ """Return specific state by index.
87
+
88
+ Parameters
89
+ ==========
90
+
91
+ index : index of state to be returned
92
+
93
+ Examples
94
+ ========
95
+
96
+ >>> from sympy.physics.quantum.state import Ket
97
+ >>> from sympy.physics.quantum.density import Density
98
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
99
+ >>> d.states()[1]
100
+ |1>
101
+
102
+ """
103
+ state = self.args[index][0]
104
+ return state
105
+
106
+ def get_prob(self, index):
107
+ """Return probability of specific state by index.
108
+
109
+ Parameters
110
+ ===========
111
+
112
+ index : index of states whose probability is returned.
113
+
114
+ Examples
115
+ ========
116
+
117
+ >>> from sympy.physics.quantum.state import Ket
118
+ >>> from sympy.physics.quantum.density import Density
119
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
120
+ >>> d.probs()[1]
121
+ 0.500000000000000
122
+
123
+ """
124
+ prob = self.args[index][1]
125
+ return prob
126
+
127
+ def apply_op(self, op):
128
+ """op will operate on each individual state.
129
+
130
+ Parameters
131
+ ==========
132
+
133
+ op : Operator
134
+
135
+ Examples
136
+ ========
137
+
138
+ >>> from sympy.physics.quantum.state import Ket
139
+ >>> from sympy.physics.quantum.density import Density
140
+ >>> from sympy.physics.quantum.operator import Operator
141
+ >>> A = Operator('A')
142
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
143
+ >>> d.apply_op(A)
144
+ Density((A*|0>, 0.5),(A*|1>, 0.5))
145
+
146
+ """
147
+ new_args = [(op*state, prob) for (state, prob) in self.args]
148
+ return Density(*new_args)
149
+
150
+ def doit(self, **hints):
151
+ """Expand the density operator into an outer product format.
152
+
153
+ Examples
154
+ ========
155
+
156
+ >>> from sympy.physics.quantum.state import Ket
157
+ >>> from sympy.physics.quantum.density import Density
158
+ >>> from sympy.physics.quantum.operator import Operator
159
+ >>> A = Operator('A')
160
+ >>> d = Density([Ket(0), 0.5], [Ket(1),0.5])
161
+ >>> d.doit()
162
+ 0.5*|0><0| + 0.5*|1><1|
163
+
164
+ """
165
+
166
+ terms = []
167
+ for (state, prob) in self.args:
168
+ state = state.expand() # needed to break up (a+b)*c
169
+ if (isinstance(state, Add)):
170
+ for arg in product(state.args, repeat=2):
171
+ terms.append(prob*self._generate_outer_prod(arg[0],
172
+ arg[1]))
173
+ else:
174
+ terms.append(prob*self._generate_outer_prod(state, state))
175
+
176
+ return Add(*terms)
177
+
178
+ def _generate_outer_prod(self, arg1, arg2):
179
+ c_part1, nc_part1 = arg1.args_cnc()
180
+ c_part2, nc_part2 = arg2.args_cnc()
181
+
182
+ if (len(nc_part1) == 0 or len(nc_part2) == 0):
183
+ raise ValueError('Atleast one-pair of'
184
+ ' Non-commutative instance required'
185
+ ' for outer product.')
186
+
187
+ # Muls of Tensor Products should be expanded
188
+ # before this function is called
189
+ if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1
190
+ and len(nc_part2) == 1):
191
+ op = tensor_product_simp(nc_part1[0]*Dagger(nc_part2[0]))
192
+ else:
193
+ op = Mul(*nc_part1)*Dagger(Mul(*nc_part2))
194
+
195
+ return Mul(*c_part1)*Mul(*c_part2) * op
196
+
197
+ def _represent(self, **options):
198
+ return represent(self.doit(), **options)
199
+
200
+ def _print_operator_name_latex(self, printer, *args):
201
+ return r'\rho'
202
+
203
+ def _print_operator_name_pretty(self, printer, *args):
204
+ return prettyForm('\N{GREEK SMALL LETTER RHO}')
205
+
206
+ def _eval_trace(self, **kwargs):
207
+ indices = kwargs.get('indices', [])
208
+ return Tr(self.doit(), indices).doit()
209
+
210
+ def entropy(self):
211
+ """ Compute the entropy of a density matrix.
212
+
213
+ Refer to density.entropy() method for examples.
214
+ """
215
+ return entropy(self)
216
+
217
+
218
+ def entropy(density):
219
+ """Compute the entropy of a matrix/density object.
220
+
221
+ This computes -Tr(density*ln(density)) using the eigenvalue decomposition
222
+ of density, which is given as either a Density instance or a matrix
223
+ (numpy.ndarray, sympy.Matrix or scipy.sparse).
224
+
225
+ Parameters
226
+ ==========
227
+
228
+ density : density matrix of type Density, SymPy matrix,
229
+ scipy.sparse or numpy.ndarray
230
+
231
+ Examples
232
+ ========
233
+
234
+ >>> from sympy.physics.quantum.density import Density, entropy
235
+ >>> from sympy.physics.quantum.spin import JzKet
236
+ >>> from sympy import S
237
+ >>> up = JzKet(S(1)/2,S(1)/2)
238
+ >>> down = JzKet(S(1)/2,-S(1)/2)
239
+ >>> d = Density((up,S(1)/2),(down,S(1)/2))
240
+ >>> entropy(d)
241
+ log(2)/2
242
+
243
+ """
244
+ if isinstance(density, Density):
245
+ density = represent(density) # represent in Matrix
246
+
247
+ if isinstance(density, scipy_sparse_matrix):
248
+ density = to_numpy(density)
249
+
250
+ if isinstance(density, Matrix):
251
+ eigvals = density.eigenvals().keys()
252
+ return expand(-sum(e*log(e) for e in eigvals))
253
+ elif isinstance(density, numpy_ndarray):
254
+ import numpy as np
255
+ eigvals = np.linalg.eigvals(density)
256
+ return -np.sum(eigvals*np.log(eigvals))
257
+ else:
258
+ raise ValueError(
259
+ "numpy.ndarray, scipy.sparse or SymPy matrix expected")
260
+
261
+
262
+ def fidelity(state1, state2):
263
+ """ Computes the fidelity [1]_ between two quantum states
264
+
265
+ The arguments provided to this function should be a square matrix or a
266
+ Density object. If it is a square matrix, it is assumed to be diagonalizable.
267
+
268
+ Parameters
269
+ ==========
270
+
271
+ state1, state2 : a density matrix or Matrix
272
+
273
+
274
+ Examples
275
+ ========
276
+
277
+ >>> from sympy import S, sqrt
278
+ >>> from sympy.physics.quantum.dagger import Dagger
279
+ >>> from sympy.physics.quantum.spin import JzKet
280
+ >>> from sympy.physics.quantum.density import fidelity
281
+ >>> from sympy.physics.quantum.represent import represent
282
+ >>>
283
+ >>> up = JzKet(S(1)/2,S(1)/2)
284
+ >>> down = JzKet(S(1)/2,-S(1)/2)
285
+ >>> amp = 1/sqrt(2)
286
+ >>> updown = (amp*up) + (amp*down)
287
+ >>>
288
+ >>> # represent turns Kets into matrices
289
+ >>> up_dm = represent(up*Dagger(up))
290
+ >>> down_dm = represent(down*Dagger(down))
291
+ >>> updown_dm = represent(updown*Dagger(updown))
292
+ >>>
293
+ >>> fidelity(up_dm, up_dm)
294
+ 1
295
+ >>> fidelity(up_dm, down_dm) #orthogonal states
296
+ 0
297
+ >>> fidelity(up_dm, updown_dm).evalf().round(3)
298
+ 0.707
299
+
300
+ References
301
+ ==========
302
+
303
+ .. [1] https://en.wikipedia.org/wiki/Fidelity_of_quantum_states
304
+
305
+ """
306
+ state1 = represent(state1) if isinstance(state1, Density) else state1
307
+ state2 = represent(state2) if isinstance(state2, Density) else state2
308
+
309
+ if not isinstance(state1, Matrix) or not isinstance(state2, Matrix):
310
+ raise ValueError("state1 and state2 must be of type Density or Matrix "
311
+ "received type=%s for state1 and type=%s for state2" %
312
+ (type(state1), type(state2)))
313
+
314
+ if state1.shape != state2.shape and state1.is_square:
315
+ raise ValueError("The dimensions of both args should be equal and the "
316
+ "matrix obtained should be a square matrix")
317
+
318
+ sqrt_state1 = state1**S.Half
319
+ return Tr((sqrt_state1*state2*sqrt_state1)**S.Half).doit()
venv/lib/python3.10/site-packages/sympy/physics/quantum/gate.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An implementation of gates that act on qubits.
2
+
3
+ Gates are unitary operators that act on the space of qubits.
4
+
5
+ Medium Term Todo:
6
+
7
+ * Optimize Gate._apply_operators_Qubit to remove the creation of many
8
+ intermediate Qubit objects.
9
+ * Add commutation relationships to all operators and use this in gate_sort.
10
+ * Fix gate_sort and gate_simp.
11
+ * Get multi-target UGates plotting properly.
12
+ * Get UGate to work with either sympy/numpy matrices and output either
13
+ format. This should also use the matrix slots.
14
+ """
15
+
16
+ from itertools import chain
17
+ import random
18
+
19
+ from sympy.core.add import Add
20
+ from sympy.core.containers import Tuple
21
+ from sympy.core.mul import Mul
22
+ from sympy.core.numbers import (I, Integer)
23
+ from sympy.core.power import Pow
24
+ from sympy.core.numbers import Number
25
+ from sympy.core.singleton import S as _S
26
+ from sympy.core.sorting import default_sort_key
27
+ from sympy.core.sympify import _sympify
28
+ from sympy.functions.elementary.miscellaneous import sqrt
29
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
30
+
31
+ from sympy.physics.quantum.anticommutator import AntiCommutator
32
+ from sympy.physics.quantum.commutator import Commutator
33
+ from sympy.physics.quantum.qexpr import QuantumError
34
+ from sympy.physics.quantum.hilbert import ComplexSpace
35
+ from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
36
+ HermitianOperator)
37
+ from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
38
+ from sympy.physics.quantum.matrixcache import matrix_cache
39
+
40
+ from sympy.matrices.matrices import MatrixBase
41
+
42
+ from sympy.utilities.iterables import is_sequence
43
+
44
+ __all__ = [
45
+ 'Gate',
46
+ 'CGate',
47
+ 'UGate',
48
+ 'OneQubitGate',
49
+ 'TwoQubitGate',
50
+ 'IdentityGate',
51
+ 'HadamardGate',
52
+ 'XGate',
53
+ 'YGate',
54
+ 'ZGate',
55
+ 'TGate',
56
+ 'PhaseGate',
57
+ 'SwapGate',
58
+ 'CNotGate',
59
+ # Aliased gate names
60
+ 'CNOT',
61
+ 'SWAP',
62
+ 'H',
63
+ 'X',
64
+ 'Y',
65
+ 'Z',
66
+ 'T',
67
+ 'S',
68
+ 'Phase',
69
+ 'normalized',
70
+ 'gate_sort',
71
+ 'gate_simp',
72
+ 'random_circuit',
73
+ 'CPHASE',
74
+ 'CGateS',
75
+ ]
76
+
77
+ #-----------------------------------------------------------------------------
78
+ # Gate Super-Classes
79
+ #-----------------------------------------------------------------------------
80
+
81
+ _normalized = True
82
+
83
+
84
+ def _max(*args, **kwargs):
85
+ if "key" not in kwargs:
86
+ kwargs["key"] = default_sort_key
87
+ return max(*args, **kwargs)
88
+
89
+
90
+ def _min(*args, **kwargs):
91
+ if "key" not in kwargs:
92
+ kwargs["key"] = default_sort_key
93
+ return min(*args, **kwargs)
94
+
95
+
96
+ def normalized(normalize):
97
+ r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
98
+
99
+ This is a global setting that can be used to simplify the look of various
100
+ expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
101
+
102
+ Parameters
103
+ ----------
104
+ normalize : bool
105
+ Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
106
+ When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
107
+ Hadamard gate will not have this factor.
108
+ """
109
+ global _normalized
110
+ _normalized = normalize
111
+
112
+
113
+ def _validate_targets_controls(tandc):
114
+ tandc = list(tandc)
115
+ # Check for integers
116
+ for bit in tandc:
117
+ if not bit.is_Integer and not bit.is_Symbol:
118
+ raise TypeError('Integer expected, got: %r' % tandc[bit])
119
+ # Detect duplicates
120
+ if len(set(tandc)) != len(tandc):
121
+ raise QuantumError(
122
+ 'Target/control qubits in a gate cannot be duplicated'
123
+ )
124
+
125
+
126
+ class Gate(UnitaryOperator):
127
+ """Non-controlled unitary gate operator that acts on qubits.
128
+
129
+ This is a general abstract gate that needs to be subclassed to do anything
130
+ useful.
131
+
132
+ Parameters
133
+ ----------
134
+ label : tuple, int
135
+ A list of the target qubits (as ints) that the gate will apply to.
136
+
137
+ Examples
138
+ ========
139
+
140
+
141
+ """
142
+
143
+ _label_separator = ','
144
+
145
+ gate_name = 'G'
146
+ gate_name_latex = 'G'
147
+
148
+ #-------------------------------------------------------------------------
149
+ # Initialization/creation
150
+ #-------------------------------------------------------------------------
151
+
152
+ @classmethod
153
+ def _eval_args(cls, args):
154
+ args = Tuple(*UnitaryOperator._eval_args(args))
155
+ _validate_targets_controls(args)
156
+ return args
157
+
158
+ @classmethod
159
+ def _eval_hilbert_space(cls, args):
160
+ """This returns the smallest possible Hilbert space."""
161
+ return ComplexSpace(2)**(_max(args) + 1)
162
+
163
+ #-------------------------------------------------------------------------
164
+ # Properties
165
+ #-------------------------------------------------------------------------
166
+
167
+ @property
168
+ def nqubits(self):
169
+ """The total number of qubits this gate acts on.
170
+
171
+ For controlled gate subclasses this includes both target and control
172
+ qubits, so that, for examples the CNOT gate acts on 2 qubits.
173
+ """
174
+ return len(self.targets)
175
+
176
+ @property
177
+ def min_qubits(self):
178
+ """The minimum number of qubits this gate needs to act on."""
179
+ return _max(self.targets) + 1
180
+
181
+ @property
182
+ def targets(self):
183
+ """A tuple of target qubits."""
184
+ return self.label
185
+
186
+ @property
187
+ def gate_name_plot(self):
188
+ return r'$%s$' % self.gate_name_latex
189
+
190
+ #-------------------------------------------------------------------------
191
+ # Gate methods
192
+ #-------------------------------------------------------------------------
193
+
194
+ def get_target_matrix(self, format='sympy'):
195
+ """The matrix representation of the target part of the gate.
196
+
197
+ Parameters
198
+ ----------
199
+ format : str
200
+ The format string ('sympy','numpy', etc.)
201
+ """
202
+ raise NotImplementedError(
203
+ 'get_target_matrix is not implemented in Gate.')
204
+
205
+ #-------------------------------------------------------------------------
206
+ # Apply
207
+ #-------------------------------------------------------------------------
208
+
209
+ def _apply_operator_IntQubit(self, qubits, **options):
210
+ """Redirect an apply from IntQubit to Qubit"""
211
+ return self._apply_operator_Qubit(qubits, **options)
212
+
213
+ def _apply_operator_Qubit(self, qubits, **options):
214
+ """Apply this gate to a Qubit."""
215
+
216
+ # Check number of qubits this gate acts on.
217
+ if qubits.nqubits < self.min_qubits:
218
+ raise QuantumError(
219
+ 'Gate needs a minimum of %r qubits to act on, got: %r' %
220
+ (self.min_qubits, qubits.nqubits)
221
+ )
222
+
223
+ # If the controls are not met, just return
224
+ if isinstance(self, CGate):
225
+ if not self.eval_controls(qubits):
226
+ return qubits
227
+
228
+ targets = self.targets
229
+ target_matrix = self.get_target_matrix(format='sympy')
230
+
231
+ # Find which column of the target matrix this applies to.
232
+ column_index = 0
233
+ n = 1
234
+ for target in targets:
235
+ column_index += n*qubits[target]
236
+ n = n << 1
237
+ column = target_matrix[:, int(column_index)]
238
+
239
+ # Now apply each column element to the qubit.
240
+ result = 0
241
+ for index in range(column.rows):
242
+ # TODO: This can be optimized to reduce the number of Qubit
243
+ # creations. We should simply manipulate the raw list of qubit
244
+ # values and then build the new Qubit object once.
245
+ # Make a copy of the incoming qubits.
246
+ new_qubit = qubits.__class__(*qubits.args)
247
+ # Flip the bits that need to be flipped.
248
+ for bit, target in enumerate(targets):
249
+ if new_qubit[target] != (index >> bit) & 1:
250
+ new_qubit = new_qubit.flip(target)
251
+ # The value in that row and column times the flipped-bit qubit
252
+ # is the result for that part.
253
+ result += column[index]*new_qubit
254
+ return result
255
+
256
+ #-------------------------------------------------------------------------
257
+ # Represent
258
+ #-------------------------------------------------------------------------
259
+
260
+ def _represent_default_basis(self, **options):
261
+ return self._represent_ZGate(None, **options)
262
+
263
+ def _represent_ZGate(self, basis, **options):
264
+ format = options.get('format', 'sympy')
265
+ nqubits = options.get('nqubits', 0)
266
+ if nqubits == 0:
267
+ raise QuantumError(
268
+ 'The number of qubits must be given as nqubits.')
269
+
270
+ # Make sure we have enough qubits for the gate.
271
+ if nqubits < self.min_qubits:
272
+ raise QuantumError(
273
+ 'The number of qubits %r is too small for the gate.' % nqubits
274
+ )
275
+
276
+ target_matrix = self.get_target_matrix(format)
277
+ targets = self.targets
278
+ if isinstance(self, CGate):
279
+ controls = self.controls
280
+ else:
281
+ controls = []
282
+ m = represent_zbasis(
283
+ controls, targets, target_matrix, nqubits, format
284
+ )
285
+ return m
286
+
287
+ #-------------------------------------------------------------------------
288
+ # Print methods
289
+ #-------------------------------------------------------------------------
290
+
291
+ def _sympystr(self, printer, *args):
292
+ label = self._print_label(printer, *args)
293
+ return '%s(%s)' % (self.gate_name, label)
294
+
295
+ def _pretty(self, printer, *args):
296
+ a = stringPict(self.gate_name)
297
+ b = self._print_label_pretty(printer, *args)
298
+ return self._print_subscript_pretty(a, b)
299
+
300
+ def _latex(self, printer, *args):
301
+ label = self._print_label(printer, *args)
302
+ return '%s_{%s}' % (self.gate_name_latex, label)
303
+
304
+ def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
305
+ raise NotImplementedError('plot_gate is not implemented.')
306
+
307
+
308
+ class CGate(Gate):
309
+ """A general unitary gate with control qubits.
310
+
311
+ A general control gate applies a target gate to a set of targets if all
312
+ of the control qubits have a particular values (set by
313
+ ``CGate.control_value``).
314
+
315
+ Parameters
316
+ ----------
317
+ label : tuple
318
+ The label in this case has the form (controls, gate), where controls
319
+ is a tuple/list of control qubits (as ints) and gate is a ``Gate``
320
+ instance that is the target operator.
321
+
322
+ Examples
323
+ ========
324
+
325
+ """
326
+
327
+ gate_name = 'C'
328
+ gate_name_latex = 'C'
329
+
330
+ # The values this class controls for.
331
+ control_value = _S.One
332
+
333
+ simplify_cgate = False
334
+
335
+ #-------------------------------------------------------------------------
336
+ # Initialization
337
+ #-------------------------------------------------------------------------
338
+
339
+ @classmethod
340
+ def _eval_args(cls, args):
341
+ # _eval_args has the right logic for the controls argument.
342
+ controls = args[0]
343
+ gate = args[1]
344
+ if not is_sequence(controls):
345
+ controls = (controls,)
346
+ controls = UnitaryOperator._eval_args(controls)
347
+ _validate_targets_controls(chain(controls, gate.targets))
348
+ return (Tuple(*controls), gate)
349
+
350
+ @classmethod
351
+ def _eval_hilbert_space(cls, args):
352
+ """This returns the smallest possible Hilbert space."""
353
+ return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
354
+
355
+ #-------------------------------------------------------------------------
356
+ # Properties
357
+ #-------------------------------------------------------------------------
358
+
359
+ @property
360
+ def nqubits(self):
361
+ """The total number of qubits this gate acts on.
362
+
363
+ For controlled gate subclasses this includes both target and control
364
+ qubits, so that, for examples the CNOT gate acts on 2 qubits.
365
+ """
366
+ return len(self.targets) + len(self.controls)
367
+
368
+ @property
369
+ def min_qubits(self):
370
+ """The minimum number of qubits this gate needs to act on."""
371
+ return _max(_max(self.controls), _max(self.targets)) + 1
372
+
373
+ @property
374
+ def targets(self):
375
+ """A tuple of target qubits."""
376
+ return self.gate.targets
377
+
378
+ @property
379
+ def controls(self):
380
+ """A tuple of control qubits."""
381
+ return tuple(self.label[0])
382
+
383
+ @property
384
+ def gate(self):
385
+ """The non-controlled gate that will be applied to the targets."""
386
+ return self.label[1]
387
+
388
+ #-------------------------------------------------------------------------
389
+ # Gate methods
390
+ #-------------------------------------------------------------------------
391
+
392
+ def get_target_matrix(self, format='sympy'):
393
+ return self.gate.get_target_matrix(format)
394
+
395
+ def eval_controls(self, qubit):
396
+ """Return True/False to indicate if the controls are satisfied."""
397
+ return all(qubit[bit] == self.control_value for bit in self.controls)
398
+
399
+ def decompose(self, **options):
400
+ """Decompose the controlled gate into CNOT and single qubits gates."""
401
+ if len(self.controls) == 1:
402
+ c = self.controls[0]
403
+ t = self.gate.targets[0]
404
+ if isinstance(self.gate, YGate):
405
+ g1 = PhaseGate(t)
406
+ g2 = CNotGate(c, t)
407
+ g3 = PhaseGate(t)
408
+ g4 = ZGate(t)
409
+ return g1*g2*g3*g4
410
+ if isinstance(self.gate, ZGate):
411
+ g1 = HadamardGate(t)
412
+ g2 = CNotGate(c, t)
413
+ g3 = HadamardGate(t)
414
+ return g1*g2*g3
415
+ else:
416
+ return self
417
+
418
+ #-------------------------------------------------------------------------
419
+ # Print methods
420
+ #-------------------------------------------------------------------------
421
+
422
+ def _print_label(self, printer, *args):
423
+ controls = self._print_sequence(self.controls, ',', printer, *args)
424
+ gate = printer._print(self.gate, *args)
425
+ return '(%s),%s' % (controls, gate)
426
+
427
+ def _pretty(self, printer, *args):
428
+ controls = self._print_sequence_pretty(
429
+ self.controls, ',', printer, *args)
430
+ gate = printer._print(self.gate)
431
+ gate_name = stringPict(self.gate_name)
432
+ first = self._print_subscript_pretty(gate_name, controls)
433
+ gate = self._print_parens_pretty(gate)
434
+ final = prettyForm(*first.right(gate))
435
+ return final
436
+
437
+ def _latex(self, printer, *args):
438
+ controls = self._print_sequence(self.controls, ',', printer, *args)
439
+ gate = printer._print(self.gate, *args)
440
+ return r'%s_{%s}{\left(%s\right)}' % \
441
+ (self.gate_name_latex, controls, gate)
442
+
443
+ def plot_gate(self, circ_plot, gate_idx):
444
+ """
445
+ Plot the controlled gate. If *simplify_cgate* is true, simplify
446
+ C-X and C-Z gates into their more familiar forms.
447
+ """
448
+ min_wire = int(_min(chain(self.controls, self.targets)))
449
+ max_wire = int(_max(chain(self.controls, self.targets)))
450
+ circ_plot.control_line(gate_idx, min_wire, max_wire)
451
+ for c in self.controls:
452
+ circ_plot.control_point(gate_idx, int(c))
453
+ if self.simplify_cgate:
454
+ if self.gate.gate_name == 'X':
455
+ self.gate.plot_gate_plus(circ_plot, gate_idx)
456
+ elif self.gate.gate_name == 'Z':
457
+ circ_plot.control_point(gate_idx, self.targets[0])
458
+ else:
459
+ self.gate.plot_gate(circ_plot, gate_idx)
460
+ else:
461
+ self.gate.plot_gate(circ_plot, gate_idx)
462
+
463
+ #-------------------------------------------------------------------------
464
+ # Miscellaneous
465
+ #-------------------------------------------------------------------------
466
+
467
+ def _eval_dagger(self):
468
+ if isinstance(self.gate, HermitianOperator):
469
+ return self
470
+ else:
471
+ return Gate._eval_dagger(self)
472
+
473
+ def _eval_inverse(self):
474
+ if isinstance(self.gate, HermitianOperator):
475
+ return self
476
+ else:
477
+ return Gate._eval_inverse(self)
478
+
479
+ def _eval_power(self, exp):
480
+ if isinstance(self.gate, HermitianOperator):
481
+ if exp == -1:
482
+ return Gate._eval_power(self, exp)
483
+ elif abs(exp) % 2 == 0:
484
+ return self*(Gate._eval_inverse(self))
485
+ else:
486
+ return self
487
+ else:
488
+ return Gate._eval_power(self, exp)
489
+
490
+ class CGateS(CGate):
491
+ """Version of CGate that allows gate simplifications.
492
+ I.e. cnot looks like an oplus, cphase has dots, etc.
493
+ """
494
+ simplify_cgate=True
495
+
496
+
497
+ class UGate(Gate):
498
+ """General gate specified by a set of targets and a target matrix.
499
+
500
+ Parameters
501
+ ----------
502
+ label : tuple
503
+ A tuple of the form (targets, U), where targets is a tuple of the
504
+ target qubits and U is a unitary matrix with dimension of
505
+ len(targets).
506
+ """
507
+ gate_name = 'U'
508
+ gate_name_latex = 'U'
509
+
510
+ #-------------------------------------------------------------------------
511
+ # Initialization
512
+ #-------------------------------------------------------------------------
513
+
514
+ @classmethod
515
+ def _eval_args(cls, args):
516
+ targets = args[0]
517
+ if not is_sequence(targets):
518
+ targets = (targets,)
519
+ targets = Gate._eval_args(targets)
520
+ _validate_targets_controls(targets)
521
+ mat = args[1]
522
+ if not isinstance(mat, MatrixBase):
523
+ raise TypeError('Matrix expected, got: %r' % mat)
524
+ #make sure this matrix is of a Basic type
525
+ mat = _sympify(mat)
526
+ dim = 2**len(targets)
527
+ if not all(dim == shape for shape in mat.shape):
528
+ raise IndexError(
529
+ 'Number of targets must match the matrix size: %r %r' %
530
+ (targets, mat)
531
+ )
532
+ return (targets, mat)
533
+
534
+ @classmethod
535
+ def _eval_hilbert_space(cls, args):
536
+ """This returns the smallest possible Hilbert space."""
537
+ return ComplexSpace(2)**(_max(args[0]) + 1)
538
+
539
+ #-------------------------------------------------------------------------
540
+ # Properties
541
+ #-------------------------------------------------------------------------
542
+
543
+ @property
544
+ def targets(self):
545
+ """A tuple of target qubits."""
546
+ return tuple(self.label[0])
547
+
548
+ #-------------------------------------------------------------------------
549
+ # Gate methods
550
+ #-------------------------------------------------------------------------
551
+
552
+ def get_target_matrix(self, format='sympy'):
553
+ """The matrix rep. of the target part of the gate.
554
+
555
+ Parameters
556
+ ----------
557
+ format : str
558
+ The format string ('sympy','numpy', etc.)
559
+ """
560
+ return self.label[1]
561
+
562
+ #-------------------------------------------------------------------------
563
+ # Print methods
564
+ #-------------------------------------------------------------------------
565
+ def _pretty(self, printer, *args):
566
+ targets = self._print_sequence_pretty(
567
+ self.targets, ',', printer, *args)
568
+ gate_name = stringPict(self.gate_name)
569
+ return self._print_subscript_pretty(gate_name, targets)
570
+
571
+ def _latex(self, printer, *args):
572
+ targets = self._print_sequence(self.targets, ',', printer, *args)
573
+ return r'%s_{%s}' % (self.gate_name_latex, targets)
574
+
575
+ def plot_gate(self, circ_plot, gate_idx):
576
+ circ_plot.one_qubit_box(
577
+ self.gate_name_plot,
578
+ gate_idx, int(self.targets[0])
579
+ )
580
+
581
+
582
+ class OneQubitGate(Gate):
583
+ """A single qubit unitary gate base class."""
584
+
585
+ nqubits = _S.One
586
+
587
+ def plot_gate(self, circ_plot, gate_idx):
588
+ circ_plot.one_qubit_box(
589
+ self.gate_name_plot,
590
+ gate_idx, int(self.targets[0])
591
+ )
592
+
593
+ def _eval_commutator(self, other, **hints):
594
+ if isinstance(other, OneQubitGate):
595
+ if self.targets != other.targets or self.__class__ == other.__class__:
596
+ return _S.Zero
597
+ return Operator._eval_commutator(self, other, **hints)
598
+
599
+ def _eval_anticommutator(self, other, **hints):
600
+ if isinstance(other, OneQubitGate):
601
+ if self.targets != other.targets or self.__class__ == other.__class__:
602
+ return Integer(2)*self*other
603
+ return Operator._eval_anticommutator(self, other, **hints)
604
+
605
+
606
+ class TwoQubitGate(Gate):
607
+ """A two qubit unitary gate base class."""
608
+
609
+ nqubits = Integer(2)
610
+
611
+ #-----------------------------------------------------------------------------
612
+ # Single Qubit Gates
613
+ #-----------------------------------------------------------------------------
614
+
615
+
616
+ class IdentityGate(OneQubitGate):
617
+ """The single qubit identity gate.
618
+
619
+ Parameters
620
+ ----------
621
+ target : int
622
+ The target qubit this gate will apply to.
623
+
624
+ Examples
625
+ ========
626
+
627
+ """
628
+ gate_name = '1'
629
+ gate_name_latex = '1'
630
+
631
+ # Short cut version of gate._apply_operator_Qubit
632
+ def _apply_operator_Qubit(self, qubits, **options):
633
+ # Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
634
+ if qubits.nqubits < self.min_qubits:
635
+ raise QuantumError(
636
+ 'Gate needs a minimum of %r qubits to act on, got: %r' %
637
+ (self.min_qubits, qubits.nqubits)
638
+ )
639
+ return qubits # no computation required for IdentityGate
640
+
641
+ def get_target_matrix(self, format='sympy'):
642
+ return matrix_cache.get_matrix('eye2', format)
643
+
644
+ def _eval_commutator(self, other, **hints):
645
+ return _S.Zero
646
+
647
+ def _eval_anticommutator(self, other, **hints):
648
+ return Integer(2)*other
649
+
650
+
651
+ class HadamardGate(HermitianOperator, OneQubitGate):
652
+ """The single qubit Hadamard gate.
653
+
654
+ Parameters
655
+ ----------
656
+ target : int
657
+ The target qubit this gate will apply to.
658
+
659
+ Examples
660
+ ========
661
+
662
+ >>> from sympy import sqrt
663
+ >>> from sympy.physics.quantum.qubit import Qubit
664
+ >>> from sympy.physics.quantum.gate import HadamardGate
665
+ >>> from sympy.physics.quantum.qapply import qapply
666
+ >>> qapply(HadamardGate(0)*Qubit('1'))
667
+ sqrt(2)*|0>/2 - sqrt(2)*|1>/2
668
+ >>> # Hadamard on bell state, applied on 2 qubits.
669
+ >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
670
+ >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
671
+ sqrt(2)*|00>/2 + sqrt(2)*|11>/2
672
+
673
+ """
674
+ gate_name = 'H'
675
+ gate_name_latex = 'H'
676
+
677
+ def get_target_matrix(self, format='sympy'):
678
+ if _normalized:
679
+ return matrix_cache.get_matrix('H', format)
680
+ else:
681
+ return matrix_cache.get_matrix('Hsqrt2', format)
682
+
683
+ def _eval_commutator_XGate(self, other, **hints):
684
+ return I*sqrt(2)*YGate(self.targets[0])
685
+
686
+ def _eval_commutator_YGate(self, other, **hints):
687
+ return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
688
+
689
+ def _eval_commutator_ZGate(self, other, **hints):
690
+ return -I*sqrt(2)*YGate(self.targets[0])
691
+
692
+ def _eval_anticommutator_XGate(self, other, **hints):
693
+ return sqrt(2)*IdentityGate(self.targets[0])
694
+
695
+ def _eval_anticommutator_YGate(self, other, **hints):
696
+ return _S.Zero
697
+
698
+ def _eval_anticommutator_ZGate(self, other, **hints):
699
+ return sqrt(2)*IdentityGate(self.targets[0])
700
+
701
+
702
+ class XGate(HermitianOperator, OneQubitGate):
703
+ """The single qubit X, or NOT, gate.
704
+
705
+ Parameters
706
+ ----------
707
+ target : int
708
+ The target qubit this gate will apply to.
709
+
710
+ Examples
711
+ ========
712
+
713
+ """
714
+ gate_name = 'X'
715
+ gate_name_latex = 'X'
716
+
717
+ def get_target_matrix(self, format='sympy'):
718
+ return matrix_cache.get_matrix('X', format)
719
+
720
+ def plot_gate(self, circ_plot, gate_idx):
721
+ OneQubitGate.plot_gate(self,circ_plot,gate_idx)
722
+
723
+ def plot_gate_plus(self, circ_plot, gate_idx):
724
+ circ_plot.not_point(
725
+ gate_idx, int(self.label[0])
726
+ )
727
+
728
+ def _eval_commutator_YGate(self, other, **hints):
729
+ return Integer(2)*I*ZGate(self.targets[0])
730
+
731
+ def _eval_anticommutator_XGate(self, other, **hints):
732
+ return Integer(2)*IdentityGate(self.targets[0])
733
+
734
+ def _eval_anticommutator_YGate(self, other, **hints):
735
+ return _S.Zero
736
+
737
+ def _eval_anticommutator_ZGate(self, other, **hints):
738
+ return _S.Zero
739
+
740
+
741
+ class YGate(HermitianOperator, OneQubitGate):
742
+ """The single qubit Y gate.
743
+
744
+ Parameters
745
+ ----------
746
+ target : int
747
+ The target qubit this gate will apply to.
748
+
749
+ Examples
750
+ ========
751
+
752
+ """
753
+ gate_name = 'Y'
754
+ gate_name_latex = 'Y'
755
+
756
+ def get_target_matrix(self, format='sympy'):
757
+ return matrix_cache.get_matrix('Y', format)
758
+
759
+ def _eval_commutator_ZGate(self, other, **hints):
760
+ return Integer(2)*I*XGate(self.targets[0])
761
+
762
+ def _eval_anticommutator_YGate(self, other, **hints):
763
+ return Integer(2)*IdentityGate(self.targets[0])
764
+
765
+ def _eval_anticommutator_ZGate(self, other, **hints):
766
+ return _S.Zero
767
+
768
+
769
+ class ZGate(HermitianOperator, OneQubitGate):
770
+ """The single qubit Z gate.
771
+
772
+ Parameters
773
+ ----------
774
+ target : int
775
+ The target qubit this gate will apply to.
776
+
777
+ Examples
778
+ ========
779
+
780
+ """
781
+ gate_name = 'Z'
782
+ gate_name_latex = 'Z'
783
+
784
+ def get_target_matrix(self, format='sympy'):
785
+ return matrix_cache.get_matrix('Z', format)
786
+
787
+ def _eval_commutator_XGate(self, other, **hints):
788
+ return Integer(2)*I*YGate(self.targets[0])
789
+
790
+ def _eval_anticommutator_YGate(self, other, **hints):
791
+ return _S.Zero
792
+
793
+
794
+ class PhaseGate(OneQubitGate):
795
+ """The single qubit phase, or S, gate.
796
+
797
+ This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
798
+ does nothing if the state is ``|0>``.
799
+
800
+ Parameters
801
+ ----------
802
+ target : int
803
+ The target qubit this gate will apply to.
804
+
805
+ Examples
806
+ ========
807
+
808
+ """
809
+ gate_name = 'S'
810
+ gate_name_latex = 'S'
811
+
812
+ def get_target_matrix(self, format='sympy'):
813
+ return matrix_cache.get_matrix('S', format)
814
+
815
+ def _eval_commutator_ZGate(self, other, **hints):
816
+ return _S.Zero
817
+
818
+ def _eval_commutator_TGate(self, other, **hints):
819
+ return _S.Zero
820
+
821
+
822
+ class TGate(OneQubitGate):
823
+ """The single qubit pi/8 gate.
824
+
825
+ This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
826
+ does nothing if the state is ``|0>``.
827
+
828
+ Parameters
829
+ ----------
830
+ target : int
831
+ The target qubit this gate will apply to.
832
+
833
+ Examples
834
+ ========
835
+
836
+ """
837
+ gate_name = 'T'
838
+ gate_name_latex = 'T'
839
+
840
+ def get_target_matrix(self, format='sympy'):
841
+ return matrix_cache.get_matrix('T', format)
842
+
843
+ def _eval_commutator_ZGate(self, other, **hints):
844
+ return _S.Zero
845
+
846
+ def _eval_commutator_PhaseGate(self, other, **hints):
847
+ return _S.Zero
848
+
849
+
850
+ # Aliases for gate names.
851
+ H = HadamardGate
852
+ X = XGate
853
+ Y = YGate
854
+ Z = ZGate
855
+ T = TGate
856
+ Phase = S = PhaseGate
857
+
858
+
859
+ #-----------------------------------------------------------------------------
860
+ # 2 Qubit Gates
861
+ #-----------------------------------------------------------------------------
862
+
863
+
864
+ class CNotGate(HermitianOperator, CGate, TwoQubitGate):
865
+ """Two qubit controlled-NOT.
866
+
867
+ This gate performs the NOT or X gate on the target qubit if the control
868
+ qubits all have the value 1.
869
+
870
+ Parameters
871
+ ----------
872
+ label : tuple
873
+ A tuple of the form (control, target).
874
+
875
+ Examples
876
+ ========
877
+
878
+ >>> from sympy.physics.quantum.gate import CNOT
879
+ >>> from sympy.physics.quantum.qapply import qapply
880
+ >>> from sympy.physics.quantum.qubit import Qubit
881
+ >>> c = CNOT(1,0)
882
+ >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
883
+ |11>
884
+
885
+ """
886
+ gate_name = 'CNOT'
887
+ gate_name_latex = r'\text{CNOT}'
888
+ simplify_cgate = True
889
+
890
+ #-------------------------------------------------------------------------
891
+ # Initialization
892
+ #-------------------------------------------------------------------------
893
+
894
+ @classmethod
895
+ def _eval_args(cls, args):
896
+ args = Gate._eval_args(args)
897
+ return args
898
+
899
+ @classmethod
900
+ def _eval_hilbert_space(cls, args):
901
+ """This returns the smallest possible Hilbert space."""
902
+ return ComplexSpace(2)**(_max(args) + 1)
903
+
904
+ #-------------------------------------------------------------------------
905
+ # Properties
906
+ #-------------------------------------------------------------------------
907
+
908
+ @property
909
+ def min_qubits(self):
910
+ """The minimum number of qubits this gate needs to act on."""
911
+ return _max(self.label) + 1
912
+
913
+ @property
914
+ def targets(self):
915
+ """A tuple of target qubits."""
916
+ return (self.label[1],)
917
+
918
+ @property
919
+ def controls(self):
920
+ """A tuple of control qubits."""
921
+ return (self.label[0],)
922
+
923
+ @property
924
+ def gate(self):
925
+ """The non-controlled gate that will be applied to the targets."""
926
+ return XGate(self.label[1])
927
+
928
+ #-------------------------------------------------------------------------
929
+ # Properties
930
+ #-------------------------------------------------------------------------
931
+
932
+ # The default printing of Gate works better than those of CGate, so we
933
+ # go around the overridden methods in CGate.
934
+
935
+ def _print_label(self, printer, *args):
936
+ return Gate._print_label(self, printer, *args)
937
+
938
+ def _pretty(self, printer, *args):
939
+ return Gate._pretty(self, printer, *args)
940
+
941
+ def _latex(self, printer, *args):
942
+ return Gate._latex(self, printer, *args)
943
+
944
+ #-------------------------------------------------------------------------
945
+ # Commutator/AntiCommutator
946
+ #-------------------------------------------------------------------------
947
+
948
+ def _eval_commutator_ZGate(self, other, **hints):
949
+ """[CNOT(i, j), Z(i)] == 0."""
950
+ if self.controls[0] == other.targets[0]:
951
+ return _S.Zero
952
+ else:
953
+ raise NotImplementedError('Commutator not implemented: %r' % other)
954
+
955
+ def _eval_commutator_TGate(self, other, **hints):
956
+ """[CNOT(i, j), T(i)] == 0."""
957
+ return self._eval_commutator_ZGate(other, **hints)
958
+
959
+ def _eval_commutator_PhaseGate(self, other, **hints):
960
+ """[CNOT(i, j), S(i)] == 0."""
961
+ return self._eval_commutator_ZGate(other, **hints)
962
+
963
+ def _eval_commutator_XGate(self, other, **hints):
964
+ """[CNOT(i, j), X(j)] == 0."""
965
+ if self.targets[0] == other.targets[0]:
966
+ return _S.Zero
967
+ else:
968
+ raise NotImplementedError('Commutator not implemented: %r' % other)
969
+
970
+ def _eval_commutator_CNotGate(self, other, **hints):
971
+ """[CNOT(i, j), CNOT(i,k)] == 0."""
972
+ if self.controls[0] == other.controls[0]:
973
+ return _S.Zero
974
+ else:
975
+ raise NotImplementedError('Commutator not implemented: %r' % other)
976
+
977
+
978
+ class SwapGate(TwoQubitGate):
979
+ """Two qubit SWAP gate.
980
+
981
+ This gate swap the values of the two qubits.
982
+
983
+ Parameters
984
+ ----------
985
+ label : tuple
986
+ A tuple of the form (target1, target2).
987
+
988
+ Examples
989
+ ========
990
+
991
+ """
992
+ gate_name = 'SWAP'
993
+ gate_name_latex = r'\text{SWAP}'
994
+
995
+ def get_target_matrix(self, format='sympy'):
996
+ return matrix_cache.get_matrix('SWAP', format)
997
+
998
+ def decompose(self, **options):
999
+ """Decompose the SWAP gate into CNOT gates."""
1000
+ i, j = self.targets[0], self.targets[1]
1001
+ g1 = CNotGate(i, j)
1002
+ g2 = CNotGate(j, i)
1003
+ return g1*g2*g1
1004
+
1005
+ def plot_gate(self, circ_plot, gate_idx):
1006
+ min_wire = int(_min(self.targets))
1007
+ max_wire = int(_max(self.targets))
1008
+ circ_plot.control_line(gate_idx, min_wire, max_wire)
1009
+ circ_plot.swap_point(gate_idx, min_wire)
1010
+ circ_plot.swap_point(gate_idx, max_wire)
1011
+
1012
+ def _represent_ZGate(self, basis, **options):
1013
+ """Represent the SWAP gate in the computational basis.
1014
+
1015
+ The following representation is used to compute this:
1016
+
1017
+ SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
1018
+ """
1019
+ format = options.get('format', 'sympy')
1020
+ targets = [int(t) for t in self.targets]
1021
+ min_target = _min(targets)
1022
+ max_target = _max(targets)
1023
+ nqubits = options.get('nqubits', self.min_qubits)
1024
+
1025
+ op01 = matrix_cache.get_matrix('op01', format)
1026
+ op10 = matrix_cache.get_matrix('op10', format)
1027
+ op11 = matrix_cache.get_matrix('op11', format)
1028
+ op00 = matrix_cache.get_matrix('op00', format)
1029
+ eye2 = matrix_cache.get_matrix('eye2', format)
1030
+
1031
+ result = None
1032
+ for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
1033
+ product = nqubits*[eye2]
1034
+ product[nqubits - min_target - 1] = i
1035
+ product[nqubits - max_target - 1] = j
1036
+ new_result = matrix_tensor_product(*product)
1037
+ if result is None:
1038
+ result = new_result
1039
+ else:
1040
+ result = result + new_result
1041
+
1042
+ return result
1043
+
1044
+
1045
+ # Aliases for gate names.
1046
+ CNOT = CNotGate
1047
+ SWAP = SwapGate
1048
+ def CPHASE(a,b): return CGateS((a,),Z(b))
1049
+
1050
+
1051
+ #-----------------------------------------------------------------------------
1052
+ # Represent
1053
+ #-----------------------------------------------------------------------------
1054
+
1055
+
1056
+ def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
1057
+ """Represent a gate with controls, targets and target_matrix.
1058
+
1059
+ This function does the low-level work of representing gates as matrices
1060
+ in the standard computational basis (ZGate). Currently, we support two
1061
+ main cases:
1062
+
1063
+ 1. One target qubit and no control qubits.
1064
+ 2. One target qubits and multiple control qubits.
1065
+
1066
+ For the base of multiple controls, we use the following expression [1]:
1067
+
1068
+ 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
1069
+
1070
+ Parameters
1071
+ ----------
1072
+ controls : list, tuple
1073
+ A sequence of control qubits.
1074
+ targets : list, tuple
1075
+ A sequence of target qubits.
1076
+ target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
1077
+ The matrix form of the transformation to be performed on the target
1078
+ qubits. The format of this matrix must match that passed into
1079
+ the `format` argument.
1080
+ nqubits : int
1081
+ The total number of qubits used for the representation.
1082
+ format : str
1083
+ The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
1084
+
1085
+ Examples
1086
+ ========
1087
+
1088
+ References
1089
+ ----------
1090
+ [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
1091
+ """
1092
+ controls = [int(x) for x in controls]
1093
+ targets = [int(x) for x in targets]
1094
+ nqubits = int(nqubits)
1095
+
1096
+ # This checks for the format as well.
1097
+ op11 = matrix_cache.get_matrix('op11', format)
1098
+ eye2 = matrix_cache.get_matrix('eye2', format)
1099
+
1100
+ # Plain single qubit case
1101
+ if len(controls) == 0 and len(targets) == 1:
1102
+ product = []
1103
+ bit = targets[0]
1104
+ # Fill product with [I1,Gate,I2] such that the unitaries,
1105
+ # I, cause the gate to be applied to the correct Qubit
1106
+ if bit != nqubits - 1:
1107
+ product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
1108
+ product.append(target_matrix)
1109
+ if bit != 0:
1110
+ product.append(matrix_eye(2**bit, format=format))
1111
+ return matrix_tensor_product(*product)
1112
+
1113
+ # Single target, multiple controls.
1114
+ elif len(targets) == 1 and len(controls) >= 1:
1115
+ target = targets[0]
1116
+
1117
+ # Build the non-trivial part.
1118
+ product2 = []
1119
+ for i in range(nqubits):
1120
+ product2.append(matrix_eye(2, format=format))
1121
+ for control in controls:
1122
+ product2[nqubits - 1 - control] = op11
1123
+ product2[nqubits - 1 - target] = target_matrix - eye2
1124
+
1125
+ return matrix_eye(2**nqubits, format=format) + \
1126
+ matrix_tensor_product(*product2)
1127
+
1128
+ # Multi-target, multi-control is not yet implemented.
1129
+ else:
1130
+ raise NotImplementedError(
1131
+ 'The representation of multi-target, multi-control gates '
1132
+ 'is not implemented.'
1133
+ )
1134
+
1135
+
1136
+ #-----------------------------------------------------------------------------
1137
+ # Gate manipulation functions.
1138
+ #-----------------------------------------------------------------------------
1139
+
1140
+
1141
+ def gate_simp(circuit):
1142
+ """Simplifies gates symbolically
1143
+
1144
+ It first sorts gates using gate_sort. It then applies basic
1145
+ simplification rules to the circuit, e.g., XGate**2 = Identity
1146
+ """
1147
+
1148
+ # Bubble sort out gates that commute.
1149
+ circuit = gate_sort(circuit)
1150
+
1151
+ # Do simplifications by subing a simplification into the first element
1152
+ # which can be simplified. We recursively call gate_simp with new circuit
1153
+ # as input more simplifications exist.
1154
+ if isinstance(circuit, Add):
1155
+ return sum(gate_simp(t) for t in circuit.args)
1156
+ elif isinstance(circuit, Mul):
1157
+ circuit_args = circuit.args
1158
+ elif isinstance(circuit, Pow):
1159
+ b, e = circuit.as_base_exp()
1160
+ circuit_args = (gate_simp(b)**e,)
1161
+ else:
1162
+ return circuit
1163
+
1164
+ # Iterate through each element in circuit, simplify if possible.
1165
+ for i in range(len(circuit_args)):
1166
+ # H,X,Y or Z squared is 1.
1167
+ # T**2 = S, S**2 = Z
1168
+ if isinstance(circuit_args[i], Pow):
1169
+ if isinstance(circuit_args[i].base,
1170
+ (HadamardGate, XGate, YGate, ZGate)) \
1171
+ and isinstance(circuit_args[i].exp, Number):
1172
+ # Build a new circuit taking replacing the
1173
+ # H,X,Y,Z squared with one.
1174
+ newargs = (circuit_args[:i] +
1175
+ (circuit_args[i].base**(circuit_args[i].exp % 2),) +
1176
+ circuit_args[i + 1:])
1177
+ # Recursively simplify the new circuit.
1178
+ circuit = gate_simp(Mul(*newargs))
1179
+ break
1180
+ elif isinstance(circuit_args[i].base, PhaseGate):
1181
+ # Build a new circuit taking old circuit but splicing
1182
+ # in simplification.
1183
+ newargs = circuit_args[:i]
1184
+ # Replace PhaseGate**2 with ZGate.
1185
+ newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
1186
+ (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
1187
+ (circuit_args[i].exp % 2))
1188
+ # Append the last elements.
1189
+ newargs = newargs + circuit_args[i + 1:]
1190
+ # Recursively simplify the new circuit.
1191
+ circuit = gate_simp(Mul(*newargs))
1192
+ break
1193
+ elif isinstance(circuit_args[i].base, TGate):
1194
+ # Build a new circuit taking all the old elements.
1195
+ newargs = circuit_args[:i]
1196
+
1197
+ # Put an Phasegate in place of any TGate**2.
1198
+ newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
1199
+ Integer(circuit_args[i].exp/2), circuit_args[i].base**
1200
+ (circuit_args[i].exp % 2))
1201
+
1202
+ # Append the last elements.
1203
+ newargs = newargs + circuit_args[i + 1:]
1204
+ # Recursively simplify the new circuit.
1205
+ circuit = gate_simp(Mul(*newargs))
1206
+ break
1207
+ return circuit
1208
+
1209
+
1210
+ def gate_sort(circuit):
1211
+ """Sorts the gates while keeping track of commutation relations
1212
+
1213
+ This function uses a bubble sort to rearrange the order of gate
1214
+ application. Keeps track of Quantum computations special commutation
1215
+ relations (e.g. things that apply to the same Qubit do not commute with
1216
+ each other)
1217
+
1218
+ circuit is the Mul of gates that are to be sorted.
1219
+ """
1220
+ # Make sure we have an Add or Mul.
1221
+ if isinstance(circuit, Add):
1222
+ return sum(gate_sort(t) for t in circuit.args)
1223
+ if isinstance(circuit, Pow):
1224
+ return gate_sort(circuit.base)**circuit.exp
1225
+ elif isinstance(circuit, Gate):
1226
+ return circuit
1227
+ if not isinstance(circuit, Mul):
1228
+ return circuit
1229
+
1230
+ changes = True
1231
+ while changes:
1232
+ changes = False
1233
+ circ_array = circuit.args
1234
+ for i in range(len(circ_array) - 1):
1235
+ # Go through each element and switch ones that are in wrong order
1236
+ if isinstance(circ_array[i], (Gate, Pow)) and \
1237
+ isinstance(circ_array[i + 1], (Gate, Pow)):
1238
+ # If we have a Pow object, look at only the base
1239
+ first_base, first_exp = circ_array[i].as_base_exp()
1240
+ second_base, second_exp = circ_array[i + 1].as_base_exp()
1241
+
1242
+ # Use SymPy's hash based sorting. This is not mathematical
1243
+ # sorting, but is rather based on comparing hashes of objects.
1244
+ # See Basic.compare for details.
1245
+ if first_base.compare(second_base) > 0:
1246
+ if Commutator(first_base, second_base).doit() == 0:
1247
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1248
+ (circuit.args[i],) + circuit.args[i + 2:])
1249
+ circuit = Mul(*new_args)
1250
+ changes = True
1251
+ break
1252
+ if AntiCommutator(first_base, second_base).doit() == 0:
1253
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1254
+ (circuit.args[i],) + circuit.args[i + 2:])
1255
+ sign = _S.NegativeOne**(first_exp*second_exp)
1256
+ circuit = sign*Mul(*new_args)
1257
+ changes = True
1258
+ break
1259
+ return circuit
1260
+
1261
+
1262
+ #-----------------------------------------------------------------------------
1263
+ # Utility functions
1264
+ #-----------------------------------------------------------------------------
1265
+
1266
+
1267
+ def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
1268
+ """Return a random circuit of ngates and nqubits.
1269
+
1270
+ This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
1271
+ gates.
1272
+
1273
+ Parameters
1274
+ ----------
1275
+ ngates : int
1276
+ The number of gates in the circuit.
1277
+ nqubits : int
1278
+ The number of qubits in the circuit.
1279
+ gate_space : tuple
1280
+ A tuple of the gate classes that will be used in the circuit.
1281
+ Repeating gate classes multiple times in this tuple will increase
1282
+ the frequency they appear in the random circuit.
1283
+ """
1284
+ qubit_space = range(nqubits)
1285
+ result = []
1286
+ for i in range(ngates):
1287
+ g = random.choice(gate_space)
1288
+ if g == CNotGate or g == SwapGate:
1289
+ qubits = random.sample(qubit_space, 2)
1290
+ g = g(*qubits)
1291
+ else:
1292
+ qubit = random.choice(qubit_space)
1293
+ g = g(qubit)
1294
+ result.append(g)
1295
+ return Mul(*result)
1296
+
1297
+
1298
+ def zx_basis_transform(self, format='sympy'):
1299
+ """Transformation matrix from Z to X basis."""
1300
+ return matrix_cache.get_matrix('ZX', format)
1301
+
1302
+
1303
+ def zy_basis_transform(self, format='sympy'):
1304
+ """Transformation matrix from Z to Y basis."""
1305
+ return matrix_cache.get_matrix('ZY', format)
venv/lib/python3.10/site-packages/sympy/physics/quantum/grover.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Grover's algorithm and helper functions.
2
+
3
+ Todo:
4
+
5
+ * W gate construction (or perhaps -W gate based on Mermin's book)
6
+ * Generalize the algorithm for an unknown function that returns 1 on multiple
7
+ qubit states, not just one.
8
+ * Implement _represent_ZGate in OracleGate
9
+ """
10
+
11
+ from sympy.core.numbers import pi
12
+ from sympy.core.sympify import sympify
13
+ from sympy.core.basic import Atom
14
+ from sympy.functions.elementary.integers import floor
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.matrices.dense import eye
17
+ from sympy.core.numbers import NegativeOne
18
+ from sympy.physics.quantum.qapply import qapply
19
+ from sympy.physics.quantum.qexpr import QuantumError
20
+ from sympy.physics.quantum.hilbert import ComplexSpace
21
+ from sympy.physics.quantum.operator import UnitaryOperator
22
+ from sympy.physics.quantum.gate import Gate
23
+ from sympy.physics.quantum.qubit import IntQubit
24
+
25
+ __all__ = [
26
+ 'OracleGate',
27
+ 'WGate',
28
+ 'superposition_basis',
29
+ 'grover_iteration',
30
+ 'apply_grover'
31
+ ]
32
+
33
+
34
+ def superposition_basis(nqubits):
35
+ """Creates an equal superposition of the computational basis.
36
+
37
+ Parameters
38
+ ==========
39
+
40
+ nqubits : int
41
+ The number of qubits.
42
+
43
+ Returns
44
+ =======
45
+
46
+ state : Qubit
47
+ An equal superposition of the computational basis with nqubits.
48
+
49
+ Examples
50
+ ========
51
+
52
+ Create an equal superposition of 2 qubits::
53
+
54
+ >>> from sympy.physics.quantum.grover import superposition_basis
55
+ >>> superposition_basis(2)
56
+ |0>/2 + |1>/2 + |2>/2 + |3>/2
57
+ """
58
+
59
+ amp = 1/sqrt(2**nqubits)
60
+ return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)])
61
+
62
+ class OracleGateFunction(Atom):
63
+ """Wrapper for python functions used in `OracleGate`s"""
64
+
65
+ def __new__(cls, function):
66
+ if not callable(function):
67
+ raise TypeError('Callable expected, got: %r' % function)
68
+ obj = Atom.__new__(cls)
69
+ obj.function = function
70
+ return obj
71
+
72
+ def _hashable_content(self):
73
+ return type(self), self.function
74
+
75
+ def __call__(self, *args):
76
+ return self.function(*args)
77
+
78
+
79
+ class OracleGate(Gate):
80
+ """A black box gate.
81
+
82
+ The gate marks the desired qubits of an unknown function by flipping
83
+ the sign of the qubits. The unknown function returns true when it
84
+ finds its desired qubits and false otherwise.
85
+
86
+ Parameters
87
+ ==========
88
+
89
+ qubits : int
90
+ Number of qubits.
91
+
92
+ oracle : callable
93
+ A callable function that returns a boolean on a computational basis.
94
+
95
+ Examples
96
+ ========
97
+
98
+ Apply an Oracle gate that flips the sign of ``|2>`` on different qubits::
99
+
100
+ >>> from sympy.physics.quantum.qubit import IntQubit
101
+ >>> from sympy.physics.quantum.qapply import qapply
102
+ >>> from sympy.physics.quantum.grover import OracleGate
103
+ >>> f = lambda qubits: qubits == IntQubit(2)
104
+ >>> v = OracleGate(2, f)
105
+ >>> qapply(v*IntQubit(2))
106
+ -|2>
107
+ >>> qapply(v*IntQubit(3))
108
+ |3>
109
+ """
110
+
111
+ gate_name = 'V'
112
+ gate_name_latex = 'V'
113
+
114
+ #-------------------------------------------------------------------------
115
+ # Initialization/creation
116
+ #-------------------------------------------------------------------------
117
+
118
+ @classmethod
119
+ def _eval_args(cls, args):
120
+ if len(args) != 2:
121
+ raise QuantumError(
122
+ 'Insufficient/excessive arguments to Oracle. Please ' +
123
+ 'supply the number of qubits and an unknown function.'
124
+ )
125
+ sub_args = (args[0],)
126
+ sub_args = UnitaryOperator._eval_args(sub_args)
127
+ if not sub_args[0].is_Integer:
128
+ raise TypeError('Integer expected, got: %r' % sub_args[0])
129
+
130
+ function = args[1]
131
+ if not isinstance(function, OracleGateFunction):
132
+ function = OracleGateFunction(function)
133
+
134
+ return (sub_args[0], function)
135
+
136
+ @classmethod
137
+ def _eval_hilbert_space(cls, args):
138
+ """This returns the smallest possible Hilbert space."""
139
+ return ComplexSpace(2)**args[0]
140
+
141
+ #-------------------------------------------------------------------------
142
+ # Properties
143
+ #-------------------------------------------------------------------------
144
+
145
+ @property
146
+ def search_function(self):
147
+ """The unknown function that helps find the sought after qubits."""
148
+ return self.label[1]
149
+
150
+ @property
151
+ def targets(self):
152
+ """A tuple of target qubits."""
153
+ return sympify(tuple(range(self.args[0])))
154
+
155
+ #-------------------------------------------------------------------------
156
+ # Apply
157
+ #-------------------------------------------------------------------------
158
+
159
+ def _apply_operator_Qubit(self, qubits, **options):
160
+ """Apply this operator to a Qubit subclass.
161
+
162
+ Parameters
163
+ ==========
164
+
165
+ qubits : Qubit
166
+ The qubit subclass to apply this operator to.
167
+
168
+ Returns
169
+ =======
170
+
171
+ state : Expr
172
+ The resulting quantum state.
173
+ """
174
+ if qubits.nqubits != self.nqubits:
175
+ raise QuantumError(
176
+ 'OracleGate operates on %r qubits, got: %r'
177
+ % (self.nqubits, qubits.nqubits)
178
+ )
179
+ # If function returns 1 on qubits
180
+ # return the negative of the qubits (flip the sign)
181
+ if self.search_function(qubits):
182
+ return -qubits
183
+ else:
184
+ return qubits
185
+
186
+ #-------------------------------------------------------------------------
187
+ # Represent
188
+ #-------------------------------------------------------------------------
189
+
190
+ def _represent_ZGate(self, basis, **options):
191
+ """
192
+ Represent the OracleGate in the computational basis.
193
+ """
194
+ nbasis = 2**self.nqubits # compute it only once
195
+ matrixOracle = eye(nbasis)
196
+ # Flip the sign given the output of the oracle function
197
+ for i in range(nbasis):
198
+ if self.search_function(IntQubit(i, nqubits=self.nqubits)):
199
+ matrixOracle[i, i] = NegativeOne()
200
+ return matrixOracle
201
+
202
+
203
+ class WGate(Gate):
204
+ """General n qubit W Gate in Grover's algorithm.
205
+
206
+ The gate performs the operation ``2|phi><phi| - 1`` on some qubits.
207
+ ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)``
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ nqubits : int
213
+ The number of qubits to operate on
214
+
215
+ """
216
+
217
+ gate_name = 'W'
218
+ gate_name_latex = 'W'
219
+
220
+ @classmethod
221
+ def _eval_args(cls, args):
222
+ if len(args) != 1:
223
+ raise QuantumError(
224
+ 'Insufficient/excessive arguments to W gate. Please ' +
225
+ 'supply the number of qubits to operate on.'
226
+ )
227
+ args = UnitaryOperator._eval_args(args)
228
+ if not args[0].is_Integer:
229
+ raise TypeError('Integer expected, got: %r' % args[0])
230
+ return args
231
+
232
+ #-------------------------------------------------------------------------
233
+ # Properties
234
+ #-------------------------------------------------------------------------
235
+
236
+ @property
237
+ def targets(self):
238
+ return sympify(tuple(reversed(range(self.args[0]))))
239
+
240
+ #-------------------------------------------------------------------------
241
+ # Apply
242
+ #-------------------------------------------------------------------------
243
+
244
+ def _apply_operator_Qubit(self, qubits, **options):
245
+ """
246
+ qubits: a set of qubits (Qubit)
247
+ Returns: quantum object (quantum expression - QExpr)
248
+ """
249
+ if qubits.nqubits != self.nqubits:
250
+ raise QuantumError(
251
+ 'WGate operates on %r qubits, got: %r'
252
+ % (self.nqubits, qubits.nqubits)
253
+ )
254
+
255
+ # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result
256
+ # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis
257
+ # state and phi is the superposition of basis states (see function
258
+ # create_computational_basis above)
259
+ basis_states = superposition_basis(self.nqubits)
260
+ change_to_basis = (2/sqrt(2**self.nqubits))*basis_states
261
+ return change_to_basis - qubits
262
+
263
+
264
+ def grover_iteration(qstate, oracle):
265
+ """Applies one application of the Oracle and W Gate, WV.
266
+
267
+ Parameters
268
+ ==========
269
+
270
+ qstate : Qubit
271
+ A superposition of qubits.
272
+ oracle : OracleGate
273
+ The black box operator that flips the sign of the desired basis qubits.
274
+
275
+ Returns
276
+ =======
277
+
278
+ Qubit : The qubits after applying the Oracle and W gate.
279
+
280
+ Examples
281
+ ========
282
+
283
+ Perform one iteration of grover's algorithm to see a phase change::
284
+
285
+ >>> from sympy.physics.quantum.qapply import qapply
286
+ >>> from sympy.physics.quantum.qubit import IntQubit
287
+ >>> from sympy.physics.quantum.grover import OracleGate
288
+ >>> from sympy.physics.quantum.grover import superposition_basis
289
+ >>> from sympy.physics.quantum.grover import grover_iteration
290
+ >>> numqubits = 2
291
+ >>> basis_states = superposition_basis(numqubits)
292
+ >>> f = lambda qubits: qubits == IntQubit(2)
293
+ >>> v = OracleGate(numqubits, f)
294
+ >>> qapply(grover_iteration(basis_states, v))
295
+ |2>
296
+
297
+ """
298
+ wgate = WGate(oracle.nqubits)
299
+ return wgate*oracle*qstate
300
+
301
+
302
+ def apply_grover(oracle, nqubits, iterations=None):
303
+ """Applies grover's algorithm.
304
+
305
+ Parameters
306
+ ==========
307
+
308
+ oracle : callable
309
+ The unknown callable function that returns true when applied to the
310
+ desired qubits and false otherwise.
311
+
312
+ Returns
313
+ =======
314
+
315
+ state : Expr
316
+ The resulting state after Grover's algorithm has been iterated.
317
+
318
+ Examples
319
+ ========
320
+
321
+ Apply grover's algorithm to an even superposition of 2 qubits::
322
+
323
+ >>> from sympy.physics.quantum.qapply import qapply
324
+ >>> from sympy.physics.quantum.qubit import IntQubit
325
+ >>> from sympy.physics.quantum.grover import apply_grover
326
+ >>> f = lambda qubits: qubits == IntQubit(2)
327
+ >>> qapply(apply_grover(f, 2))
328
+ |2>
329
+
330
+ """
331
+ if nqubits <= 0:
332
+ raise QuantumError(
333
+ 'Grover\'s algorithm needs nqubits > 0, received %r qubits'
334
+ % nqubits
335
+ )
336
+ if iterations is None:
337
+ iterations = floor(sqrt(2**nqubits)*(pi/4))
338
+
339
+ v = OracleGate(nqubits, oracle)
340
+ iterated = superposition_basis(nqubits)
341
+ for iter in range(iterations):
342
+ iterated = grover_iteration(iterated, v)
343
+ iterated = qapply(iterated)
344
+
345
+ return iterated
venv/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from sympy.core.random import randint
3
+
4
+ from sympy.external import import_module
5
+ from sympy.core.basic import Basic
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.numbers import Number, equal_valued
8
+ from sympy.core.power import Pow
9
+ from sympy.core.singleton import S
10
+ from sympy.physics.quantum.represent import represent
11
+ from sympy.physics.quantum.dagger import Dagger
12
+
13
+ __all__ = [
14
+ # Public interfaces
15
+ 'generate_gate_rules',
16
+ 'generate_equivalent_ids',
17
+ 'GateIdentity',
18
+ 'bfs_identity_search',
19
+ 'random_identity_search',
20
+
21
+ # "Private" functions
22
+ 'is_scalar_sparse_matrix',
23
+ 'is_scalar_nonsparse_matrix',
24
+ 'is_degenerate',
25
+ 'is_reducible',
26
+ ]
27
+
28
+ np = import_module('numpy')
29
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
30
+
31
+
32
+ def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
33
+ """Checks if a given scipy.sparse matrix is a scalar matrix.
34
+
35
+ A scalar matrix is such that B = bI, where B is the scalar
36
+ matrix, b is some scalar multiple, and I is the identity
37
+ matrix. A scalar matrix would have only the element b along
38
+ it's main diagonal and zeroes elsewhere.
39
+
40
+ Parameters
41
+ ==========
42
+
43
+ circuit : Gate tuple
44
+ Sequence of quantum gates representing a quantum circuit
45
+ nqubits : int
46
+ Number of qubits in the circuit
47
+ identity_only : bool
48
+ Check for only identity matrices
49
+ eps : number
50
+ The tolerance value for zeroing out elements in the matrix.
51
+ Values in the range [-eps, +eps] will be changed to a zero.
52
+ """
53
+
54
+ if not np or not scipy:
55
+ pass
56
+
57
+ matrix = represent(Mul(*circuit), nqubits=nqubits,
58
+ format='scipy.sparse')
59
+
60
+ # In some cases, represent returns a 1D scalar value in place
61
+ # of a multi-dimensional scalar matrix
62
+ if (isinstance(matrix, int)):
63
+ return matrix == 1 if identity_only else True
64
+
65
+ # If represent returns a matrix, check if the matrix is diagonal
66
+ # and if every item along the diagonal is the same
67
+ else:
68
+ # Due to floating pointing operations, must zero out
69
+ # elements that are "very" small in the dense matrix
70
+ # See parameter for default value.
71
+
72
+ # Get the ndarray version of the dense matrix
73
+ dense_matrix = matrix.todense().getA()
74
+ # Since complex values can't be compared, must split
75
+ # the matrix into real and imaginary components
76
+ # Find the real values in between -eps and eps
77
+ bool_real = np.logical_and(dense_matrix.real > -eps,
78
+ dense_matrix.real < eps)
79
+ # Find the imaginary values between -eps and eps
80
+ bool_imag = np.logical_and(dense_matrix.imag > -eps,
81
+ dense_matrix.imag < eps)
82
+ # Replaces values between -eps and eps with 0
83
+ corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
84
+ corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
85
+ # Convert the matrix with real values into imaginary values
86
+ corrected_imag = corrected_imag * complex(1j)
87
+ # Recombine the real and imaginary components
88
+ corrected_dense = corrected_real + corrected_imag
89
+
90
+ # Check if it's diagonal
91
+ row_indices = corrected_dense.nonzero()[0]
92
+ col_indices = corrected_dense.nonzero()[1]
93
+ # Check if the rows indices and columns indices are the same
94
+ # If they match, then matrix only contains elements along diagonal
95
+ bool_indices = row_indices == col_indices
96
+ is_diagonal = bool_indices.all()
97
+
98
+ first_element = corrected_dense[0][0]
99
+ # If the first element is a zero, then can't rescale matrix
100
+ # and definitely not diagonal
101
+ if (first_element == 0.0 + 0.0j):
102
+ return False
103
+
104
+ # The dimensions of the dense matrix should still
105
+ # be 2^nqubits if there are elements all along the
106
+ # the main diagonal
107
+ trace_of_corrected = (corrected_dense/first_element).trace()
108
+ expected_trace = pow(2, nqubits)
109
+ has_correct_trace = trace_of_corrected == expected_trace
110
+
111
+ # If only looking for identity matrices
112
+ # first element must be a 1
113
+ real_is_one = abs(first_element.real - 1.0) < eps
114
+ imag_is_zero = abs(first_element.imag) < eps
115
+ is_one = real_is_one and imag_is_zero
116
+ is_identity = is_one if identity_only else True
117
+ return bool(is_diagonal and has_correct_trace and is_identity)
118
+
119
+
120
+ def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
121
+ """Checks if a given circuit, in matrix form, is equivalent to
122
+ a scalar value.
123
+
124
+ Parameters
125
+ ==========
126
+
127
+ circuit : Gate tuple
128
+ Sequence of quantum gates representing a quantum circuit
129
+ nqubits : int
130
+ Number of qubits in the circuit
131
+ identity_only : bool
132
+ Check for only identity matrices
133
+ eps : number
134
+ This argument is ignored. It is just for signature compatibility with
135
+ is_scalar_sparse_matrix.
136
+
137
+ Note: Used in situations when is_scalar_sparse_matrix has bugs
138
+ """
139
+
140
+ matrix = represent(Mul(*circuit), nqubits=nqubits)
141
+
142
+ # In some cases, represent returns a 1D scalar value in place
143
+ # of a multi-dimensional scalar matrix
144
+ if (isinstance(matrix, Number)):
145
+ return matrix == 1 if identity_only else True
146
+
147
+ # If represent returns a matrix, check if the matrix is diagonal
148
+ # and if every item along the diagonal is the same
149
+ else:
150
+ # Added up the diagonal elements
151
+ matrix_trace = matrix.trace()
152
+ # Divide the trace by the first element in the matrix
153
+ # if matrix is not required to be the identity matrix
154
+ adjusted_matrix_trace = (matrix_trace/matrix[0]
155
+ if not identity_only
156
+ else matrix_trace)
157
+
158
+ is_identity = equal_valued(matrix[0], 1) if identity_only else True
159
+
160
+ has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
161
+
162
+ # The matrix is scalar if it's diagonal and the adjusted trace
163
+ # value is equal to 2^nqubits
164
+ return bool(
165
+ matrix.is_diagonal() and has_correct_trace and is_identity)
166
+
167
+ if np and scipy:
168
+ is_scalar_matrix = is_scalar_sparse_matrix
169
+ else:
170
+ is_scalar_matrix = is_scalar_nonsparse_matrix
171
+
172
+
173
+ def _get_min_qubits(a_gate):
174
+ if isinstance(a_gate, Pow):
175
+ return a_gate.base.min_qubits
176
+ else:
177
+ return a_gate.min_qubits
178
+
179
+
180
+ def ll_op(left, right):
181
+ """Perform a LL operation.
182
+
183
+ A LL operation multiplies both left and right circuits
184
+ with the dagger of the left circuit's leftmost gate, and
185
+ the dagger is multiplied on the left side of both circuits.
186
+
187
+ If a LL is possible, it returns the new gate rule as a
188
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
189
+ and RHS is the right circuit of the new rule.
190
+ If a LL is not possible, None is returned.
191
+
192
+ Parameters
193
+ ==========
194
+
195
+ left : Gate tuple
196
+ The left circuit of a gate rule expression.
197
+ right : Gate tuple
198
+ The right circuit of a gate rule expression.
199
+
200
+ Examples
201
+ ========
202
+
203
+ Generate a new gate rule using a LL operation:
204
+
205
+ >>> from sympy.physics.quantum.identitysearch import ll_op
206
+ >>> from sympy.physics.quantum.gate import X, Y, Z
207
+ >>> x = X(0); y = Y(0); z = Z(0)
208
+ >>> ll_op((x, y, z), ())
209
+ ((Y(0), Z(0)), (X(0),))
210
+
211
+ >>> ll_op((y, z), (x,))
212
+ ((Z(0),), (Y(0), X(0)))
213
+ """
214
+
215
+ if (len(left) > 0):
216
+ ll_gate = left[0]
217
+ ll_gate_is_unitary = is_scalar_matrix(
218
+ (Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
219
+
220
+ if (len(left) > 0 and ll_gate_is_unitary):
221
+ # Get the new left side w/o the leftmost gate
222
+ new_left = left[1:len(left)]
223
+ # Add the leftmost gate to the left position on the right side
224
+ new_right = (Dagger(ll_gate),) + right
225
+ # Return the new gate rule
226
+ return (new_left, new_right)
227
+
228
+ return None
229
+
230
+
231
+ def lr_op(left, right):
232
+ """Perform a LR operation.
233
+
234
+ A LR operation multiplies both left and right circuits
235
+ with the dagger of the left circuit's rightmost gate, and
236
+ the dagger is multiplied on the right side of both circuits.
237
+
238
+ If a LR is possible, it returns the new gate rule as a
239
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
240
+ and RHS is the right circuit of the new rule.
241
+ If a LR is not possible, None is returned.
242
+
243
+ Parameters
244
+ ==========
245
+
246
+ left : Gate tuple
247
+ The left circuit of a gate rule expression.
248
+ right : Gate tuple
249
+ The right circuit of a gate rule expression.
250
+
251
+ Examples
252
+ ========
253
+
254
+ Generate a new gate rule using a LR operation:
255
+
256
+ >>> from sympy.physics.quantum.identitysearch import lr_op
257
+ >>> from sympy.physics.quantum.gate import X, Y, Z
258
+ >>> x = X(0); y = Y(0); z = Z(0)
259
+ >>> lr_op((x, y, z), ())
260
+ ((X(0), Y(0)), (Z(0),))
261
+
262
+ >>> lr_op((x, y), (z,))
263
+ ((X(0),), (Z(0), Y(0)))
264
+ """
265
+
266
+ if (len(left) > 0):
267
+ lr_gate = left[len(left) - 1]
268
+ lr_gate_is_unitary = is_scalar_matrix(
269
+ (Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
270
+
271
+ if (len(left) > 0 and lr_gate_is_unitary):
272
+ # Get the new left side w/o the rightmost gate
273
+ new_left = left[0:len(left) - 1]
274
+ # Add the rightmost gate to the right position on the right side
275
+ new_right = right + (Dagger(lr_gate),)
276
+ # Return the new gate rule
277
+ return (new_left, new_right)
278
+
279
+ return None
280
+
281
+
282
+ def rl_op(left, right):
283
+ """Perform a RL operation.
284
+
285
+ A RL operation multiplies both left and right circuits
286
+ with the dagger of the right circuit's leftmost gate, and
287
+ the dagger is multiplied on the left side of both circuits.
288
+
289
+ If a RL is possible, it returns the new gate rule as a
290
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
291
+ and RHS is the right circuit of the new rule.
292
+ If a RL is not possible, None is returned.
293
+
294
+ Parameters
295
+ ==========
296
+
297
+ left : Gate tuple
298
+ The left circuit of a gate rule expression.
299
+ right : Gate tuple
300
+ The right circuit of a gate rule expression.
301
+
302
+ Examples
303
+ ========
304
+
305
+ Generate a new gate rule using a RL operation:
306
+
307
+ >>> from sympy.physics.quantum.identitysearch import rl_op
308
+ >>> from sympy.physics.quantum.gate import X, Y, Z
309
+ >>> x = X(0); y = Y(0); z = Z(0)
310
+ >>> rl_op((x,), (y, z))
311
+ ((Y(0), X(0)), (Z(0),))
312
+
313
+ >>> rl_op((x, y), (z,))
314
+ ((Z(0), X(0), Y(0)), ())
315
+ """
316
+
317
+ if (len(right) > 0):
318
+ rl_gate = right[0]
319
+ rl_gate_is_unitary = is_scalar_matrix(
320
+ (Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
321
+
322
+ if (len(right) > 0 and rl_gate_is_unitary):
323
+ # Get the new right side w/o the leftmost gate
324
+ new_right = right[1:len(right)]
325
+ # Add the leftmost gate to the left position on the left side
326
+ new_left = (Dagger(rl_gate),) + left
327
+ # Return the new gate rule
328
+ return (new_left, new_right)
329
+
330
+ return None
331
+
332
+
333
+ def rr_op(left, right):
334
+ """Perform a RR operation.
335
+
336
+ A RR operation multiplies both left and right circuits
337
+ with the dagger of the right circuit's rightmost gate, and
338
+ the dagger is multiplied on the right side of both circuits.
339
+
340
+ If a RR is possible, it returns the new gate rule as a
341
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
342
+ and RHS is the right circuit of the new rule.
343
+ If a RR is not possible, None is returned.
344
+
345
+ Parameters
346
+ ==========
347
+
348
+ left : Gate tuple
349
+ The left circuit of a gate rule expression.
350
+ right : Gate tuple
351
+ The right circuit of a gate rule expression.
352
+
353
+ Examples
354
+ ========
355
+
356
+ Generate a new gate rule using a RR operation:
357
+
358
+ >>> from sympy.physics.quantum.identitysearch import rr_op
359
+ >>> from sympy.physics.quantum.gate import X, Y, Z
360
+ >>> x = X(0); y = Y(0); z = Z(0)
361
+ >>> rr_op((x, y), (z,))
362
+ ((X(0), Y(0), Z(0)), ())
363
+
364
+ >>> rr_op((x,), (y, z))
365
+ ((X(0), Z(0)), (Y(0),))
366
+ """
367
+
368
+ if (len(right) > 0):
369
+ rr_gate = right[len(right) - 1]
370
+ rr_gate_is_unitary = is_scalar_matrix(
371
+ (Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
372
+
373
+ if (len(right) > 0 and rr_gate_is_unitary):
374
+ # Get the new right side w/o the rightmost gate
375
+ new_right = right[0:len(right) - 1]
376
+ # Add the rightmost gate to the right position on the right side
377
+ new_left = left + (Dagger(rr_gate),)
378
+ # Return the new gate rule
379
+ return (new_left, new_right)
380
+
381
+ return None
382
+
383
+
384
+ def generate_gate_rules(gate_seq, return_as_muls=False):
385
+ """Returns a set of gate rules. Each gate rules is represented
386
+ as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
387
+ scalar value.
388
+
389
+ This function uses the four operations (LL, LR, RL, RR)
390
+ to generate the gate rules.
391
+
392
+ A gate rule is an expression such as ABC = D or AB = CD, where
393
+ A, B, C, and D are gates. Each value on either side of the
394
+ equal sign represents a circuit. The four operations allow
395
+ one to find a set of equivalent circuits from a gate identity.
396
+ The letters denoting the operation tell the user what
397
+ activities to perform on each expression. The first letter
398
+ indicates which side of the equal sign to focus on. The
399
+ second letter indicates which gate to focus on given the
400
+ side. Once this information is determined, the inverse
401
+ of the gate is multiplied on both circuits to create a new
402
+ gate rule.
403
+
404
+ For example, given the identity, ABCD = 1, a LL operation
405
+ means look at the left value and multiply both left sides by the
406
+ inverse of the leftmost gate A. If A is Hermitian, the inverse
407
+ of A is still A. The resulting new rule is BCD = A.
408
+
409
+ The following is a summary of the four operations. Assume
410
+ that in the examples, all gates are Hermitian.
411
+
412
+ LL : left circuit, left multiply
413
+ ABCD = E -> AABCD = AE -> BCD = AE
414
+ LR : left circuit, right multiply
415
+ ABCD = E -> ABCDD = ED -> ABC = ED
416
+ RL : right circuit, left multiply
417
+ ABC = ED -> EABC = EED -> EABC = D
418
+ RR : right circuit, right multiply
419
+ AB = CD -> ABD = CDD -> ABD = C
420
+
421
+ The number of gate rules generated is n*(n+1), where n
422
+ is the number of gates in the sequence (unproven).
423
+
424
+ Parameters
425
+ ==========
426
+
427
+ gate_seq : Gate tuple, Mul, or Number
428
+ A variable length tuple or Mul of Gates whose product is equal to
429
+ a scalar matrix
430
+ return_as_muls : bool
431
+ True to return a set of Muls; False to return a set of tuples
432
+
433
+ Examples
434
+ ========
435
+
436
+ Find the gate rules of the current circuit using tuples:
437
+
438
+ >>> from sympy.physics.quantum.identitysearch import generate_gate_rules
439
+ >>> from sympy.physics.quantum.gate import X, Y, Z
440
+ >>> x = X(0); y = Y(0); z = Z(0)
441
+ >>> generate_gate_rules((x, x))
442
+ {((X(0),), (X(0),)), ((X(0), X(0)), ())}
443
+
444
+ >>> generate_gate_rules((x, y, z))
445
+ {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
446
+ ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
447
+ ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
448
+ ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
449
+ ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
450
+ ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
451
+
452
+ Find the gate rules of the current circuit using Muls:
453
+
454
+ >>> generate_gate_rules(x*x, return_as_muls=True)
455
+ {(1, 1)}
456
+
457
+ >>> generate_gate_rules(x*y*z, return_as_muls=True)
458
+ {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
459
+ (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
460
+ (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
461
+ (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
462
+ (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
463
+ (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
464
+ """
465
+
466
+ if isinstance(gate_seq, Number):
467
+ if return_as_muls:
468
+ return {(S.One, S.One)}
469
+ else:
470
+ return {((), ())}
471
+
472
+ elif isinstance(gate_seq, Mul):
473
+ gate_seq = gate_seq.args
474
+
475
+ # Each item in queue is a 3-tuple:
476
+ # i) first item is the left side of an equality
477
+ # ii) second item is the right side of an equality
478
+ # iii) third item is the number of operations performed
479
+ # The argument, gate_seq, will start on the left side, and
480
+ # the right side will be empty, implying the presence of an
481
+ # identity.
482
+ queue = deque()
483
+ # A set of gate rules
484
+ rules = set()
485
+ # Maximum number of operations to perform
486
+ max_ops = len(gate_seq)
487
+
488
+ def process_new_rule(new_rule, ops):
489
+ if new_rule is not None:
490
+ new_left, new_right = new_rule
491
+
492
+ if new_rule not in rules and (new_right, new_left) not in rules:
493
+ rules.add(new_rule)
494
+ # If haven't reached the max limit on operations
495
+ if ops + 1 < max_ops:
496
+ queue.append(new_rule + (ops + 1,))
497
+
498
+ queue.append((gate_seq, (), 0))
499
+ rules.add((gate_seq, ()))
500
+
501
+ while len(queue) > 0:
502
+ left, right, ops = queue.popleft()
503
+
504
+ # Do a LL
505
+ new_rule = ll_op(left, right)
506
+ process_new_rule(new_rule, ops)
507
+ # Do a LR
508
+ new_rule = lr_op(left, right)
509
+ process_new_rule(new_rule, ops)
510
+ # Do a RL
511
+ new_rule = rl_op(left, right)
512
+ process_new_rule(new_rule, ops)
513
+ # Do a RR
514
+ new_rule = rr_op(left, right)
515
+ process_new_rule(new_rule, ops)
516
+
517
+ if return_as_muls:
518
+ # Convert each rule as tuples into a rule as muls
519
+ mul_rules = set()
520
+ for rule in rules:
521
+ left, right = rule
522
+ mul_rules.add((Mul(*left), Mul(*right)))
523
+
524
+ rules = mul_rules
525
+
526
+ return rules
527
+
528
+
529
+ def generate_equivalent_ids(gate_seq, return_as_muls=False):
530
+ """Returns a set of equivalent gate identities.
531
+
532
+ A gate identity is a quantum circuit such that the product
533
+ of the gates in the circuit is equal to a scalar value.
534
+ For example, XYZ = i, where X, Y, Z are the Pauli gates and
535
+ i is the imaginary value, is considered a gate identity.
536
+
537
+ This function uses the four operations (LL, LR, RL, RR)
538
+ to generate the gate rules and, subsequently, to locate equivalent
539
+ gate identities.
540
+
541
+ Note that all equivalent identities are reachable in n operations
542
+ from the starting gate identity, where n is the number of gates
543
+ in the sequence.
544
+
545
+ The max number of gate identities is 2n, where n is the number
546
+ of gates in the sequence (unproven).
547
+
548
+ Parameters
549
+ ==========
550
+
551
+ gate_seq : Gate tuple, Mul, or Number
552
+ A variable length tuple or Mul of Gates whose product is equal to
553
+ a scalar matrix.
554
+ return_as_muls: bool
555
+ True to return as Muls; False to return as tuples
556
+
557
+ Examples
558
+ ========
559
+
560
+ Find equivalent gate identities from the current circuit with tuples:
561
+
562
+ >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
563
+ >>> from sympy.physics.quantum.gate import X, Y, Z
564
+ >>> x = X(0); y = Y(0); z = Z(0)
565
+ >>> generate_equivalent_ids((x, x))
566
+ {(X(0), X(0))}
567
+
568
+ >>> generate_equivalent_ids((x, y, z))
569
+ {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
570
+ (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
571
+
572
+ Find equivalent gate identities from the current circuit with Muls:
573
+
574
+ >>> generate_equivalent_ids(x*x, return_as_muls=True)
575
+ {1}
576
+
577
+ >>> generate_equivalent_ids(x*y*z, return_as_muls=True)
578
+ {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
579
+ Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
580
+ """
581
+
582
+ if isinstance(gate_seq, Number):
583
+ return {S.One}
584
+ elif isinstance(gate_seq, Mul):
585
+ gate_seq = gate_seq.args
586
+
587
+ # Filter through the gate rules and keep the rules
588
+ # with an empty tuple either on the left or right side
589
+
590
+ # A set of equivalent gate identities
591
+ eq_ids = set()
592
+
593
+ gate_rules = generate_gate_rules(gate_seq)
594
+ for rule in gate_rules:
595
+ l, r = rule
596
+ if l == ():
597
+ eq_ids.add(r)
598
+ elif r == ():
599
+ eq_ids.add(l)
600
+
601
+ if return_as_muls:
602
+ convert_to_mul = lambda id_seq: Mul(*id_seq)
603
+ eq_ids = set(map(convert_to_mul, eq_ids))
604
+
605
+ return eq_ids
606
+
607
+
608
+ class GateIdentity(Basic):
609
+ """Wrapper class for circuits that reduce to a scalar value.
610
+
611
+ A gate identity is a quantum circuit such that the product
612
+ of the gates in the circuit is equal to a scalar value.
613
+ For example, XYZ = i, where X, Y, Z are the Pauli gates and
614
+ i is the imaginary value, is considered a gate identity.
615
+
616
+ Parameters
617
+ ==========
618
+
619
+ args : Gate tuple
620
+ A variable length tuple of Gates that form an identity.
621
+
622
+ Examples
623
+ ========
624
+
625
+ Create a GateIdentity and look at its attributes:
626
+
627
+ >>> from sympy.physics.quantum.identitysearch import GateIdentity
628
+ >>> from sympy.physics.quantum.gate import X, Y, Z
629
+ >>> x = X(0); y = Y(0); z = Z(0)
630
+ >>> an_identity = GateIdentity(x, y, z)
631
+ >>> an_identity.circuit
632
+ X(0)*Y(0)*Z(0)
633
+
634
+ >>> an_identity.equivalent_ids
635
+ {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
636
+ (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
637
+ """
638
+
639
+ def __new__(cls, *args):
640
+ # args should be a tuple - a variable length argument list
641
+ obj = Basic.__new__(cls, *args)
642
+ obj._circuit = Mul(*args)
643
+ obj._rules = generate_gate_rules(args)
644
+ obj._eq_ids = generate_equivalent_ids(args)
645
+
646
+ return obj
647
+
648
+ @property
649
+ def circuit(self):
650
+ return self._circuit
651
+
652
+ @property
653
+ def gate_rules(self):
654
+ return self._rules
655
+
656
+ @property
657
+ def equivalent_ids(self):
658
+ return self._eq_ids
659
+
660
+ @property
661
+ def sequence(self):
662
+ return self.args
663
+
664
+ def __str__(self):
665
+ """Returns the string of gates in a tuple."""
666
+ return str(self.circuit)
667
+
668
+
669
+ def is_degenerate(identity_set, gate_identity):
670
+ """Checks if a gate identity is a permutation of another identity.
671
+
672
+ Parameters
673
+ ==========
674
+
675
+ identity_set : set
676
+ A Python set with GateIdentity objects.
677
+ gate_identity : GateIdentity
678
+ The GateIdentity to check for existence in the set.
679
+
680
+ Examples
681
+ ========
682
+
683
+ Check if the identity is a permutation of another identity:
684
+
685
+ >>> from sympy.physics.quantum.identitysearch import (
686
+ ... GateIdentity, is_degenerate)
687
+ >>> from sympy.physics.quantum.gate import X, Y, Z
688
+ >>> x = X(0); y = Y(0); z = Z(0)
689
+ >>> an_identity = GateIdentity(x, y, z)
690
+ >>> id_set = {an_identity}
691
+ >>> another_id = (y, z, x)
692
+ >>> is_degenerate(id_set, another_id)
693
+ True
694
+
695
+ >>> another_id = (x, x)
696
+ >>> is_degenerate(id_set, another_id)
697
+ False
698
+ """
699
+
700
+ # For now, just iteratively go through the set and check if the current
701
+ # gate_identity is a permutation of an identity in the set
702
+ for an_id in identity_set:
703
+ if (gate_identity in an_id.equivalent_ids):
704
+ return True
705
+ return False
706
+
707
+
708
+ def is_reducible(circuit, nqubits, begin, end):
709
+ """Determines if a circuit is reducible by checking
710
+ if its subcircuits are scalar values.
711
+
712
+ Parameters
713
+ ==========
714
+
715
+ circuit : Gate tuple
716
+ A tuple of Gates representing a circuit. The circuit to check
717
+ if a gate identity is contained in a subcircuit.
718
+ nqubits : int
719
+ The number of qubits the circuit operates on.
720
+ begin : int
721
+ The leftmost gate in the circuit to include in a subcircuit.
722
+ end : int
723
+ The rightmost gate in the circuit to include in a subcircuit.
724
+
725
+ Examples
726
+ ========
727
+
728
+ Check if the circuit can be reduced:
729
+
730
+ >>> from sympy.physics.quantum.identitysearch import is_reducible
731
+ >>> from sympy.physics.quantum.gate import X, Y, Z
732
+ >>> x = X(0); y = Y(0); z = Z(0)
733
+ >>> is_reducible((x, y, z), 1, 0, 3)
734
+ True
735
+
736
+ Check if an interval in the circuit can be reduced:
737
+
738
+ >>> is_reducible((x, y, z), 1, 1, 3)
739
+ False
740
+
741
+ >>> is_reducible((x, y, y), 1, 1, 3)
742
+ True
743
+ """
744
+
745
+ current_circuit = ()
746
+ # Start from the gate at "end" and go down to almost the gate at "begin"
747
+ for ndx in reversed(range(begin, end)):
748
+ next_gate = circuit[ndx]
749
+ current_circuit = (next_gate,) + current_circuit
750
+
751
+ # If a circuit as a matrix is equivalent to a scalar value
752
+ if (is_scalar_matrix(current_circuit, nqubits, False)):
753
+ return True
754
+
755
+ return False
756
+
757
+
758
+ def bfs_identity_search(gate_list, nqubits, max_depth=None,
759
+ identity_only=False):
760
+ """Constructs a set of gate identities from the list of possible gates.
761
+
762
+ Performs a breadth first search over the space of gate identities.
763
+ This allows the finding of the shortest gate identities first.
764
+
765
+ Parameters
766
+ ==========
767
+
768
+ gate_list : list, Gate
769
+ A list of Gates from which to search for gate identities.
770
+ nqubits : int
771
+ The number of qubits the quantum circuit operates on.
772
+ max_depth : int
773
+ The longest quantum circuit to construct from gate_list.
774
+ identity_only : bool
775
+ True to search for gate identities that reduce to identity;
776
+ False to search for gate identities that reduce to a scalar.
777
+
778
+ Examples
779
+ ========
780
+
781
+ Find a list of gate identities:
782
+
783
+ >>> from sympy.physics.quantum.identitysearch import bfs_identity_search
784
+ >>> from sympy.physics.quantum.gate import X, Y, Z
785
+ >>> x = X(0); y = Y(0); z = Z(0)
786
+ >>> bfs_identity_search([x], 1, max_depth=2)
787
+ {GateIdentity(X(0), X(0))}
788
+
789
+ >>> bfs_identity_search([x, y, z], 1)
790
+ {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
791
+ GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
792
+
793
+ Find a list of identities that only equal to 1:
794
+
795
+ >>> bfs_identity_search([x, y, z], 1, identity_only=True)
796
+ {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
797
+ GateIdentity(Z(0), Z(0))}
798
+ """
799
+
800
+ if max_depth is None or max_depth <= 0:
801
+ max_depth = len(gate_list)
802
+
803
+ id_only = identity_only
804
+
805
+ # Start with an empty sequence (implicitly contains an IdentityGate)
806
+ queue = deque([()])
807
+
808
+ # Create an empty set of gate identities
809
+ ids = set()
810
+
811
+ # Begin searching for gate identities in given space.
812
+ while (len(queue) > 0):
813
+ current_circuit = queue.popleft()
814
+
815
+ for next_gate in gate_list:
816
+ new_circuit = current_circuit + (next_gate,)
817
+
818
+ # Determines if a (strict) subcircuit is a scalar matrix
819
+ circuit_reducible = is_reducible(new_circuit, nqubits,
820
+ 1, len(new_circuit))
821
+
822
+ # In many cases when the matrix is a scalar value,
823
+ # the evaluated matrix will actually be an integer
824
+ if (is_scalar_matrix(new_circuit, nqubits, id_only) and
825
+ not is_degenerate(ids, new_circuit) and
826
+ not circuit_reducible):
827
+ ids.add(GateIdentity(*new_circuit))
828
+
829
+ elif (len(new_circuit) < max_depth and
830
+ not circuit_reducible):
831
+ queue.append(new_circuit)
832
+
833
+ return ids
834
+
835
+
836
+ def random_identity_search(gate_list, numgates, nqubits):
837
+ """Randomly selects numgates from gate_list and checks if it is
838
+ a gate identity.
839
+
840
+ If the circuit is a gate identity, the circuit is returned;
841
+ Otherwise, None is returned.
842
+ """
843
+
844
+ gate_size = len(gate_list)
845
+ circuit = ()
846
+
847
+ for i in range(numgates):
848
+ next_gate = gate_list[randint(0, gate_size - 1)]
849
+ circuit = circuit + (next_gate,)
850
+
851
+ is_scalar = is_scalar_matrix(circuit, nqubits, False)
852
+
853
+ return circuit if is_scalar else None
venv/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Symbolic inner product."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.functions.elementary.complexes import conjugate
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ from sympy.physics.quantum.dagger import Dagger
7
+ from sympy.physics.quantum.state import KetBase, BraBase
8
+
9
+ __all__ = [
10
+ 'InnerProduct'
11
+ ]
12
+
13
+
14
+ # InnerProduct is not an QExpr because it is really just a regular commutative
15
+ # number. We have gone back and forth about this, but we gain a lot by having
16
+ # it subclass Expr. The main challenges were getting Dagger to work
17
+ # (we use _eval_conjugate) and represent (we can use atoms and subs). Having
18
+ # it be an Expr, mean that there are no commutative QExpr subclasses,
19
+ # which simplifies the design of everything.
20
+
21
+ class InnerProduct(Expr):
22
+ """An unevaluated inner product between a Bra and a Ket [1].
23
+
24
+ Parameters
25
+ ==========
26
+
27
+ bra : BraBase or subclass
28
+ The bra on the left side of the inner product.
29
+ ket : KetBase or subclass
30
+ The ket on the right side of the inner product.
31
+
32
+ Examples
33
+ ========
34
+
35
+ Create an InnerProduct and check its properties:
36
+
37
+ >>> from sympy.physics.quantum import Bra, Ket
38
+ >>> b = Bra('b')
39
+ >>> k = Ket('k')
40
+ >>> ip = b*k
41
+ >>> ip
42
+ <b|k>
43
+ >>> ip.bra
44
+ <b|
45
+ >>> ip.ket
46
+ |k>
47
+
48
+ In simple products of kets and bras inner products will be automatically
49
+ identified and created::
50
+
51
+ >>> b*k
52
+ <b|k>
53
+
54
+ But in more complex expressions, there is ambiguity in whether inner or
55
+ outer products should be created::
56
+
57
+ >>> k*b*k*b
58
+ |k><b|*|k>*<b|
59
+
60
+ A user can force the creation of a inner products in a complex expression
61
+ by using parentheses to group the bra and ket::
62
+
63
+ >>> k*(b*k)*b
64
+ <b|k>*|k>*<b|
65
+
66
+ Notice how the inner product <b|k> moved to the left of the expression
67
+ because inner products are commutative complex numbers.
68
+
69
+ References
70
+ ==========
71
+
72
+ .. [1] https://en.wikipedia.org/wiki/Inner_product
73
+ """
74
+ is_complex = True
75
+
76
+ def __new__(cls, bra, ket):
77
+ if not isinstance(ket, KetBase):
78
+ raise TypeError('KetBase subclass expected, got: %r' % ket)
79
+ if not isinstance(bra, BraBase):
80
+ raise TypeError('BraBase subclass expected, got: %r' % ket)
81
+ obj = Expr.__new__(cls, bra, ket)
82
+ return obj
83
+
84
+ @property
85
+ def bra(self):
86
+ return self.args[0]
87
+
88
+ @property
89
+ def ket(self):
90
+ return self.args[1]
91
+
92
+ def _eval_conjugate(self):
93
+ return InnerProduct(Dagger(self.ket), Dagger(self.bra))
94
+
95
+ def _sympyrepr(self, printer, *args):
96
+ return '%s(%s,%s)' % (self.__class__.__name__,
97
+ printer._print(self.bra, *args), printer._print(self.ket, *args))
98
+
99
+ def _sympystr(self, printer, *args):
100
+ sbra = printer._print(self.bra)
101
+ sket = printer._print(self.ket)
102
+ return '%s|%s' % (sbra[:-1], sket[1:])
103
+
104
+ def _pretty(self, printer, *args):
105
+ # Print state contents
106
+ bra = self.bra._print_contents_pretty(printer, *args)
107
+ ket = self.ket._print_contents_pretty(printer, *args)
108
+ # Print brackets
109
+ height = max(bra.height(), ket.height())
110
+ use_unicode = printer._use_unicode
111
+ lbracket, _ = self.bra._pretty_brackets(height, use_unicode)
112
+ cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode)
113
+ # Build innerproduct
114
+ pform = prettyForm(*bra.left(lbracket))
115
+ pform = prettyForm(*pform.right(cbracket))
116
+ pform = prettyForm(*pform.right(ket))
117
+ pform = prettyForm(*pform.right(rbracket))
118
+ return pform
119
+
120
+ def _latex(self, printer, *args):
121
+ bra_label = self.bra._print_contents_latex(printer, *args)
122
+ ket = printer._print(self.ket, *args)
123
+ return r'\left\langle %s \right. %s' % (bra_label, ket)
124
+
125
+ def doit(self, **hints):
126
+ try:
127
+ r = self.ket._eval_innerproduct(self.bra, **hints)
128
+ except NotImplementedError:
129
+ try:
130
+ r = conjugate(
131
+ self.bra.dual._eval_innerproduct(self.ket.dual, **hints)
132
+ )
133
+ except NotImplementedError:
134
+ r = None
135
+ if r is not None:
136
+ return r
137
+ return self
venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A cache for storing small matrices in multiple formats."""
2
+
3
+ from sympy.core.numbers import (I, Rational, pi)
4
+ from sympy.core.power import Pow
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.matrices.dense import Matrix
7
+
8
+ from sympy.physics.quantum.matrixutils import (
9
+ to_sympy, to_numpy, to_scipy_sparse
10
+ )
11
+
12
+
13
+ class MatrixCache:
14
+ """A cache for small matrices in different formats.
15
+
16
+ This class takes small matrices in the standard ``sympy.Matrix`` format,
17
+ and then converts these to both ``numpy.matrix`` and
18
+ ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for
19
+ future recovery.
20
+ """
21
+
22
+ def __init__(self, dtype='complex'):
23
+ self._cache = {}
24
+ self.dtype = dtype
25
+
26
+ def cache_matrix(self, name, m):
27
+ """Cache a matrix by its name.
28
+
29
+ Parameters
30
+ ----------
31
+ name : str
32
+ A descriptive name for the matrix, like "identity2".
33
+ m : list of lists
34
+ The raw matrix data as a SymPy Matrix.
35
+ """
36
+ try:
37
+ self._sympy_matrix(name, m)
38
+ except ImportError:
39
+ pass
40
+ try:
41
+ self._numpy_matrix(name, m)
42
+ except ImportError:
43
+ pass
44
+ try:
45
+ self._scipy_sparse_matrix(name, m)
46
+ except ImportError:
47
+ pass
48
+
49
+ def get_matrix(self, name, format):
50
+ """Get a cached matrix by name and format.
51
+
52
+ Parameters
53
+ ----------
54
+ name : str
55
+ A descriptive name for the matrix, like "identity2".
56
+ format : str
57
+ The format desired ('sympy', 'numpy', 'scipy.sparse')
58
+ """
59
+ m = self._cache.get((name, format))
60
+ if m is not None:
61
+ return m
62
+ raise NotImplementedError(
63
+ 'Matrix with name %s and format %s is not available.' %
64
+ (name, format)
65
+ )
66
+
67
+ def _store_matrix(self, name, format, m):
68
+ self._cache[(name, format)] = m
69
+
70
+ def _sympy_matrix(self, name, m):
71
+ self._store_matrix(name, 'sympy', to_sympy(m))
72
+
73
+ def _numpy_matrix(self, name, m):
74
+ m = to_numpy(m, dtype=self.dtype)
75
+ self._store_matrix(name, 'numpy', m)
76
+
77
+ def _scipy_sparse_matrix(self, name, m):
78
+ # TODO: explore different sparse formats. But sparse.kron will use
79
+ # coo in most cases, so we use that here.
80
+ m = to_scipy_sparse(m, dtype=self.dtype)
81
+ self._store_matrix(name, 'scipy.sparse', m)
82
+
83
+
84
+ sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False)
85
+
86
+ # Save the common matrices that we will need
87
+ matrix_cache = MatrixCache()
88
+ matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]]))
89
+ matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1|
90
+ matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0|
91
+ matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0|
92
+ matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1|
93
+ matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]]))
94
+ matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]]))
95
+ matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]]))
96
+ matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]]))
97
+ matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]]))
98
+ matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
99
+ matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]]))
100
+ matrix_cache.cache_matrix(
101
+ 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]))
102
+ matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]]))
103
+ matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
venv/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.numbers import I
5
+ from sympy.core.singleton import S
6
+ from sympy.matrices.matrices import MatrixBase
7
+ from sympy.matrices import eye, zeros
8
+ from sympy.external import import_module
9
+
10
+ __all__ = [
11
+ 'numpy_ndarray',
12
+ 'scipy_sparse_matrix',
13
+ 'sympy_to_numpy',
14
+ 'sympy_to_scipy_sparse',
15
+ 'numpy_to_sympy',
16
+ 'scipy_sparse_to_sympy',
17
+ 'flatten_scalar',
18
+ 'matrix_dagger',
19
+ 'to_sympy',
20
+ 'to_numpy',
21
+ 'to_scipy_sparse',
22
+ 'matrix_tensor_product',
23
+ 'matrix_zeros'
24
+ ]
25
+
26
+ # Conditionally define the base classes for numpy and scipy.sparse arrays
27
+ # for use in isinstance tests.
28
+
29
+ np = import_module('numpy')
30
+ if not np:
31
+ class numpy_ndarray:
32
+ pass
33
+ else:
34
+ numpy_ndarray = np.ndarray # type: ignore
35
+
36
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
37
+ if not scipy:
38
+ class scipy_sparse_matrix:
39
+ pass
40
+ sparse = None
41
+ else:
42
+ sparse = scipy.sparse
43
+ scipy_sparse_matrix = sparse.spmatrix # type: ignore
44
+
45
+
46
+ def sympy_to_numpy(m, **options):
47
+ """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
48
+ if not np:
49
+ raise ImportError
50
+ dtype = options.get('dtype', 'complex')
51
+ if isinstance(m, MatrixBase):
52
+ return np.array(m.tolist(), dtype=dtype)
53
+ elif isinstance(m, Expr):
54
+ if m.is_Number or m.is_NumberSymbol or m == I:
55
+ return complex(m)
56
+ raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
57
+
58
+
59
+ def sympy_to_scipy_sparse(m, **options):
60
+ """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
61
+ if not np or not sparse:
62
+ raise ImportError
63
+ dtype = options.get('dtype', 'complex')
64
+ if isinstance(m, MatrixBase):
65
+ return sparse.csr_matrix(np.array(m.tolist(), dtype=dtype))
66
+ elif isinstance(m, Expr):
67
+ if m.is_Number or m.is_NumberSymbol or m == I:
68
+ return complex(m)
69
+ raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
70
+
71
+
72
+ def scipy_sparse_to_sympy(m, **options):
73
+ """Convert a scipy.sparse matrix to a SymPy matrix."""
74
+ return MatrixBase(m.todense())
75
+
76
+
77
+ def numpy_to_sympy(m, **options):
78
+ """Convert a numpy matrix to a SymPy matrix."""
79
+ return MatrixBase(m)
80
+
81
+
82
+ def to_sympy(m, **options):
83
+ """Convert a numpy/scipy.sparse matrix to a SymPy matrix."""
84
+ if isinstance(m, MatrixBase):
85
+ return m
86
+ elif isinstance(m, numpy_ndarray):
87
+ return numpy_to_sympy(m)
88
+ elif isinstance(m, scipy_sparse_matrix):
89
+ return scipy_sparse_to_sympy(m)
90
+ elif isinstance(m, Expr):
91
+ return m
92
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
93
+
94
+
95
+ def to_numpy(m, **options):
96
+ """Convert a sympy/scipy.sparse matrix to a numpy matrix."""
97
+ dtype = options.get('dtype', 'complex')
98
+ if isinstance(m, (MatrixBase, Expr)):
99
+ return sympy_to_numpy(m, dtype=dtype)
100
+ elif isinstance(m, numpy_ndarray):
101
+ return m
102
+ elif isinstance(m, scipy_sparse_matrix):
103
+ return m.todense()
104
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
105
+
106
+
107
+ def to_scipy_sparse(m, **options):
108
+ """Convert a sympy/numpy matrix to a scipy.sparse matrix."""
109
+ dtype = options.get('dtype', 'complex')
110
+ if isinstance(m, (MatrixBase, Expr)):
111
+ return sympy_to_scipy_sparse(m, dtype=dtype)
112
+ elif isinstance(m, numpy_ndarray):
113
+ if not sparse:
114
+ raise ImportError
115
+ return sparse.csr_matrix(m)
116
+ elif isinstance(m, scipy_sparse_matrix):
117
+ return m
118
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
119
+
120
+
121
+ def flatten_scalar(e):
122
+ """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged."""
123
+ if isinstance(e, MatrixBase):
124
+ if e.shape == (1, 1):
125
+ e = e[0]
126
+ if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
127
+ if e.shape == (1, 1):
128
+ e = complex(e[0, 0])
129
+ return e
130
+
131
+
132
+ def matrix_dagger(e):
133
+ """Return the dagger of a sympy/numpy/scipy.sparse matrix."""
134
+ if isinstance(e, MatrixBase):
135
+ return e.H
136
+ elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
137
+ return e.conjugate().transpose()
138
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e)
139
+
140
+
141
+ # TODO: Move this into sympy.matricies.
142
+ def _sympy_tensor_product(*matrices):
143
+ """Compute the kronecker product of a sequence of SymPy Matrices.
144
+ """
145
+ from sympy.matrices.expressions.kronecker import matrix_kronecker_product
146
+
147
+ return matrix_kronecker_product(*matrices)
148
+
149
+
150
+ def _numpy_tensor_product(*product):
151
+ """numpy version of tensor product of multiple arguments."""
152
+ if not np:
153
+ raise ImportError
154
+ answer = product[0]
155
+ for item in product[1:]:
156
+ answer = np.kron(answer, item)
157
+ return answer
158
+
159
+
160
+ def _scipy_sparse_tensor_product(*product):
161
+ """scipy.sparse version of tensor product of multiple arguments."""
162
+ if not sparse:
163
+ raise ImportError
164
+ answer = product[0]
165
+ for item in product[1:]:
166
+ answer = sparse.kron(answer, item)
167
+ # The final matrices will just be multiplied, so csr is a good final
168
+ # sparse format.
169
+ return sparse.csr_matrix(answer)
170
+
171
+
172
+ def matrix_tensor_product(*product):
173
+ """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices."""
174
+ if isinstance(product[0], MatrixBase):
175
+ return _sympy_tensor_product(*product)
176
+ elif isinstance(product[0], numpy_ndarray):
177
+ return _numpy_tensor_product(*product)
178
+ elif isinstance(product[0], scipy_sparse_matrix):
179
+ return _scipy_sparse_tensor_product(*product)
180
+
181
+
182
+ def _numpy_eye(n):
183
+ """numpy version of complex eye."""
184
+ if not np:
185
+ raise ImportError
186
+ return np.array(np.eye(n, dtype='complex'))
187
+
188
+
189
+ def _scipy_sparse_eye(n):
190
+ """scipy.sparse version of complex eye."""
191
+ if not sparse:
192
+ raise ImportError
193
+ return sparse.eye(n, n, dtype='complex')
194
+
195
+
196
+ def matrix_eye(n, **options):
197
+ """Get the version of eye and tensor_product for a given format."""
198
+ format = options.get('format', 'sympy')
199
+ if format == 'sympy':
200
+ return eye(n)
201
+ elif format == 'numpy':
202
+ return _numpy_eye(n)
203
+ elif format == 'scipy.sparse':
204
+ return _scipy_sparse_eye(n)
205
+ raise NotImplementedError('Invalid format: %r' % format)
206
+
207
+
208
+ def _numpy_zeros(m, n, **options):
209
+ """numpy version of zeros."""
210
+ dtype = options.get('dtype', 'float64')
211
+ if not np:
212
+ raise ImportError
213
+ return np.zeros((m, n), dtype=dtype)
214
+
215
+
216
+ def _scipy_sparse_zeros(m, n, **options):
217
+ """scipy.sparse version of zeros."""
218
+ spmatrix = options.get('spmatrix', 'csr')
219
+ dtype = options.get('dtype', 'float64')
220
+ if not sparse:
221
+ raise ImportError
222
+ if spmatrix == 'lil':
223
+ return sparse.lil_matrix((m, n), dtype=dtype)
224
+ elif spmatrix == 'csr':
225
+ return sparse.csr_matrix((m, n), dtype=dtype)
226
+
227
+
228
+ def matrix_zeros(m, n, **options):
229
+ """"Get a zeros matrix for a given format."""
230
+ format = options.get('format', 'sympy')
231
+ if format == 'sympy':
232
+ return zeros(m, n)
233
+ elif format == 'numpy':
234
+ return _numpy_zeros(m, n, **options)
235
+ elif format == 'scipy.sparse':
236
+ return _scipy_sparse_zeros(m, n, **options)
237
+ raise NotImplementedError('Invaild format: %r' % format)
238
+
239
+
240
+ def _numpy_matrix_to_zero(e):
241
+ """Convert a numpy zero matrix to the zero scalar."""
242
+ if not np:
243
+ raise ImportError
244
+ test = np.zeros_like(e)
245
+ if np.allclose(e, test):
246
+ return 0.0
247
+ else:
248
+ return e
249
+
250
+
251
+ def _scipy_sparse_matrix_to_zero(e):
252
+ """Convert a scipy.sparse zero matrix to the zero scalar."""
253
+ if not np:
254
+ raise ImportError
255
+ edense = e.todense()
256
+ test = np.zeros_like(edense)
257
+ if np.allclose(edense, test):
258
+ return 0.0
259
+ else:
260
+ return e
261
+
262
+
263
+ def matrix_to_zero(e):
264
+ """Convert a zero matrix to the scalar zero."""
265
+ if isinstance(e, MatrixBase):
266
+ if zeros(*e.shape) == e:
267
+ e = S.Zero
268
+ elif isinstance(e, numpy_ndarray):
269
+ e = _numpy_matrix_to_zero(e)
270
+ elif isinstance(e, scipy_sparse_matrix):
271
+ e = _scipy_sparse_matrix_to_zero(e)
272
+ return e
venv/lib/python3.10/site-packages/sympy/physics/quantum/operator.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quantum mechanical operators.
2
+
3
+ TODO:
4
+
5
+ * Fix early 0 in apply_operators.
6
+ * Debug and test apply_operators.
7
+ * Get cse working with classes in this file.
8
+ * Doctests and documentation of special methods for InnerProduct, Commutator,
9
+ AntiCommutator, represent, apply_operators.
10
+ """
11
+
12
+ from sympy.core.add import Add
13
+ from sympy.core.expr import Expr
14
+ from sympy.core.function import (Derivative, expand)
15
+ from sympy.core.mul import Mul
16
+ from sympy.core.numbers import oo
17
+ from sympy.core.singleton import S
18
+ from sympy.printing.pretty.stringpict import prettyForm
19
+ from sympy.physics.quantum.dagger import Dagger
20
+ from sympy.physics.quantum.qexpr import QExpr, dispatch_method
21
+ from sympy.matrices import eye
22
+
23
+ __all__ = [
24
+ 'Operator',
25
+ 'HermitianOperator',
26
+ 'UnitaryOperator',
27
+ 'IdentityOperator',
28
+ 'OuterProduct',
29
+ 'DifferentialOperator'
30
+ ]
31
+
32
+ #-----------------------------------------------------------------------------
33
+ # Operators and outer products
34
+ #-----------------------------------------------------------------------------
35
+
36
+
37
+ class Operator(QExpr):
38
+ """Base class for non-commuting quantum operators.
39
+
40
+ An operator maps between quantum states [1]_. In quantum mechanics,
41
+ observables (including, but not limited to, measured physical values) are
42
+ represented as Hermitian operators [2]_.
43
+
44
+ Parameters
45
+ ==========
46
+
47
+ args : tuple
48
+ The list of numbers or parameters that uniquely specify the
49
+ operator. For time-dependent operators, this will include the time.
50
+
51
+ Examples
52
+ ========
53
+
54
+ Create an operator and examine its attributes::
55
+
56
+ >>> from sympy.physics.quantum import Operator
57
+ >>> from sympy import I
58
+ >>> A = Operator('A')
59
+ >>> A
60
+ A
61
+ >>> A.hilbert_space
62
+ H
63
+ >>> A.label
64
+ (A,)
65
+ >>> A.is_commutative
66
+ False
67
+
68
+ Create another operator and do some arithmetic operations::
69
+
70
+ >>> B = Operator('B')
71
+ >>> C = 2*A*A + I*B
72
+ >>> C
73
+ 2*A**2 + I*B
74
+
75
+ Operators do not commute::
76
+
77
+ >>> A.is_commutative
78
+ False
79
+ >>> B.is_commutative
80
+ False
81
+ >>> A*B == B*A
82
+ False
83
+
84
+ Polymonials of operators respect the commutation properties::
85
+
86
+ >>> e = (A+B)**3
87
+ >>> e.expand()
88
+ A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
89
+
90
+ Operator inverses are handle symbolically::
91
+
92
+ >>> A.inv()
93
+ A**(-1)
94
+ >>> A*A.inv()
95
+ 1
96
+
97
+ References
98
+ ==========
99
+
100
+ .. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
101
+ .. [2] https://en.wikipedia.org/wiki/Observable
102
+ """
103
+
104
+ @classmethod
105
+ def default_args(self):
106
+ return ("O",)
107
+
108
+ #-------------------------------------------------------------------------
109
+ # Printing
110
+ #-------------------------------------------------------------------------
111
+
112
+ _label_separator = ','
113
+
114
+ def _print_operator_name(self, printer, *args):
115
+ return self.__class__.__name__
116
+
117
+ _print_operator_name_latex = _print_operator_name
118
+
119
+ def _print_operator_name_pretty(self, printer, *args):
120
+ return prettyForm(self.__class__.__name__)
121
+
122
+ def _print_contents(self, printer, *args):
123
+ if len(self.label) == 1:
124
+ return self._print_label(printer, *args)
125
+ else:
126
+ return '%s(%s)' % (
127
+ self._print_operator_name(printer, *args),
128
+ self._print_label(printer, *args)
129
+ )
130
+
131
+ def _print_contents_pretty(self, printer, *args):
132
+ if len(self.label) == 1:
133
+ return self._print_label_pretty(printer, *args)
134
+ else:
135
+ pform = self._print_operator_name_pretty(printer, *args)
136
+ label_pform = self._print_label_pretty(printer, *args)
137
+ label_pform = prettyForm(
138
+ *label_pform.parens(left='(', right=')')
139
+ )
140
+ pform = prettyForm(*pform.right(label_pform))
141
+ return pform
142
+
143
+ def _print_contents_latex(self, printer, *args):
144
+ if len(self.label) == 1:
145
+ return self._print_label_latex(printer, *args)
146
+ else:
147
+ return r'%s\left(%s\right)' % (
148
+ self._print_operator_name_latex(printer, *args),
149
+ self._print_label_latex(printer, *args)
150
+ )
151
+
152
+ #-------------------------------------------------------------------------
153
+ # _eval_* methods
154
+ #-------------------------------------------------------------------------
155
+
156
+ def _eval_commutator(self, other, **options):
157
+ """Evaluate [self, other] if known, return None if not known."""
158
+ return dispatch_method(self, '_eval_commutator', other, **options)
159
+
160
+ def _eval_anticommutator(self, other, **options):
161
+ """Evaluate [self, other] if known."""
162
+ return dispatch_method(self, '_eval_anticommutator', other, **options)
163
+
164
+ #-------------------------------------------------------------------------
165
+ # Operator application
166
+ #-------------------------------------------------------------------------
167
+
168
+ def _apply_operator(self, ket, **options):
169
+ return dispatch_method(self, '_apply_operator', ket, **options)
170
+
171
+ def matrix_element(self, *args):
172
+ raise NotImplementedError('matrix_elements is not defined')
173
+
174
+ def inverse(self):
175
+ return self._eval_inverse()
176
+
177
+ inv = inverse
178
+
179
+ def _eval_inverse(self):
180
+ return self**(-1)
181
+
182
+ def __mul__(self, other):
183
+
184
+ if isinstance(other, IdentityOperator):
185
+ return self
186
+
187
+ return Mul(self, other)
188
+
189
+
190
+ class HermitianOperator(Operator):
191
+ """A Hermitian operator that satisfies H == Dagger(H).
192
+
193
+ Parameters
194
+ ==========
195
+
196
+ args : tuple
197
+ The list of numbers or parameters that uniquely specify the
198
+ operator. For time-dependent operators, this will include the time.
199
+
200
+ Examples
201
+ ========
202
+
203
+ >>> from sympy.physics.quantum import Dagger, HermitianOperator
204
+ >>> H = HermitianOperator('H')
205
+ >>> Dagger(H)
206
+ H
207
+ """
208
+
209
+ is_hermitian = True
210
+
211
+ def _eval_inverse(self):
212
+ if isinstance(self, UnitaryOperator):
213
+ return self
214
+ else:
215
+ return Operator._eval_inverse(self)
216
+
217
+ def _eval_power(self, exp):
218
+ if isinstance(self, UnitaryOperator):
219
+ # so all eigenvalues of self are 1 or -1
220
+ if exp.is_even:
221
+ from sympy.core.singleton import S
222
+ return S.One # is identity, see Issue 24153.
223
+ elif exp.is_odd:
224
+ return self
225
+ # No simplification in all other cases
226
+ return Operator._eval_power(self, exp)
227
+
228
+
229
+ class UnitaryOperator(Operator):
230
+ """A unitary operator that satisfies U*Dagger(U) == 1.
231
+
232
+ Parameters
233
+ ==========
234
+
235
+ args : tuple
236
+ The list of numbers or parameters that uniquely specify the
237
+ operator. For time-dependent operators, this will include the time.
238
+
239
+ Examples
240
+ ========
241
+
242
+ >>> from sympy.physics.quantum import Dagger, UnitaryOperator
243
+ >>> U = UnitaryOperator('U')
244
+ >>> U*Dagger(U)
245
+ 1
246
+ """
247
+
248
+ def _eval_adjoint(self):
249
+ return self._eval_inverse()
250
+
251
+
252
+ class IdentityOperator(Operator):
253
+ """An identity operator I that satisfies op * I == I * op == op for any
254
+ operator op.
255
+
256
+ Parameters
257
+ ==========
258
+
259
+ N : Integer
260
+ Optional parameter that specifies the dimension of the Hilbert space
261
+ of operator. This is used when generating a matrix representation.
262
+
263
+ Examples
264
+ ========
265
+
266
+ >>> from sympy.physics.quantum import IdentityOperator
267
+ >>> IdentityOperator()
268
+ I
269
+ """
270
+ @property
271
+ def dimension(self):
272
+ return self.N
273
+
274
+ @classmethod
275
+ def default_args(self):
276
+ return (oo,)
277
+
278
+ def __init__(self, *args, **hints):
279
+ if not len(args) in (0, 1):
280
+ raise ValueError('0 or 1 parameters expected, got %s' % args)
281
+
282
+ self.N = args[0] if (len(args) == 1 and args[0]) else oo
283
+
284
+ def _eval_commutator(self, other, **hints):
285
+ return S.Zero
286
+
287
+ def _eval_anticommutator(self, other, **hints):
288
+ return 2 * other
289
+
290
+ def _eval_inverse(self):
291
+ return self
292
+
293
+ def _eval_adjoint(self):
294
+ return self
295
+
296
+ def _apply_operator(self, ket, **options):
297
+ return ket
298
+
299
+ def _apply_from_right_to(self, bra, **options):
300
+ return bra
301
+
302
+ def _eval_power(self, exp):
303
+ return self
304
+
305
+ def _print_contents(self, printer, *args):
306
+ return 'I'
307
+
308
+ def _print_contents_pretty(self, printer, *args):
309
+ return prettyForm('I')
310
+
311
+ def _print_contents_latex(self, printer, *args):
312
+ return r'{\mathcal{I}}'
313
+
314
+ def __mul__(self, other):
315
+
316
+ if isinstance(other, (Operator, Dagger)):
317
+ return other
318
+
319
+ return Mul(self, other)
320
+
321
+ def _represent_default_basis(self, **options):
322
+ if not self.N or self.N == oo:
323
+ raise NotImplementedError('Cannot represent infinite dimensional' +
324
+ ' identity operator as a matrix')
325
+
326
+ format = options.get('format', 'sympy')
327
+ if format != 'sympy':
328
+ raise NotImplementedError('Representation in format ' +
329
+ '%s not implemented.' % format)
330
+
331
+ return eye(self.N)
332
+
333
+
334
+ class OuterProduct(Operator):
335
+ """An unevaluated outer product between a ket and bra.
336
+
337
+ This constructs an outer product between any subclass of ``KetBase`` and
338
+ ``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
339
+ operators in quantum expressions. For reference see [1]_.
340
+
341
+ Parameters
342
+ ==========
343
+
344
+ ket : KetBase
345
+ The ket on the left side of the outer product.
346
+ bar : BraBase
347
+ The bra on the right side of the outer product.
348
+
349
+ Examples
350
+ ========
351
+
352
+ Create a simple outer product by hand and take its dagger::
353
+
354
+ >>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
355
+ >>> from sympy.physics.quantum import Operator
356
+
357
+ >>> k = Ket('k')
358
+ >>> b = Bra('b')
359
+ >>> op = OuterProduct(k, b)
360
+ >>> op
361
+ |k><b|
362
+ >>> op.hilbert_space
363
+ H
364
+ >>> op.ket
365
+ |k>
366
+ >>> op.bra
367
+ <b|
368
+ >>> Dagger(op)
369
+ |b><k|
370
+
371
+ In simple products of kets and bras outer products will be automatically
372
+ identified and created::
373
+
374
+ >>> k*b
375
+ |k><b|
376
+
377
+ But in more complex expressions, outer products are not automatically
378
+ created::
379
+
380
+ >>> A = Operator('A')
381
+ >>> A*k*b
382
+ A*|k>*<b|
383
+
384
+ A user can force the creation of an outer product in a complex expression
385
+ by using parentheses to group the ket and bra::
386
+
387
+ >>> A*(k*b)
388
+ A*|k><b|
389
+
390
+ References
391
+ ==========
392
+
393
+ .. [1] https://en.wikipedia.org/wiki/Outer_product
394
+ """
395
+ is_commutative = False
396
+
397
+ def __new__(cls, *args, **old_assumptions):
398
+ from sympy.physics.quantum.state import KetBase, BraBase
399
+
400
+ if len(args) != 2:
401
+ raise ValueError('2 parameters expected, got %d' % len(args))
402
+
403
+ ket_expr = expand(args[0])
404
+ bra_expr = expand(args[1])
405
+
406
+ if (isinstance(ket_expr, (KetBase, Mul)) and
407
+ isinstance(bra_expr, (BraBase, Mul))):
408
+ ket_c, kets = ket_expr.args_cnc()
409
+ bra_c, bras = bra_expr.args_cnc()
410
+
411
+ if len(kets) != 1 or not isinstance(kets[0], KetBase):
412
+ raise TypeError('KetBase subclass expected'
413
+ ', got: %r' % Mul(*kets))
414
+
415
+ if len(bras) != 1 or not isinstance(bras[0], BraBase):
416
+ raise TypeError('BraBase subclass expected'
417
+ ', got: %r' % Mul(*bras))
418
+
419
+ if not kets[0].dual_class() == bras[0].__class__:
420
+ raise TypeError(
421
+ 'ket and bra are not dual classes: %r, %r' %
422
+ (kets[0].__class__, bras[0].__class__)
423
+ )
424
+
425
+ # TODO: make sure the hilbert spaces of the bra and ket are
426
+ # compatible
427
+ obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
428
+ obj.hilbert_space = kets[0].hilbert_space
429
+ return Mul(*(ket_c + bra_c)) * obj
430
+
431
+ op_terms = []
432
+ if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
433
+ for ket_term in ket_expr.args:
434
+ for bra_term in bra_expr.args:
435
+ op_terms.append(OuterProduct(ket_term, bra_term,
436
+ **old_assumptions))
437
+ elif isinstance(ket_expr, Add):
438
+ for ket_term in ket_expr.args:
439
+ op_terms.append(OuterProduct(ket_term, bra_expr,
440
+ **old_assumptions))
441
+ elif isinstance(bra_expr, Add):
442
+ for bra_term in bra_expr.args:
443
+ op_terms.append(OuterProduct(ket_expr, bra_term,
444
+ **old_assumptions))
445
+ else:
446
+ raise TypeError(
447
+ 'Expected ket and bra expression, got: %r, %r' %
448
+ (ket_expr, bra_expr)
449
+ )
450
+
451
+ return Add(*op_terms)
452
+
453
+ @property
454
+ def ket(self):
455
+ """Return the ket on the left side of the outer product."""
456
+ return self.args[0]
457
+
458
+ @property
459
+ def bra(self):
460
+ """Return the bra on the right side of the outer product."""
461
+ return self.args[1]
462
+
463
+ def _eval_adjoint(self):
464
+ return OuterProduct(Dagger(self.bra), Dagger(self.ket))
465
+
466
+ def _sympystr(self, printer, *args):
467
+ return printer._print(self.ket) + printer._print(self.bra)
468
+
469
+ def _sympyrepr(self, printer, *args):
470
+ return '%s(%s,%s)' % (self.__class__.__name__,
471
+ printer._print(self.ket, *args), printer._print(self.bra, *args))
472
+
473
+ def _pretty(self, printer, *args):
474
+ pform = self.ket._pretty(printer, *args)
475
+ return prettyForm(*pform.right(self.bra._pretty(printer, *args)))
476
+
477
+ def _latex(self, printer, *args):
478
+ k = printer._print(self.ket, *args)
479
+ b = printer._print(self.bra, *args)
480
+ return k + b
481
+
482
+ def _represent(self, **options):
483
+ k = self.ket._represent(**options)
484
+ b = self.bra._represent(**options)
485
+ return k*b
486
+
487
+ def _eval_trace(self, **kwargs):
488
+ # TODO if operands are tensorproducts this may be will be handled
489
+ # differently.
490
+
491
+ return self.ket._eval_trace(self.bra, **kwargs)
492
+
493
+
494
+ class DifferentialOperator(Operator):
495
+ """An operator for representing the differential operator, i.e. d/dx
496
+
497
+ It is initialized by passing two arguments. The first is an arbitrary
498
+ expression that involves a function, such as ``Derivative(f(x), x)``. The
499
+ second is the function (e.g. ``f(x)``) which we are to replace with the
500
+ ``Wavefunction`` that this ``DifferentialOperator`` is applied to.
501
+
502
+ Parameters
503
+ ==========
504
+
505
+ expr : Expr
506
+ The arbitrary expression which the appropriate Wavefunction is to be
507
+ substituted into
508
+
509
+ func : Expr
510
+ A function (e.g. f(x)) which is to be replaced with the appropriate
511
+ Wavefunction when this DifferentialOperator is applied
512
+
513
+ Examples
514
+ ========
515
+
516
+ You can define a completely arbitrary expression and specify where the
517
+ Wavefunction is to be substituted
518
+
519
+ >>> from sympy import Derivative, Function, Symbol
520
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
521
+ >>> from sympy.physics.quantum.state import Wavefunction
522
+ >>> from sympy.physics.quantum.qapply import qapply
523
+ >>> f = Function('f')
524
+ >>> x = Symbol('x')
525
+ >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
526
+ >>> w = Wavefunction(x**2, x)
527
+ >>> d.function
528
+ f(x)
529
+ >>> d.variables
530
+ (x,)
531
+ >>> qapply(d*w)
532
+ Wavefunction(2, x)
533
+
534
+ """
535
+
536
+ @property
537
+ def variables(self):
538
+ """
539
+ Returns the variables with which the function in the specified
540
+ arbitrary expression is evaluated
541
+
542
+ Examples
543
+ ========
544
+
545
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
546
+ >>> from sympy import Symbol, Function, Derivative
547
+ >>> x = Symbol('x')
548
+ >>> f = Function('f')
549
+ >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
550
+ >>> d.variables
551
+ (x,)
552
+ >>> y = Symbol('y')
553
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
554
+ ... Derivative(f(x, y), y), f(x, y))
555
+ >>> d.variables
556
+ (x, y)
557
+ """
558
+
559
+ return self.args[-1].args
560
+
561
+ @property
562
+ def function(self):
563
+ """
564
+ Returns the function which is to be replaced with the Wavefunction
565
+
566
+ Examples
567
+ ========
568
+
569
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
570
+ >>> from sympy import Function, Symbol, Derivative
571
+ >>> x = Symbol('x')
572
+ >>> f = Function('f')
573
+ >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
574
+ >>> d.function
575
+ f(x)
576
+ >>> y = Symbol('y')
577
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
578
+ ... Derivative(f(x, y), y), f(x, y))
579
+ >>> d.function
580
+ f(x, y)
581
+ """
582
+
583
+ return self.args[-1]
584
+
585
+ @property
586
+ def expr(self):
587
+ """
588
+ Returns the arbitrary expression which is to have the Wavefunction
589
+ substituted into it
590
+
591
+ Examples
592
+ ========
593
+
594
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
595
+ >>> from sympy import Function, Symbol, Derivative
596
+ >>> x = Symbol('x')
597
+ >>> f = Function('f')
598
+ >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
599
+ >>> d.expr
600
+ Derivative(f(x), x)
601
+ >>> y = Symbol('y')
602
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
603
+ ... Derivative(f(x, y), y), f(x, y))
604
+ >>> d.expr
605
+ Derivative(f(x, y), x) + Derivative(f(x, y), y)
606
+ """
607
+
608
+ return self.args[0]
609
+
610
+ @property
611
+ def free_symbols(self):
612
+ """
613
+ Return the free symbols of the expression.
614
+ """
615
+
616
+ return self.expr.free_symbols
617
+
618
+ def _apply_operator_Wavefunction(self, func, **options):
619
+ from sympy.physics.quantum.state import Wavefunction
620
+ var = self.variables
621
+ wf_vars = func.args[1:]
622
+
623
+ f = self.function
624
+ new_expr = self.expr.subs(f, func(*var))
625
+ new_expr = new_expr.doit()
626
+
627
+ return Wavefunction(new_expr, *wf_vars)
628
+
629
+ def _eval_derivative(self, symbol):
630
+ new_expr = Derivative(self.expr, symbol)
631
+ return DifferentialOperator(new_expr, self.args[-1])
632
+
633
+ #-------------------------------------------------------------------------
634
+ # Printing
635
+ #-------------------------------------------------------------------------
636
+
637
+ def _print(self, printer, *args):
638
+ return '%s(%s)' % (
639
+ self._print_operator_name(printer, *args),
640
+ self._print_label(printer, *args)
641
+ )
642
+
643
+ def _print_pretty(self, printer, *args):
644
+ pform = self._print_operator_name_pretty(printer, *args)
645
+ label_pform = self._print_label_pretty(printer, *args)
646
+ label_pform = prettyForm(
647
+ *label_pform.parens(left='(', right=')')
648
+ )
649
+ pform = prettyForm(*pform.right(label_pform))
650
+ return pform
venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for reordering operator expressions."""
2
+
3
+ import warnings
4
+
5
+ from sympy.core.add import Add
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.numbers import Integer
8
+ from sympy.core.power import Pow
9
+ from sympy.physics.quantum import Operator, Commutator, AntiCommutator
10
+ from sympy.physics.quantum.boson import BosonOp
11
+ from sympy.physics.quantum.fermion import FermionOp
12
+
13
+ __all__ = [
14
+ 'normal_order',
15
+ 'normal_ordered_form'
16
+ ]
17
+
18
+
19
+ def _expand_powers(factors):
20
+ """
21
+ Helper function for normal_ordered_form and normal_order: Expand a
22
+ power expression to a multiplication expression so that that the
23
+ expression can be handled by the normal ordering functions.
24
+ """
25
+
26
+ new_factors = []
27
+ for factor in factors.args:
28
+ if (isinstance(factor, Pow)
29
+ and isinstance(factor.args[1], Integer)
30
+ and factor.args[1] > 0):
31
+ for n in range(factor.args[1]):
32
+ new_factors.append(factor.args[0])
33
+ else:
34
+ new_factors.append(factor)
35
+
36
+ return new_factors
37
+
38
+
39
+ def _normal_ordered_form_factor(product, independent=False, recursive_limit=10,
40
+ _recursive_depth=0):
41
+ """
42
+ Helper function for normal_ordered_form_factor: Write multiplication
43
+ expression with bosonic or fermionic operators on normally ordered form,
44
+ using the bosonic and fermionic commutation relations. The resulting
45
+ operator expression is equivalent to the argument, but will in general be
46
+ a sum of operator products instead of a simple product.
47
+ """
48
+
49
+ factors = _expand_powers(product)
50
+
51
+ new_factors = []
52
+ n = 0
53
+ while n < len(factors) - 1:
54
+
55
+ if isinstance(factors[n], BosonOp):
56
+ # boson
57
+ if not isinstance(factors[n + 1], BosonOp):
58
+ new_factors.append(factors[n])
59
+
60
+ elif factors[n].is_annihilation == factors[n + 1].is_annihilation:
61
+ if (independent and
62
+ str(factors[n].name) > str(factors[n + 1].name)):
63
+ new_factors.append(factors[n + 1])
64
+ new_factors.append(factors[n])
65
+ n += 1
66
+ else:
67
+ new_factors.append(factors[n])
68
+
69
+ elif not factors[n].is_annihilation:
70
+ new_factors.append(factors[n])
71
+
72
+ else:
73
+ if factors[n + 1].is_annihilation:
74
+ new_factors.append(factors[n])
75
+ else:
76
+ if factors[n].args[0] != factors[n + 1].args[0]:
77
+ if independent:
78
+ c = 0
79
+ else:
80
+ c = Commutator(factors[n], factors[n + 1])
81
+ new_factors.append(factors[n + 1] * factors[n] + c)
82
+ else:
83
+ c = Commutator(factors[n], factors[n + 1])
84
+ new_factors.append(
85
+ factors[n + 1] * factors[n] + c.doit())
86
+ n += 1
87
+
88
+ elif isinstance(factors[n], FermionOp):
89
+ # fermion
90
+ if not isinstance(factors[n + 1], FermionOp):
91
+ new_factors.append(factors[n])
92
+
93
+ elif factors[n].is_annihilation == factors[n + 1].is_annihilation:
94
+ if (independent and
95
+ str(factors[n].name) > str(factors[n + 1].name)):
96
+ new_factors.append(factors[n + 1])
97
+ new_factors.append(factors[n])
98
+ n += 1
99
+ else:
100
+ new_factors.append(factors[n])
101
+
102
+ elif not factors[n].is_annihilation:
103
+ new_factors.append(factors[n])
104
+
105
+ else:
106
+ if factors[n + 1].is_annihilation:
107
+ new_factors.append(factors[n])
108
+ else:
109
+ if factors[n].args[0] != factors[n + 1].args[0]:
110
+ if independent:
111
+ c = 0
112
+ else:
113
+ c = AntiCommutator(factors[n], factors[n + 1])
114
+ new_factors.append(-factors[n + 1] * factors[n] + c)
115
+ else:
116
+ c = AntiCommutator(factors[n], factors[n + 1])
117
+ new_factors.append(
118
+ -factors[n + 1] * factors[n] + c.doit())
119
+ n += 1
120
+
121
+ elif isinstance(factors[n], Operator):
122
+
123
+ if isinstance(factors[n + 1], (BosonOp, FermionOp)):
124
+ new_factors.append(factors[n + 1])
125
+ new_factors.append(factors[n])
126
+ n += 1
127
+ else:
128
+ new_factors.append(factors[n])
129
+
130
+ else:
131
+ new_factors.append(factors[n])
132
+
133
+ n += 1
134
+
135
+ if n == len(factors) - 1:
136
+ new_factors.append(factors[-1])
137
+
138
+ if new_factors == factors:
139
+ return product
140
+ else:
141
+ expr = Mul(*new_factors).expand()
142
+ return normal_ordered_form(expr,
143
+ recursive_limit=recursive_limit,
144
+ _recursive_depth=_recursive_depth + 1,
145
+ independent=independent)
146
+
147
+
148
+ def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10,
149
+ _recursive_depth=0):
150
+ """
151
+ Helper function for normal_ordered_form: loop through each term in an
152
+ addition expression and call _normal_ordered_form_factor to perform the
153
+ factor to an normally ordered expression.
154
+ """
155
+
156
+ new_terms = []
157
+ for term in expr.args:
158
+ if isinstance(term, Mul):
159
+ new_term = _normal_ordered_form_factor(
160
+ term, recursive_limit=recursive_limit,
161
+ _recursive_depth=_recursive_depth, independent=independent)
162
+ new_terms.append(new_term)
163
+ else:
164
+ new_terms.append(term)
165
+
166
+ return Add(*new_terms)
167
+
168
+
169
+ def normal_ordered_form(expr, independent=False, recursive_limit=10,
170
+ _recursive_depth=0):
171
+ """Write an expression with bosonic or fermionic operators on normal
172
+ ordered form, where each term is normally ordered. Note that this
173
+ normal ordered form is equivalent to the original expression.
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ expr : expression
179
+ The expression write on normal ordered form.
180
+
181
+ recursive_limit : int (default 10)
182
+ The number of allowed recursive applications of the function.
183
+
184
+ Examples
185
+ ========
186
+
187
+ >>> from sympy.physics.quantum import Dagger
188
+ >>> from sympy.physics.quantum.boson import BosonOp
189
+ >>> from sympy.physics.quantum.operatorordering import normal_ordered_form
190
+ >>> a = BosonOp("a")
191
+ >>> normal_ordered_form(a * Dagger(a))
192
+ 1 + Dagger(a)*a
193
+ """
194
+
195
+ if _recursive_depth > recursive_limit:
196
+ warnings.warn("Too many recursions, aborting")
197
+ return expr
198
+
199
+ if isinstance(expr, Add):
200
+ return _normal_ordered_form_terms(expr,
201
+ recursive_limit=recursive_limit,
202
+ _recursive_depth=_recursive_depth,
203
+ independent=independent)
204
+ elif isinstance(expr, Mul):
205
+ return _normal_ordered_form_factor(expr,
206
+ recursive_limit=recursive_limit,
207
+ _recursive_depth=_recursive_depth,
208
+ independent=independent)
209
+ else:
210
+ return expr
211
+
212
+
213
+ def _normal_order_factor(product, recursive_limit=10, _recursive_depth=0):
214
+ """
215
+ Helper function for normal_order: Normal order a multiplication expression
216
+ with bosonic or fermionic operators. In general the resulting operator
217
+ expression will not be equivalent to original product.
218
+ """
219
+
220
+ factors = _expand_powers(product)
221
+
222
+ n = 0
223
+ new_factors = []
224
+ while n < len(factors) - 1:
225
+
226
+ if (isinstance(factors[n], BosonOp) and
227
+ factors[n].is_annihilation):
228
+ # boson
229
+ if not isinstance(factors[n + 1], BosonOp):
230
+ new_factors.append(factors[n])
231
+ else:
232
+ if factors[n + 1].is_annihilation:
233
+ new_factors.append(factors[n])
234
+ else:
235
+ if factors[n].args[0] != factors[n + 1].args[0]:
236
+ new_factors.append(factors[n + 1] * factors[n])
237
+ else:
238
+ new_factors.append(factors[n + 1] * factors[n])
239
+ n += 1
240
+
241
+ elif (isinstance(factors[n], FermionOp) and
242
+ factors[n].is_annihilation):
243
+ # fermion
244
+ if not isinstance(factors[n + 1], FermionOp):
245
+ new_factors.append(factors[n])
246
+ else:
247
+ if factors[n + 1].is_annihilation:
248
+ new_factors.append(factors[n])
249
+ else:
250
+ if factors[n].args[0] != factors[n + 1].args[0]:
251
+ new_factors.append(-factors[n + 1] * factors[n])
252
+ else:
253
+ new_factors.append(-factors[n + 1] * factors[n])
254
+ n += 1
255
+
256
+ else:
257
+ new_factors.append(factors[n])
258
+
259
+ n += 1
260
+
261
+ if n == len(factors) - 1:
262
+ new_factors.append(factors[-1])
263
+
264
+ if new_factors == factors:
265
+ return product
266
+ else:
267
+ expr = Mul(*new_factors).expand()
268
+ return normal_order(expr,
269
+ recursive_limit=recursive_limit,
270
+ _recursive_depth=_recursive_depth + 1)
271
+
272
+
273
+ def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0):
274
+ """
275
+ Helper function for normal_order: look through each term in an addition
276
+ expression and call _normal_order_factor to perform the normal ordering
277
+ on the factors.
278
+ """
279
+
280
+ new_terms = []
281
+ for term in expr.args:
282
+ if isinstance(term, Mul):
283
+ new_term = _normal_order_factor(term,
284
+ recursive_limit=recursive_limit,
285
+ _recursive_depth=_recursive_depth)
286
+ new_terms.append(new_term)
287
+ else:
288
+ new_terms.append(term)
289
+
290
+ return Add(*new_terms)
291
+
292
+
293
+ def normal_order(expr, recursive_limit=10, _recursive_depth=0):
294
+ """Normal order an expression with bosonic or fermionic operators. Note
295
+ that this normal order is not equivalent to the original expression, but
296
+ the creation and annihilation operators in each term in expr is reordered
297
+ so that the expression becomes normal ordered.
298
+
299
+ Parameters
300
+ ==========
301
+
302
+ expr : expression
303
+ The expression to normal order.
304
+
305
+ recursive_limit : int (default 10)
306
+ The number of allowed recursive applications of the function.
307
+
308
+ Examples
309
+ ========
310
+
311
+ >>> from sympy.physics.quantum import Dagger
312
+ >>> from sympy.physics.quantum.boson import BosonOp
313
+ >>> from sympy.physics.quantum.operatorordering import normal_order
314
+ >>> a = BosonOp("a")
315
+ >>> normal_order(a * Dagger(a))
316
+ Dagger(a)*a
317
+ """
318
+ if _recursive_depth > recursive_limit:
319
+ warnings.warn("Too many recursions, aborting")
320
+ return expr
321
+
322
+ if isinstance(expr, Add):
323
+ return _normal_order_terms(expr, recursive_limit=recursive_limit,
324
+ _recursive_depth=_recursive_depth)
325
+ elif isinstance(expr, Mul):
326
+ return _normal_order_factor(expr, recursive_limit=recursive_limit,
327
+ _recursive_depth=_recursive_depth)
328
+ else:
329
+ return expr
venv/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ A module for mapping operators to their corresponding eigenstates
2
+ and vice versa
3
+
4
+ It contains a global dictionary with eigenstate-operator pairings.
5
+ If a new state-operator pair is created, this dictionary should be
6
+ updated as well.
7
+
8
+ It also contains functions operators_to_state and state_to_operators
9
+ for mapping between the two. These can handle both classes and
10
+ instances of operators and states. See the individual function
11
+ descriptions for details.
12
+
13
+ TODO List:
14
+ - Update the dictionary with a complete list of state-operator pairs
15
+ """
16
+
17
+ from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet,
18
+ PositionKet3D)
19
+ from sympy.physics.quantum.operator import Operator
20
+ from sympy.physics.quantum.state import StateBase, BraBase, Ket
21
+ from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet,
22
+ JzKet)
23
+
24
+ __all__ = [
25
+ 'operators_to_state',
26
+ 'state_to_operators'
27
+ ]
28
+
29
+ #state_mapping stores the mappings between states and their associated
30
+ #operators or tuples of operators. This should be updated when new
31
+ #classes are written! Entries are of the form PxKet : PxOp or
32
+ #something like 3DKet : (ROp, ThetaOp, PhiOp)
33
+
34
+ #frozenset is used so that the reverse mapping can be made
35
+ #(regular sets are not hashable because they are mutable
36
+ state_mapping = { JxKet: frozenset((J2Op, JxOp)),
37
+ JyKet: frozenset((J2Op, JyOp)),
38
+ JzKet: frozenset((J2Op, JzOp)),
39
+ Ket: Operator,
40
+ PositionKet3D: frozenset((XOp, YOp, ZOp)),
41
+ PxKet: PxOp,
42
+ XKet: XOp }
43
+
44
+ op_mapping = {v: k for k, v in state_mapping.items()}
45
+
46
+
47
+ def operators_to_state(operators, **options):
48
+ """ Returns the eigenstate of the given operator or set of operators
49
+
50
+ A global function for mapping operator classes to their associated
51
+ states. It takes either an Operator or a set of operators and
52
+ returns the state associated with these.
53
+
54
+ This function can handle both instances of a given operator or
55
+ just the class itself (i.e. both XOp() and XOp)
56
+
57
+ There are multiple use cases to consider:
58
+
59
+ 1) A class or set of classes is passed: First, we try to
60
+ instantiate default instances for these operators. If this fails,
61
+ then the class is simply returned. If we succeed in instantiating
62
+ default instances, then we try to call state._operators_to_state
63
+ on the operator instances. If this fails, the class is returned.
64
+ Otherwise, the instance returned by _operators_to_state is returned.
65
+
66
+ 2) An instance or set of instances is passed: In this case,
67
+ state._operators_to_state is called on the instances passed. If
68
+ this fails, a state class is returned. If the method returns an
69
+ instance, that instance is returned.
70
+
71
+ In both cases, if the operator class or set does not exist in the
72
+ state_mapping dictionary, None is returned.
73
+
74
+ Parameters
75
+ ==========
76
+
77
+ arg: Operator or set
78
+ The class or instance of the operator or set of operators
79
+ to be mapped to a state
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.physics.quantum.cartesian import XOp, PxOp
85
+ >>> from sympy.physics.quantum.operatorset import operators_to_state
86
+ >>> from sympy.physics.quantum.operator import Operator
87
+ >>> operators_to_state(XOp)
88
+ |x>
89
+ >>> operators_to_state(XOp())
90
+ |x>
91
+ >>> operators_to_state(PxOp)
92
+ |px>
93
+ >>> operators_to_state(PxOp())
94
+ |px>
95
+ >>> operators_to_state(Operator)
96
+ |psi>
97
+ >>> operators_to_state(Operator())
98
+ |psi>
99
+ """
100
+
101
+ if not (isinstance(operators, Operator)
102
+ or isinstance(operators, set) or issubclass(operators, Operator)):
103
+ raise NotImplementedError("Argument is not an Operator or a set!")
104
+
105
+ if isinstance(operators, set):
106
+ for s in operators:
107
+ if not (isinstance(s, Operator)
108
+ or issubclass(s, Operator)):
109
+ raise NotImplementedError("Set is not all Operators!")
110
+
111
+ ops = frozenset(operators)
112
+
113
+ if ops in op_mapping: # ops is a list of classes in this case
114
+ #Try to get an object from default instances of the
115
+ #operators...if this fails, return the class
116
+ try:
117
+ op_instances = [op() for op in ops]
118
+ ret = _get_state(op_mapping[ops], set(op_instances), **options)
119
+ except NotImplementedError:
120
+ ret = op_mapping[ops]
121
+
122
+ return ret
123
+ else:
124
+ tmp = [type(o) for o in ops]
125
+ classes = frozenset(tmp)
126
+
127
+ if classes in op_mapping:
128
+ ret = _get_state(op_mapping[classes], ops, **options)
129
+ else:
130
+ ret = None
131
+
132
+ return ret
133
+ else:
134
+ if operators in op_mapping:
135
+ try:
136
+ op_instance = operators()
137
+ ret = _get_state(op_mapping[operators], op_instance, **options)
138
+ except NotImplementedError:
139
+ ret = op_mapping[operators]
140
+
141
+ return ret
142
+ elif type(operators) in op_mapping:
143
+ return _get_state(op_mapping[type(operators)], operators, **options)
144
+ else:
145
+ return None
146
+
147
+
148
+ def state_to_operators(state, **options):
149
+ """ Returns the operator or set of operators corresponding to the
150
+ given eigenstate
151
+
152
+ A global function for mapping state classes to their associated
153
+ operators or sets of operators. It takes either a state class
154
+ or instance.
155
+
156
+ This function can handle both instances of a given state or just
157
+ the class itself (i.e. both XKet() and XKet)
158
+
159
+ There are multiple use cases to consider:
160
+
161
+ 1) A state class is passed: In this case, we first try
162
+ instantiating a default instance of the class. If this succeeds,
163
+ then we try to call state._state_to_operators on that instance.
164
+ If the creation of the default instance or if the calling of
165
+ _state_to_operators fails, then either an operator class or set of
166
+ operator classes is returned. Otherwise, the appropriate
167
+ operator instances are returned.
168
+
169
+ 2) A state instance is returned: Here, state._state_to_operators
170
+ is called for the instance. If this fails, then a class or set of
171
+ operator classes is returned. Otherwise, the instances are returned.
172
+
173
+ In either case, if the state's class does not exist in
174
+ state_mapping, None is returned.
175
+
176
+ Parameters
177
+ ==========
178
+
179
+ arg: StateBase class or instance (or subclasses)
180
+ The class or instance of the state to be mapped to an
181
+ operator or set of operators
182
+
183
+ Examples
184
+ ========
185
+
186
+ >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra
187
+ >>> from sympy.physics.quantum.operatorset import state_to_operators
188
+ >>> from sympy.physics.quantum.state import Ket, Bra
189
+ >>> state_to_operators(XKet)
190
+ X
191
+ >>> state_to_operators(XKet())
192
+ X
193
+ >>> state_to_operators(PxKet)
194
+ Px
195
+ >>> state_to_operators(PxKet())
196
+ Px
197
+ >>> state_to_operators(PxBra)
198
+ Px
199
+ >>> state_to_operators(XBra)
200
+ X
201
+ >>> state_to_operators(Ket)
202
+ O
203
+ >>> state_to_operators(Bra)
204
+ O
205
+ """
206
+
207
+ if not (isinstance(state, StateBase) or issubclass(state, StateBase)):
208
+ raise NotImplementedError("Argument is not a state!")
209
+
210
+ if state in state_mapping: # state is a class
211
+ state_inst = _make_default(state)
212
+ try:
213
+ ret = _get_ops(state_inst,
214
+ _make_set(state_mapping[state]), **options)
215
+ except (NotImplementedError, TypeError):
216
+ ret = state_mapping[state]
217
+ elif type(state) in state_mapping:
218
+ ret = _get_ops(state,
219
+ _make_set(state_mapping[type(state)]), **options)
220
+ elif isinstance(state, BraBase) and state.dual_class() in state_mapping:
221
+ ret = _get_ops(state,
222
+ _make_set(state_mapping[state.dual_class()]))
223
+ elif issubclass(state, BraBase) and state.dual_class() in state_mapping:
224
+ state_inst = _make_default(state)
225
+ try:
226
+ ret = _get_ops(state_inst,
227
+ _make_set(state_mapping[state.dual_class()]))
228
+ except (NotImplementedError, TypeError):
229
+ ret = state_mapping[state.dual_class()]
230
+ else:
231
+ ret = None
232
+
233
+ return _make_set(ret)
234
+
235
+
236
+ def _make_default(expr):
237
+ # XXX: Catching TypeError like this is a bad way of distinguishing between
238
+ # classes and instances. The logic using this function should be rewritten
239
+ # somehow.
240
+ try:
241
+ ret = expr()
242
+ except TypeError:
243
+ ret = expr
244
+
245
+ return ret
246
+
247
+
248
+ def _get_state(state_class, ops, **options):
249
+ # Try to get a state instance from the operator INSTANCES.
250
+ # If this fails, get the class
251
+ try:
252
+ ret = state_class._operators_to_state(ops, **options)
253
+ except NotImplementedError:
254
+ ret = _make_default(state_class)
255
+
256
+ return ret
257
+
258
+
259
+ def _get_ops(state_inst, op_classes, **options):
260
+ # Try to get operator instances from the state INSTANCE.
261
+ # If this fails, just return the classes
262
+ try:
263
+ ret = state_inst._state_to_operators(op_classes, **options)
264
+ except NotImplementedError:
265
+ if isinstance(op_classes, (set, tuple, frozenset)):
266
+ ret = tuple(_make_default(x) for x in op_classes)
267
+ else:
268
+ ret = _make_default(op_classes)
269
+
270
+ if isinstance(ret, set) and len(ret) == 1:
271
+ return ret[0]
272
+
273
+ return ret
274
+
275
+
276
+ def _make_set(ops):
277
+ if isinstance(ops, (tuple, list, frozenset)):
278
+ return set(ops)
279
+ else:
280
+ return ops
venv/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pauli operators and states"""
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.numbers import I
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.functions.elementary.exponential import exp
9
+ from sympy.physics.quantum import Operator, Ket, Bra
10
+ from sympy.physics.quantum import ComplexSpace
11
+ from sympy.matrices import Matrix
12
+ from sympy.functions.special.tensor_functions import KroneckerDelta
13
+
14
+ __all__ = [
15
+ 'SigmaX', 'SigmaY', 'SigmaZ', 'SigmaMinus', 'SigmaPlus', 'SigmaZKet',
16
+ 'SigmaZBra', 'qsimplify_pauli'
17
+ ]
18
+
19
+
20
+ class SigmaOpBase(Operator):
21
+ """Pauli sigma operator, base class"""
22
+
23
+ @property
24
+ def name(self):
25
+ return self.args[0]
26
+
27
+ @property
28
+ def use_name(self):
29
+ return bool(self.args[0]) is not False
30
+
31
+ @classmethod
32
+ def default_args(self):
33
+ return (False,)
34
+
35
+ def __new__(cls, *args, **hints):
36
+ return Operator.__new__(cls, *args, **hints)
37
+
38
+ def _eval_commutator_BosonOp(self, other, **hints):
39
+ return S.Zero
40
+
41
+
42
+ class SigmaX(SigmaOpBase):
43
+ """Pauli sigma x operator
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ name : str
49
+ An optional string that labels the operator. Pauli operators with
50
+ different names commute.
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy.physics.quantum import represent
56
+ >>> from sympy.physics.quantum.pauli import SigmaX
57
+ >>> sx = SigmaX()
58
+ >>> sx
59
+ SigmaX()
60
+ >>> represent(sx)
61
+ Matrix([
62
+ [0, 1],
63
+ [1, 0]])
64
+ """
65
+
66
+ def __new__(cls, *args, **hints):
67
+ return SigmaOpBase.__new__(cls, *args, **hints)
68
+
69
+ def _eval_commutator_SigmaY(self, other, **hints):
70
+ if self.name != other.name:
71
+ return S.Zero
72
+ else:
73
+ return 2 * I * SigmaZ(self.name)
74
+
75
+ def _eval_commutator_SigmaZ(self, other, **hints):
76
+ if self.name != other.name:
77
+ return S.Zero
78
+ else:
79
+ return - 2 * I * SigmaY(self.name)
80
+
81
+ def _eval_commutator_BosonOp(self, other, **hints):
82
+ return S.Zero
83
+
84
+ def _eval_anticommutator_SigmaY(self, other, **hints):
85
+ return S.Zero
86
+
87
+ def _eval_anticommutator_SigmaZ(self, other, **hints):
88
+ return S.Zero
89
+
90
+ def _eval_adjoint(self):
91
+ return self
92
+
93
+ def _print_contents_latex(self, printer, *args):
94
+ if self.use_name:
95
+ return r'{\sigma_x^{(%s)}}' % str(self.name)
96
+ else:
97
+ return r'{\sigma_x}'
98
+
99
+ def _print_contents(self, printer, *args):
100
+ return 'SigmaX()'
101
+
102
+ def _eval_power(self, e):
103
+ if e.is_Integer and e.is_positive:
104
+ return SigmaX(self.name).__pow__(int(e) % 2)
105
+
106
+ def _represent_default_basis(self, **options):
107
+ format = options.get('format', 'sympy')
108
+ if format == 'sympy':
109
+ return Matrix([[0, 1], [1, 0]])
110
+ else:
111
+ raise NotImplementedError('Representation in format ' +
112
+ format + ' not implemented.')
113
+
114
+
115
+ class SigmaY(SigmaOpBase):
116
+ """Pauli sigma y operator
117
+
118
+ Parameters
119
+ ==========
120
+
121
+ name : str
122
+ An optional string that labels the operator. Pauli operators with
123
+ different names commute.
124
+
125
+ Examples
126
+ ========
127
+
128
+ >>> from sympy.physics.quantum import represent
129
+ >>> from sympy.physics.quantum.pauli import SigmaY
130
+ >>> sy = SigmaY()
131
+ >>> sy
132
+ SigmaY()
133
+ >>> represent(sy)
134
+ Matrix([
135
+ [0, -I],
136
+ [I, 0]])
137
+ """
138
+
139
+ def __new__(cls, *args, **hints):
140
+ return SigmaOpBase.__new__(cls, *args)
141
+
142
+ def _eval_commutator_SigmaZ(self, other, **hints):
143
+ if self.name != other.name:
144
+ return S.Zero
145
+ else:
146
+ return 2 * I * SigmaX(self.name)
147
+
148
+ def _eval_commutator_SigmaX(self, other, **hints):
149
+ if self.name != other.name:
150
+ return S.Zero
151
+ else:
152
+ return - 2 * I * SigmaZ(self.name)
153
+
154
+ def _eval_anticommutator_SigmaX(self, other, **hints):
155
+ return S.Zero
156
+
157
+ def _eval_anticommutator_SigmaZ(self, other, **hints):
158
+ return S.Zero
159
+
160
+ def _eval_adjoint(self):
161
+ return self
162
+
163
+ def _print_contents_latex(self, printer, *args):
164
+ if self.use_name:
165
+ return r'{\sigma_y^{(%s)}}' % str(self.name)
166
+ else:
167
+ return r'{\sigma_y}'
168
+
169
+ def _print_contents(self, printer, *args):
170
+ return 'SigmaY()'
171
+
172
+ def _eval_power(self, e):
173
+ if e.is_Integer and e.is_positive:
174
+ return SigmaY(self.name).__pow__(int(e) % 2)
175
+
176
+ def _represent_default_basis(self, **options):
177
+ format = options.get('format', 'sympy')
178
+ if format == 'sympy':
179
+ return Matrix([[0, -I], [I, 0]])
180
+ else:
181
+ raise NotImplementedError('Representation in format ' +
182
+ format + ' not implemented.')
183
+
184
+
185
+ class SigmaZ(SigmaOpBase):
186
+ """Pauli sigma z operator
187
+
188
+ Parameters
189
+ ==========
190
+
191
+ name : str
192
+ An optional string that labels the operator. Pauli operators with
193
+ different names commute.
194
+
195
+ Examples
196
+ ========
197
+
198
+ >>> from sympy.physics.quantum import represent
199
+ >>> from sympy.physics.quantum.pauli import SigmaZ
200
+ >>> sz = SigmaZ()
201
+ >>> sz ** 3
202
+ SigmaZ()
203
+ >>> represent(sz)
204
+ Matrix([
205
+ [1, 0],
206
+ [0, -1]])
207
+ """
208
+
209
+ def __new__(cls, *args, **hints):
210
+ return SigmaOpBase.__new__(cls, *args)
211
+
212
+ def _eval_commutator_SigmaX(self, other, **hints):
213
+ if self.name != other.name:
214
+ return S.Zero
215
+ else:
216
+ return 2 * I * SigmaY(self.name)
217
+
218
+ def _eval_commutator_SigmaY(self, other, **hints):
219
+ if self.name != other.name:
220
+ return S.Zero
221
+ else:
222
+ return - 2 * I * SigmaX(self.name)
223
+
224
+ def _eval_anticommutator_SigmaX(self, other, **hints):
225
+ return S.Zero
226
+
227
+ def _eval_anticommutator_SigmaY(self, other, **hints):
228
+ return S.Zero
229
+
230
+ def _eval_adjoint(self):
231
+ return self
232
+
233
+ def _print_contents_latex(self, printer, *args):
234
+ if self.use_name:
235
+ return r'{\sigma_z^{(%s)}}' % str(self.name)
236
+ else:
237
+ return r'{\sigma_z}'
238
+
239
+ def _print_contents(self, printer, *args):
240
+ return 'SigmaZ()'
241
+
242
+ def _eval_power(self, e):
243
+ if e.is_Integer and e.is_positive:
244
+ return SigmaZ(self.name).__pow__(int(e) % 2)
245
+
246
+ def _represent_default_basis(self, **options):
247
+ format = options.get('format', 'sympy')
248
+ if format == 'sympy':
249
+ return Matrix([[1, 0], [0, -1]])
250
+ else:
251
+ raise NotImplementedError('Representation in format ' +
252
+ format + ' not implemented.')
253
+
254
+
255
+ class SigmaMinus(SigmaOpBase):
256
+ """Pauli sigma minus operator
257
+
258
+ Parameters
259
+ ==========
260
+
261
+ name : str
262
+ An optional string that labels the operator. Pauli operators with
263
+ different names commute.
264
+
265
+ Examples
266
+ ========
267
+
268
+ >>> from sympy.physics.quantum import represent, Dagger
269
+ >>> from sympy.physics.quantum.pauli import SigmaMinus
270
+ >>> sm = SigmaMinus()
271
+ >>> sm
272
+ SigmaMinus()
273
+ >>> Dagger(sm)
274
+ SigmaPlus()
275
+ >>> represent(sm)
276
+ Matrix([
277
+ [0, 0],
278
+ [1, 0]])
279
+ """
280
+
281
+ def __new__(cls, *args, **hints):
282
+ return SigmaOpBase.__new__(cls, *args)
283
+
284
+ def _eval_commutator_SigmaX(self, other, **hints):
285
+ if self.name != other.name:
286
+ return S.Zero
287
+ else:
288
+ return -SigmaZ(self.name)
289
+
290
+ def _eval_commutator_SigmaY(self, other, **hints):
291
+ if self.name != other.name:
292
+ return S.Zero
293
+ else:
294
+ return I * SigmaZ(self.name)
295
+
296
+ def _eval_commutator_SigmaZ(self, other, **hints):
297
+ return 2 * self
298
+
299
+ def _eval_commutator_SigmaMinus(self, other, **hints):
300
+ return SigmaZ(self.name)
301
+
302
+ def _eval_anticommutator_SigmaZ(self, other, **hints):
303
+ return S.Zero
304
+
305
+ def _eval_anticommutator_SigmaX(self, other, **hints):
306
+ return S.One
307
+
308
+ def _eval_anticommutator_SigmaY(self, other, **hints):
309
+ return I * S.NegativeOne
310
+
311
+ def _eval_anticommutator_SigmaPlus(self, other, **hints):
312
+ return S.One
313
+
314
+ def _eval_adjoint(self):
315
+ return SigmaPlus(self.name)
316
+
317
+ def _eval_power(self, e):
318
+ if e.is_Integer and e.is_positive:
319
+ return S.Zero
320
+
321
+ def _print_contents_latex(self, printer, *args):
322
+ if self.use_name:
323
+ return r'{\sigma_-^{(%s)}}' % str(self.name)
324
+ else:
325
+ return r'{\sigma_-}'
326
+
327
+ def _print_contents(self, printer, *args):
328
+ return 'SigmaMinus()'
329
+
330
+ def _represent_default_basis(self, **options):
331
+ format = options.get('format', 'sympy')
332
+ if format == 'sympy':
333
+ return Matrix([[0, 0], [1, 0]])
334
+ else:
335
+ raise NotImplementedError('Representation in format ' +
336
+ format + ' not implemented.')
337
+
338
+
339
+ class SigmaPlus(SigmaOpBase):
340
+ """Pauli sigma plus operator
341
+
342
+ Parameters
343
+ ==========
344
+
345
+ name : str
346
+ An optional string that labels the operator. Pauli operators with
347
+ different names commute.
348
+
349
+ Examples
350
+ ========
351
+
352
+ >>> from sympy.physics.quantum import represent, Dagger
353
+ >>> from sympy.physics.quantum.pauli import SigmaPlus
354
+ >>> sp = SigmaPlus()
355
+ >>> sp
356
+ SigmaPlus()
357
+ >>> Dagger(sp)
358
+ SigmaMinus()
359
+ >>> represent(sp)
360
+ Matrix([
361
+ [0, 1],
362
+ [0, 0]])
363
+ """
364
+
365
+ def __new__(cls, *args, **hints):
366
+ return SigmaOpBase.__new__(cls, *args)
367
+
368
+ def _eval_commutator_SigmaX(self, other, **hints):
369
+ if self.name != other.name:
370
+ return S.Zero
371
+ else:
372
+ return SigmaZ(self.name)
373
+
374
+ def _eval_commutator_SigmaY(self, other, **hints):
375
+ if self.name != other.name:
376
+ return S.Zero
377
+ else:
378
+ return I * SigmaZ(self.name)
379
+
380
+ def _eval_commutator_SigmaZ(self, other, **hints):
381
+ if self.name != other.name:
382
+ return S.Zero
383
+ else:
384
+ return -2 * self
385
+
386
+ def _eval_commutator_SigmaMinus(self, other, **hints):
387
+ return SigmaZ(self.name)
388
+
389
+ def _eval_anticommutator_SigmaZ(self, other, **hints):
390
+ return S.Zero
391
+
392
+ def _eval_anticommutator_SigmaX(self, other, **hints):
393
+ return S.One
394
+
395
+ def _eval_anticommutator_SigmaY(self, other, **hints):
396
+ return I
397
+
398
+ def _eval_anticommutator_SigmaMinus(self, other, **hints):
399
+ return S.One
400
+
401
+ def _eval_adjoint(self):
402
+ return SigmaMinus(self.name)
403
+
404
+ def _eval_mul(self, other):
405
+ return self * other
406
+
407
+ def _eval_power(self, e):
408
+ if e.is_Integer and e.is_positive:
409
+ return S.Zero
410
+
411
+ def _print_contents_latex(self, printer, *args):
412
+ if self.use_name:
413
+ return r'{\sigma_+^{(%s)}}' % str(self.name)
414
+ else:
415
+ return r'{\sigma_+}'
416
+
417
+ def _print_contents(self, printer, *args):
418
+ return 'SigmaPlus()'
419
+
420
+ def _represent_default_basis(self, **options):
421
+ format = options.get('format', 'sympy')
422
+ if format == 'sympy':
423
+ return Matrix([[0, 1], [0, 0]])
424
+ else:
425
+ raise NotImplementedError('Representation in format ' +
426
+ format + ' not implemented.')
427
+
428
+
429
+ class SigmaZKet(Ket):
430
+ """Ket for a two-level system quantum system.
431
+
432
+ Parameters
433
+ ==========
434
+
435
+ n : Number
436
+ The state number (0 or 1).
437
+
438
+ """
439
+
440
+ def __new__(cls, n):
441
+ if n not in (0, 1):
442
+ raise ValueError("n must be 0 or 1")
443
+ return Ket.__new__(cls, n)
444
+
445
+ @property
446
+ def n(self):
447
+ return self.label[0]
448
+
449
+ @classmethod
450
+ def dual_class(self):
451
+ return SigmaZBra
452
+
453
+ @classmethod
454
+ def _eval_hilbert_space(cls, label):
455
+ return ComplexSpace(2)
456
+
457
+ def _eval_innerproduct_SigmaZBra(self, bra, **hints):
458
+ return KroneckerDelta(self.n, bra.n)
459
+
460
+ def _apply_from_right_to_SigmaZ(self, op, **options):
461
+ if self.n == 0:
462
+ return self
463
+ else:
464
+ return S.NegativeOne * self
465
+
466
+ def _apply_from_right_to_SigmaX(self, op, **options):
467
+ return SigmaZKet(1) if self.n == 0 else SigmaZKet(0)
468
+
469
+ def _apply_from_right_to_SigmaY(self, op, **options):
470
+ return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0)
471
+
472
+ def _apply_from_right_to_SigmaMinus(self, op, **options):
473
+ if self.n == 0:
474
+ return SigmaZKet(1)
475
+ else:
476
+ return S.Zero
477
+
478
+ def _apply_from_right_to_SigmaPlus(self, op, **options):
479
+ if self.n == 0:
480
+ return S.Zero
481
+ else:
482
+ return SigmaZKet(0)
483
+
484
+ def _represent_default_basis(self, **options):
485
+ format = options.get('format', 'sympy')
486
+ if format == 'sympy':
487
+ return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]])
488
+ else:
489
+ raise NotImplementedError('Representation in format ' +
490
+ format + ' not implemented.')
491
+
492
+
493
+ class SigmaZBra(Bra):
494
+ """Bra for a two-level quantum system.
495
+
496
+ Parameters
497
+ ==========
498
+
499
+ n : Number
500
+ The state number (0 or 1).
501
+
502
+ """
503
+
504
+ def __new__(cls, n):
505
+ if n not in (0, 1):
506
+ raise ValueError("n must be 0 or 1")
507
+ return Bra.__new__(cls, n)
508
+
509
+ @property
510
+ def n(self):
511
+ return self.label[0]
512
+
513
+ @classmethod
514
+ def dual_class(self):
515
+ return SigmaZKet
516
+
517
+
518
+ def _qsimplify_pauli_product(a, b):
519
+ """
520
+ Internal helper function for simplifying products of Pauli operators.
521
+ """
522
+ if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)):
523
+ return Mul(a, b)
524
+
525
+ if a.name != b.name:
526
+ # Pauli matrices with different labels commute; sort by name
527
+ if a.name < b.name:
528
+ return Mul(a, b)
529
+ else:
530
+ return Mul(b, a)
531
+
532
+ elif isinstance(a, SigmaX):
533
+
534
+ if isinstance(b, SigmaX):
535
+ return S.One
536
+
537
+ if isinstance(b, SigmaY):
538
+ return I * SigmaZ(a.name)
539
+
540
+ if isinstance(b, SigmaZ):
541
+ return - I * SigmaY(a.name)
542
+
543
+ if isinstance(b, SigmaMinus):
544
+ return (S.Half + SigmaZ(a.name)/2)
545
+
546
+ if isinstance(b, SigmaPlus):
547
+ return (S.Half - SigmaZ(a.name)/2)
548
+
549
+ elif isinstance(a, SigmaY):
550
+
551
+ if isinstance(b, SigmaX):
552
+ return - I * SigmaZ(a.name)
553
+
554
+ if isinstance(b, SigmaY):
555
+ return S.One
556
+
557
+ if isinstance(b, SigmaZ):
558
+ return I * SigmaX(a.name)
559
+
560
+ if isinstance(b, SigmaMinus):
561
+ return -I * (S.One + SigmaZ(a.name))/2
562
+
563
+ if isinstance(b, SigmaPlus):
564
+ return I * (S.One - SigmaZ(a.name))/2
565
+
566
+ elif isinstance(a, SigmaZ):
567
+
568
+ if isinstance(b, SigmaX):
569
+ return I * SigmaY(a.name)
570
+
571
+ if isinstance(b, SigmaY):
572
+ return - I * SigmaX(a.name)
573
+
574
+ if isinstance(b, SigmaZ):
575
+ return S.One
576
+
577
+ if isinstance(b, SigmaMinus):
578
+ return - SigmaMinus(a.name)
579
+
580
+ if isinstance(b, SigmaPlus):
581
+ return SigmaPlus(a.name)
582
+
583
+ elif isinstance(a, SigmaMinus):
584
+
585
+ if isinstance(b, SigmaX):
586
+ return (S.One - SigmaZ(a.name))/2
587
+
588
+ if isinstance(b, SigmaY):
589
+ return - I * (S.One - SigmaZ(a.name))/2
590
+
591
+ if isinstance(b, SigmaZ):
592
+ # (SigmaX(a.name) - I * SigmaY(a.name))/2
593
+ return SigmaMinus(b.name)
594
+
595
+ if isinstance(b, SigmaMinus):
596
+ return S.Zero
597
+
598
+ if isinstance(b, SigmaPlus):
599
+ return S.Half - SigmaZ(a.name)/2
600
+
601
+ elif isinstance(a, SigmaPlus):
602
+
603
+ if isinstance(b, SigmaX):
604
+ return (S.One + SigmaZ(a.name))/2
605
+
606
+ if isinstance(b, SigmaY):
607
+ return I * (S.One + SigmaZ(a.name))/2
608
+
609
+ if isinstance(b, SigmaZ):
610
+ #-(SigmaX(a.name) + I * SigmaY(a.name))/2
611
+ return -SigmaPlus(a.name)
612
+
613
+ if isinstance(b, SigmaMinus):
614
+ return (S.One + SigmaZ(a.name))/2
615
+
616
+ if isinstance(b, SigmaPlus):
617
+ return S.Zero
618
+
619
+ else:
620
+ return a * b
621
+
622
+
623
+ def qsimplify_pauli(e):
624
+ """
625
+ Simplify an expression that includes products of pauli operators.
626
+
627
+ Parameters
628
+ ==========
629
+
630
+ e : expression
631
+ An expression that contains products of Pauli operators that is
632
+ to be simplified.
633
+
634
+ Examples
635
+ ========
636
+
637
+ >>> from sympy.physics.quantum.pauli import SigmaX, SigmaY
638
+ >>> from sympy.physics.quantum.pauli import qsimplify_pauli
639
+ >>> sx, sy = SigmaX(), SigmaY()
640
+ >>> sx * sy
641
+ SigmaX()*SigmaY()
642
+ >>> qsimplify_pauli(sx * sy)
643
+ I*SigmaZ()
644
+ """
645
+ if isinstance(e, Operator):
646
+ return e
647
+
648
+ if isinstance(e, (Add, Pow, exp)):
649
+ t = type(e)
650
+ return t(*(qsimplify_pauli(arg) for arg in e.args))
651
+
652
+ if isinstance(e, Mul):
653
+
654
+ c, nc = e.args_cnc()
655
+
656
+ nc_s = []
657
+ while nc:
658
+ curr = nc.pop(0)
659
+
660
+ while (len(nc) and
661
+ isinstance(curr, SigmaOpBase) and
662
+ isinstance(nc[0], SigmaOpBase) and
663
+ curr.name == nc[0].name):
664
+
665
+ x = nc.pop(0)
666
+ y = _qsimplify_pauli_product(curr, x)
667
+ c1, nc1 = y.args_cnc()
668
+ curr = Mul(*nc1)
669
+ c = c + c1
670
+
671
+ nc_s.append(curr)
672
+
673
+ return Mul(*c) * Mul(*nc_s)
674
+
675
+ return e
venv/lib/python3.10/site-packages/sympy/physics/quantum/piab.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """1D quantum particle in a box."""
2
+
3
+ from sympy.core.numbers import pi
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.sets.sets import Interval
9
+
10
+ from sympy.physics.quantum.operator import HermitianOperator
11
+ from sympy.physics.quantum.state import Ket, Bra
12
+ from sympy.physics.quantum.constants import hbar
13
+ from sympy.functions.special.tensor_functions import KroneckerDelta
14
+ from sympy.physics.quantum.hilbert import L2
15
+
16
+ m = Symbol('m')
17
+ L = Symbol('L')
18
+
19
+
20
+ __all__ = [
21
+ 'PIABHamiltonian',
22
+ 'PIABKet',
23
+ 'PIABBra'
24
+ ]
25
+
26
+
27
+ class PIABHamiltonian(HermitianOperator):
28
+ """Particle in a box Hamiltonian operator."""
29
+
30
+ @classmethod
31
+ def _eval_hilbert_space(cls, label):
32
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
33
+
34
+ def _apply_operator_PIABKet(self, ket, **options):
35
+ n = ket.label[0]
36
+ return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
37
+
38
+
39
+ class PIABKet(Ket):
40
+ """Particle in a box eigenket."""
41
+
42
+ @classmethod
43
+ def _eval_hilbert_space(cls, args):
44
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
45
+
46
+ @classmethod
47
+ def dual_class(self):
48
+ return PIABBra
49
+
50
+ def _represent_default_basis(self, **options):
51
+ return self._represent_XOp(None, **options)
52
+
53
+ def _represent_XOp(self, basis, **options):
54
+ x = Symbol('x')
55
+ n = Symbol('n')
56
+ subs_info = options.get('subs', {})
57
+ return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)
58
+
59
+ def _eval_innerproduct_PIABBra(self, bra):
60
+ return KroneckerDelta(bra.label[0], self.label[0])
61
+
62
+
63
+ class PIABBra(Bra):
64
+ """Particle in a box eigenbra."""
65
+
66
+ @classmethod
67
+ def _eval_hilbert_space(cls, label):
68
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
69
+
70
+ @classmethod
71
+ def dual_class(self):
72
+ return PIABKet
venv/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for applying operators to states.
2
+
3
+ Todo:
4
+ * Sometimes the final result needs to be expanded, we should do this by hand.
5
+ """
6
+
7
+ from sympy.core.add import Add
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.power import Pow
10
+ from sympy.core.singleton import S
11
+ from sympy.core.sympify import sympify
12
+
13
+ from sympy.physics.quantum.anticommutator import AntiCommutator
14
+ from sympy.physics.quantum.commutator import Commutator
15
+ from sympy.physics.quantum.dagger import Dagger
16
+ from sympy.physics.quantum.innerproduct import InnerProduct
17
+ from sympy.physics.quantum.operator import OuterProduct, Operator
18
+ from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
19
+ from sympy.physics.quantum.tensorproduct import TensorProduct
20
+
21
+ __all__ = [
22
+ 'qapply'
23
+ ]
24
+
25
+
26
+ #-----------------------------------------------------------------------------
27
+ # Main code
28
+ #-----------------------------------------------------------------------------
29
+
30
+ def qapply(e, **options):
31
+ """Apply operators to states in a quantum expression.
32
+
33
+ Parameters
34
+ ==========
35
+
36
+ e : Expr
37
+ The expression containing operators and states. This expression tree
38
+ will be walked to find operators acting on states symbolically.
39
+ options : dict
40
+ A dict of key/value pairs that determine how the operator actions
41
+ are carried out.
42
+
43
+ The following options are valid:
44
+
45
+ * ``dagger``: try to apply Dagger operators to the left
46
+ (default: False).
47
+ * ``ip_doit``: call ``.doit()`` in inner products when they are
48
+ encountered (default: True).
49
+
50
+ Returns
51
+ =======
52
+
53
+ e : Expr
54
+ The original expression, but with the operators applied to states.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.physics.quantum import qapply, Ket, Bra
60
+ >>> b = Bra('b')
61
+ >>> k = Ket('k')
62
+ >>> A = k * b
63
+ >>> A
64
+ |k><b|
65
+ >>> qapply(A * b.dual / (b * b.dual))
66
+ |k>
67
+ >>> qapply(k.dual * A / (k.dual * k), dagger=True)
68
+ <b|
69
+ >>> qapply(k.dual * A / (k.dual * k))
70
+ <k|*|k><b|/<k|k>
71
+ """
72
+ from sympy.physics.quantum.density import Density
73
+
74
+ dagger = options.get('dagger', False)
75
+
76
+ if e == 0:
77
+ return S.Zero
78
+
79
+ # This may be a bit aggressive but ensures that everything gets expanded
80
+ # to its simplest form before trying to apply operators. This includes
81
+ # things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and
82
+ # TensorProducts. The only problem with this is that if we can't apply
83
+ # all the Operators, we have just expanded everything.
84
+ # TODO: don't expand the scalars in front of each Mul.
85
+ e = e.expand(commutator=True, tensorproduct=True)
86
+
87
+ # If we just have a raw ket, return it.
88
+ if isinstance(e, KetBase):
89
+ return e
90
+
91
+ # We have an Add(a, b, c, ...) and compute
92
+ # Add(qapply(a), qapply(b), ...)
93
+ elif isinstance(e, Add):
94
+ result = 0
95
+ for arg in e.args:
96
+ result += qapply(arg, **options)
97
+ return result.expand()
98
+
99
+ # For a Density operator call qapply on its state
100
+ elif isinstance(e, Density):
101
+ new_args = [(qapply(state, **options), prob) for (state,
102
+ prob) in e.args]
103
+ return Density(*new_args)
104
+
105
+ # For a raw TensorProduct, call qapply on its args.
106
+ elif isinstance(e, TensorProduct):
107
+ return TensorProduct(*[qapply(t, **options) for t in e.args])
108
+
109
+ # For a Pow, call qapply on its base.
110
+ elif isinstance(e, Pow):
111
+ return qapply(e.base, **options)**e.exp
112
+
113
+ # We have a Mul where there might be actual operators to apply to kets.
114
+ elif isinstance(e, Mul):
115
+ c_part, nc_part = e.args_cnc()
116
+ c_mul = Mul(*c_part)
117
+ nc_mul = Mul(*nc_part)
118
+ if isinstance(nc_mul, Mul):
119
+ result = c_mul*qapply_Mul(nc_mul, **options)
120
+ else:
121
+ result = c_mul*qapply(nc_mul, **options)
122
+ if result == e and dagger:
123
+ return Dagger(qapply_Mul(Dagger(e), **options))
124
+ else:
125
+ return result
126
+
127
+ # In all other cases (State, Operator, Pow, Commutator, InnerProduct,
128
+ # OuterProduct) we won't ever have operators to apply to kets.
129
+ else:
130
+ return e
131
+
132
+
133
+ def qapply_Mul(e, **options):
134
+
135
+ ip_doit = options.get('ip_doit', True)
136
+
137
+ args = list(e.args)
138
+
139
+ # If we only have 0 or 1 args, we have nothing to do and return.
140
+ if len(args) <= 1 or not isinstance(e, Mul):
141
+ return e
142
+ rhs = args.pop()
143
+ lhs = args.pop()
144
+
145
+ # Make sure we have two non-commutative objects before proceeding.
146
+ if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \
147
+ (not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative):
148
+ return e
149
+
150
+ # For a Pow with an integer exponent, apply one of them and reduce the
151
+ # exponent by one.
152
+ if isinstance(lhs, Pow) and lhs.exp.is_Integer:
153
+ args.append(lhs.base**(lhs.exp - 1))
154
+ lhs = lhs.base
155
+
156
+ # Pull OuterProduct apart
157
+ if isinstance(lhs, OuterProduct):
158
+ args.append(lhs.ket)
159
+ lhs = lhs.bra
160
+
161
+ # Call .doit() on Commutator/AntiCommutator.
162
+ if isinstance(lhs, (Commutator, AntiCommutator)):
163
+ comm = lhs.doit()
164
+ if isinstance(comm, Add):
165
+ return qapply(
166
+ e.func(*(args + [comm.args[0], rhs])) +
167
+ e.func(*(args + [comm.args[1], rhs])),
168
+ **options
169
+ )
170
+ else:
171
+ return qapply(e.func(*args)*comm*rhs, **options)
172
+
173
+ # Apply tensor products of operators to states
174
+ if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
175
+ isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
176
+ len(lhs.args) == len(rhs.args):
177
+ result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
178
+ return qapply_Mul(e.func(*args), **options)*result
179
+
180
+ # Now try to actually apply the operator and build an inner product.
181
+ try:
182
+ result = lhs._apply_operator(rhs, **options)
183
+ except (NotImplementedError, AttributeError):
184
+ try:
185
+ result = rhs._apply_from_right_to(lhs, **options)
186
+ except (NotImplementedError, AttributeError):
187
+ if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
188
+ result = InnerProduct(lhs, rhs)
189
+ if ip_doit:
190
+ result = result.doit()
191
+ else:
192
+ result = None
193
+
194
+ # TODO: I may need to expand before returning the final result.
195
+ if result == 0:
196
+ return S.Zero
197
+ elif result is None:
198
+ if len(args) == 0:
199
+ # We had two args to begin with so args=[].
200
+ return e
201
+ else:
202
+ return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs
203
+ elif isinstance(result, InnerProduct):
204
+ return result*qapply_Mul(e.func(*args), **options)
205
+ else: # result is a scalar times a Mul, Add or TensorProduct
206
+ return qapply(e.func(*args)*result, **options)
venv/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.core.sympify import sympify
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ from sympy.core.containers import Tuple
7
+ from sympy.utilities.iterables import is_sequence
8
+
9
+ from sympy.physics.quantum.dagger import Dagger
10
+ from sympy.physics.quantum.matrixutils import (
11
+ numpy_ndarray, scipy_sparse_matrix,
12
+ to_sympy, to_numpy, to_scipy_sparse
13
+ )
14
+
15
+ __all__ = [
16
+ 'QuantumError',
17
+ 'QExpr'
18
+ ]
19
+
20
+
21
+ #-----------------------------------------------------------------------------
22
+ # Error handling
23
+ #-----------------------------------------------------------------------------
24
+
25
+ class QuantumError(Exception):
26
+ pass
27
+
28
+
29
+ def _qsympify_sequence(seq):
30
+ """Convert elements of a sequence to standard form.
31
+
32
+ This is like sympify, but it performs special logic for arguments passed
33
+ to QExpr. The following conversions are done:
34
+
35
+ * (list, tuple, Tuple) => _qsympify_sequence each element and convert
36
+ sequence to a Tuple.
37
+ * basestring => Symbol
38
+ * Matrix => Matrix
39
+ * other => sympify
40
+
41
+ Strings are passed to Symbol, not sympify to make sure that variables like
42
+ 'pi' are kept as Symbols, not the SymPy built-in number subclasses.
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy.physics.quantum.qexpr import _qsympify_sequence
48
+ >>> _qsympify_sequence((1,2,[3,4,[1,]]))
49
+ (1, 2, (3, 4, (1,)))
50
+
51
+ """
52
+
53
+ return tuple(__qsympify_sequence_helper(seq))
54
+
55
+
56
+ def __qsympify_sequence_helper(seq):
57
+ """
58
+ Helper function for _qsympify_sequence
59
+ This function does the actual work.
60
+ """
61
+ #base case. If not a list, do Sympification
62
+ if not is_sequence(seq):
63
+ if isinstance(seq, Matrix):
64
+ return seq
65
+ elif isinstance(seq, str):
66
+ return Symbol(seq)
67
+ else:
68
+ return sympify(seq)
69
+
70
+ # base condition, when seq is QExpr and also
71
+ # is iterable.
72
+ if isinstance(seq, QExpr):
73
+ return seq
74
+
75
+ #if list, recurse on each item in the list
76
+ result = [__qsympify_sequence_helper(item) for item in seq]
77
+
78
+ return Tuple(*result)
79
+
80
+
81
+ #-----------------------------------------------------------------------------
82
+ # Basic Quantum Expression from which all objects descend
83
+ #-----------------------------------------------------------------------------
84
+
85
+ class QExpr(Expr):
86
+ """A base class for all quantum object like operators and states."""
87
+
88
+ # In sympy, slots are for instance attributes that are computed
89
+ # dynamically by the __new__ method. They are not part of args, but they
90
+ # derive from args.
91
+
92
+ # The Hilbert space a quantum Object belongs to.
93
+ __slots__ = ('hilbert_space', )
94
+
95
+ is_commutative = False
96
+
97
+ # The separator used in printing the label.
98
+ _label_separator = ''
99
+
100
+ @property
101
+ def free_symbols(self):
102
+ return {self}
103
+
104
+ def __new__(cls, *args, **kwargs):
105
+ """Construct a new quantum object.
106
+
107
+ Parameters
108
+ ==========
109
+
110
+ args : tuple
111
+ The list of numbers or parameters that uniquely specify the
112
+ quantum object. For a state, this will be its symbol or its
113
+ set of quantum numbers.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy.physics.quantum.qexpr import QExpr
119
+ >>> q = QExpr(0)
120
+ >>> q
121
+ 0
122
+ >>> q.label
123
+ (0,)
124
+ >>> q.hilbert_space
125
+ H
126
+ >>> q.args
127
+ (0,)
128
+ >>> q.is_commutative
129
+ False
130
+ """
131
+
132
+ # First compute args and call Expr.__new__ to create the instance
133
+ args = cls._eval_args(args, **kwargs)
134
+ if len(args) == 0:
135
+ args = cls._eval_args(tuple(cls.default_args()), **kwargs)
136
+ inst = Expr.__new__(cls, *args)
137
+ # Now set the slots on the instance
138
+ inst.hilbert_space = cls._eval_hilbert_space(args)
139
+ return inst
140
+
141
+ @classmethod
142
+ def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
143
+ """Create new instance of this class with hilbert_space and args.
144
+
145
+ This is used to bypass the more complex logic in the ``__new__``
146
+ method in cases where you already have the exact ``hilbert_space``
147
+ and ``args``. This should be used when you are positive these
148
+ arguments are valid, in their final, proper form and want to optimize
149
+ the creation of the object.
150
+ """
151
+
152
+ obj = Expr.__new__(cls, *args, **old_assumptions)
153
+ obj.hilbert_space = hilbert_space
154
+ return obj
155
+
156
+ #-------------------------------------------------------------------------
157
+ # Properties
158
+ #-------------------------------------------------------------------------
159
+
160
+ @property
161
+ def label(self):
162
+ """The label is the unique set of identifiers for the object.
163
+
164
+ Usually, this will include all of the information about the state
165
+ *except* the time (in the case of time-dependent objects).
166
+
167
+ This must be a tuple, rather than a Tuple.
168
+ """
169
+ if len(self.args) == 0: # If there is no label specified, return the default
170
+ return self._eval_args(list(self.default_args()))
171
+ else:
172
+ return self.args
173
+
174
+ @property
175
+ def is_symbolic(self):
176
+ return True
177
+
178
+ @classmethod
179
+ def default_args(self):
180
+ """If no arguments are specified, then this will return a default set
181
+ of arguments to be run through the constructor.
182
+
183
+ NOTE: Any classes that override this MUST return a tuple of arguments.
184
+ Should be overridden by subclasses to specify the default arguments for kets and operators
185
+ """
186
+ raise NotImplementedError("No default arguments for this class!")
187
+
188
+ #-------------------------------------------------------------------------
189
+ # _eval_* methods
190
+ #-------------------------------------------------------------------------
191
+
192
+ def _eval_adjoint(self):
193
+ obj = Expr._eval_adjoint(self)
194
+ if obj is None:
195
+ obj = Expr.__new__(Dagger, self)
196
+ if isinstance(obj, QExpr):
197
+ obj.hilbert_space = self.hilbert_space
198
+ return obj
199
+
200
+ @classmethod
201
+ def _eval_args(cls, args):
202
+ """Process the args passed to the __new__ method.
203
+
204
+ This simply runs args through _qsympify_sequence.
205
+ """
206
+ return _qsympify_sequence(args)
207
+
208
+ @classmethod
209
+ def _eval_hilbert_space(cls, args):
210
+ """Compute the Hilbert space instance from the args.
211
+ """
212
+ from sympy.physics.quantum.hilbert import HilbertSpace
213
+ return HilbertSpace()
214
+
215
+ #-------------------------------------------------------------------------
216
+ # Printing
217
+ #-------------------------------------------------------------------------
218
+
219
+ # Utilities for printing: these operate on raw SymPy objects
220
+
221
+ def _print_sequence(self, seq, sep, printer, *args):
222
+ result = []
223
+ for item in seq:
224
+ result.append(printer._print(item, *args))
225
+ return sep.join(result)
226
+
227
+ def _print_sequence_pretty(self, seq, sep, printer, *args):
228
+ pform = printer._print(seq[0], *args)
229
+ for item in seq[1:]:
230
+ pform = prettyForm(*pform.right(sep))
231
+ pform = prettyForm(*pform.right(printer._print(item, *args)))
232
+ return pform
233
+
234
+ # Utilities for printing: these operate prettyForm objects
235
+
236
+ def _print_subscript_pretty(self, a, b):
237
+ top = prettyForm(*b.left(' '*a.width()))
238
+ bot = prettyForm(*a.right(' '*b.width()))
239
+ return prettyForm(binding=prettyForm.POW, *bot.below(top))
240
+
241
+ def _print_superscript_pretty(self, a, b):
242
+ return a**b
243
+
244
+ def _print_parens_pretty(self, pform, left='(', right=')'):
245
+ return prettyForm(*pform.parens(left=left, right=right))
246
+
247
+ # Printing of labels (i.e. args)
248
+
249
+ def _print_label(self, printer, *args):
250
+ """Prints the label of the QExpr
251
+
252
+ This method prints self.label, using self._label_separator to separate
253
+ the elements. This method should not be overridden, instead, override
254
+ _print_contents to change printing behavior.
255
+ """
256
+ return self._print_sequence(
257
+ self.label, self._label_separator, printer, *args
258
+ )
259
+
260
+ def _print_label_repr(self, printer, *args):
261
+ return self._print_sequence(
262
+ self.label, ',', printer, *args
263
+ )
264
+
265
+ def _print_label_pretty(self, printer, *args):
266
+ return self._print_sequence_pretty(
267
+ self.label, self._label_separator, printer, *args
268
+ )
269
+
270
+ def _print_label_latex(self, printer, *args):
271
+ return self._print_sequence(
272
+ self.label, self._label_separator, printer, *args
273
+ )
274
+
275
+ # Printing of contents (default to label)
276
+
277
+ def _print_contents(self, printer, *args):
278
+ """Printer for contents of QExpr
279
+
280
+ Handles the printing of any unique identifying contents of a QExpr to
281
+ print as its contents, such as any variables or quantum numbers. The
282
+ default is to print the label, which is almost always the args. This
283
+ should not include printing of any brackets or parentheses.
284
+ """
285
+ return self._print_label(printer, *args)
286
+
287
+ def _print_contents_pretty(self, printer, *args):
288
+ return self._print_label_pretty(printer, *args)
289
+
290
+ def _print_contents_latex(self, printer, *args):
291
+ return self._print_label_latex(printer, *args)
292
+
293
+ # Main printing methods
294
+
295
+ def _sympystr(self, printer, *args):
296
+ """Default printing behavior of QExpr objects
297
+
298
+ Handles the default printing of a QExpr. To add other things to the
299
+ printing of the object, such as an operator name to operators or
300
+ brackets to states, the class should override the _print/_pretty/_latex
301
+ functions directly and make calls to _print_contents where appropriate.
302
+ This allows things like InnerProduct to easily control its printing the
303
+ printing of contents.
304
+ """
305
+ return self._print_contents(printer, *args)
306
+
307
+ def _sympyrepr(self, printer, *args):
308
+ classname = self.__class__.__name__
309
+ label = self._print_label_repr(printer, *args)
310
+ return '%s(%s)' % (classname, label)
311
+
312
+ def _pretty(self, printer, *args):
313
+ pform = self._print_contents_pretty(printer, *args)
314
+ return pform
315
+
316
+ def _latex(self, printer, *args):
317
+ return self._print_contents_latex(printer, *args)
318
+
319
+ #-------------------------------------------------------------------------
320
+ # Represent
321
+ #-------------------------------------------------------------------------
322
+
323
+ def _represent_default_basis(self, **options):
324
+ raise NotImplementedError('This object does not have a default basis')
325
+
326
+ def _represent(self, *, basis=None, **options):
327
+ """Represent this object in a given basis.
328
+
329
+ This method dispatches to the actual methods that perform the
330
+ representation. Subclases of QExpr should define various methods to
331
+ determine how the object will be represented in various bases. The
332
+ format of these methods is::
333
+
334
+ def _represent_BasisName(self, basis, **options):
335
+
336
+ Thus to define how a quantum object is represented in the basis of
337
+ the operator Position, you would define::
338
+
339
+ def _represent_Position(self, basis, **options):
340
+
341
+ Usually, basis object will be instances of Operator subclasses, but
342
+ there is a chance we will relax this in the future to accommodate other
343
+ types of basis sets that are not associated with an operator.
344
+
345
+ If the ``format`` option is given it can be ("sympy", "numpy",
346
+ "scipy.sparse"). This will ensure that any matrices that result from
347
+ representing the object are returned in the appropriate matrix format.
348
+
349
+ Parameters
350
+ ==========
351
+
352
+ basis : Operator
353
+ The Operator whose basis functions will be used as the basis for
354
+ representation.
355
+ options : dict
356
+ A dictionary of key/value pairs that give options and hints for
357
+ the representation, such as the number of basis functions to
358
+ be used.
359
+ """
360
+ if basis is None:
361
+ result = self._represent_default_basis(**options)
362
+ else:
363
+ result = dispatch_method(self, '_represent', basis, **options)
364
+
365
+ # If we get a matrix representation, convert it to the right format.
366
+ format = options.get('format', 'sympy')
367
+ result = self._format_represent(result, format)
368
+ return result
369
+
370
+ def _format_represent(self, result, format):
371
+ if format == 'sympy' and not isinstance(result, Matrix):
372
+ return to_sympy(result)
373
+ elif format == 'numpy' and not isinstance(result, numpy_ndarray):
374
+ return to_numpy(result)
375
+ elif format == 'scipy.sparse' and \
376
+ not isinstance(result, scipy_sparse_matrix):
377
+ return to_scipy_sparse(result)
378
+
379
+ return result
380
+
381
+
382
+ def split_commutative_parts(e):
383
+ """Split into commutative and non-commutative parts."""
384
+ c_part, nc_part = e.args_cnc()
385
+ c_part = list(c_part)
386
+ return c_part, nc_part
387
+
388
+
389
+ def split_qexpr_parts(e):
390
+ """Split an expression into Expr and noncommutative QExpr parts."""
391
+ expr_part = []
392
+ qexpr_part = []
393
+ for arg in e.args:
394
+ if not isinstance(arg, QExpr):
395
+ expr_part.append(arg)
396
+ else:
397
+ qexpr_part.append(arg)
398
+ return expr_part, qexpr_part
399
+
400
+
401
+ def dispatch_method(self, basename, arg, **options):
402
+ """Dispatch a method to the proper handlers."""
403
+ method_name = '%s_%s' % (basename, arg.__class__.__name__)
404
+ if hasattr(self, method_name):
405
+ f = getattr(self, method_name)
406
+ # This can raise and we will allow it to propagate.
407
+ result = f(arg, **options)
408
+ if result is not None:
409
+ return result
410
+ raise NotImplementedError(
411
+ "%s.%s cannot handle: %r" %
412
+ (self.__class__.__name__, basename, arg)
413
+ )
venv/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qubits for quantum computing.
2
+
3
+ Todo:
4
+ * Finish implementing measurement logic. This should include POVM.
5
+ * Update docstrings.
6
+ * Update tests.
7
+ """
8
+
9
+
10
+ import math
11
+
12
+ from sympy.core.add import Add
13
+ from sympy.core.mul import Mul
14
+ from sympy.core.numbers import Integer
15
+ from sympy.core.power import Pow
16
+ from sympy.core.singleton import S
17
+ from sympy.functions.elementary.complexes import conjugate
18
+ from sympy.functions.elementary.exponential import log
19
+ from sympy.core.basic import _sympify
20
+ from sympy.external.gmpy import SYMPY_INTS
21
+ from sympy.matrices import Matrix, zeros
22
+ from sympy.printing.pretty.stringpict import prettyForm
23
+
24
+ from sympy.physics.quantum.hilbert import ComplexSpace
25
+ from sympy.physics.quantum.state import Ket, Bra, State
26
+
27
+ from sympy.physics.quantum.qexpr import QuantumError
28
+ from sympy.physics.quantum.represent import represent
29
+ from sympy.physics.quantum.matrixutils import (
30
+ numpy_ndarray, scipy_sparse_matrix
31
+ )
32
+ from mpmath.libmp.libintmath import bitcount
33
+
34
+ __all__ = [
35
+ 'Qubit',
36
+ 'QubitBra',
37
+ 'IntQubit',
38
+ 'IntQubitBra',
39
+ 'qubit_to_matrix',
40
+ 'matrix_to_qubit',
41
+ 'matrix_to_density',
42
+ 'measure_all',
43
+ 'measure_partial',
44
+ 'measure_partial_oneshot',
45
+ 'measure_all_oneshot'
46
+ ]
47
+
48
+ #-----------------------------------------------------------------------------
49
+ # Qubit Classes
50
+ #-----------------------------------------------------------------------------
51
+
52
+
53
+ class QubitState(State):
54
+ """Base class for Qubit and QubitBra."""
55
+
56
+ #-------------------------------------------------------------------------
57
+ # Initialization/creation
58
+ #-------------------------------------------------------------------------
59
+
60
+ @classmethod
61
+ def _eval_args(cls, args):
62
+ # If we are passed a QubitState or subclass, we just take its qubit
63
+ # values directly.
64
+ if len(args) == 1 and isinstance(args[0], QubitState):
65
+ return args[0].qubit_values
66
+
67
+ # Turn strings into tuple of strings
68
+ if len(args) == 1 and isinstance(args[0], str):
69
+ args = tuple( S.Zero if qb == "0" else S.One for qb in args[0])
70
+ else:
71
+ args = tuple( S.Zero if qb == "0" else S.One if qb == "1" else qb for qb in args)
72
+ args = tuple(_sympify(arg) for arg in args)
73
+
74
+ # Validate input (must have 0 or 1 input)
75
+ for element in args:
76
+ if element not in (S.Zero, S.One):
77
+ raise ValueError(
78
+ "Qubit values must be 0 or 1, got: %r" % element)
79
+ return args
80
+
81
+ @classmethod
82
+ def _eval_hilbert_space(cls, args):
83
+ return ComplexSpace(2)**len(args)
84
+
85
+ #-------------------------------------------------------------------------
86
+ # Properties
87
+ #-------------------------------------------------------------------------
88
+
89
+ @property
90
+ def dimension(self):
91
+ """The number of Qubits in the state."""
92
+ return len(self.qubit_values)
93
+
94
+ @property
95
+ def nqubits(self):
96
+ return self.dimension
97
+
98
+ @property
99
+ def qubit_values(self):
100
+ """Returns the values of the qubits as a tuple."""
101
+ return self.label
102
+
103
+ #-------------------------------------------------------------------------
104
+ # Special methods
105
+ #-------------------------------------------------------------------------
106
+
107
+ def __len__(self):
108
+ return self.dimension
109
+
110
+ def __getitem__(self, bit):
111
+ return self.qubit_values[int(self.dimension - bit - 1)]
112
+
113
+ #-------------------------------------------------------------------------
114
+ # Utility methods
115
+ #-------------------------------------------------------------------------
116
+
117
+ def flip(self, *bits):
118
+ """Flip the bit(s) given."""
119
+ newargs = list(self.qubit_values)
120
+ for i in bits:
121
+ bit = int(self.dimension - i - 1)
122
+ if newargs[bit] == 1:
123
+ newargs[bit] = 0
124
+ else:
125
+ newargs[bit] = 1
126
+ return self.__class__(*tuple(newargs))
127
+
128
+
129
+ class Qubit(QubitState, Ket):
130
+ """A multi-qubit ket in the computational (z) basis.
131
+
132
+ We use the normal convention that the least significant qubit is on the
133
+ right, so ``|00001>`` has a 1 in the least significant qubit.
134
+
135
+ Parameters
136
+ ==========
137
+
138
+ values : list, str
139
+ The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
140
+
141
+ Examples
142
+ ========
143
+
144
+ Create a qubit in a couple of different ways and look at their attributes:
145
+
146
+ >>> from sympy.physics.quantum.qubit import Qubit
147
+ >>> Qubit(0,0,0)
148
+ |000>
149
+ >>> q = Qubit('0101')
150
+ >>> q
151
+ |0101>
152
+
153
+ >>> q.nqubits
154
+ 4
155
+ >>> len(q)
156
+ 4
157
+ >>> q.dimension
158
+ 4
159
+ >>> q.qubit_values
160
+ (0, 1, 0, 1)
161
+
162
+ We can flip the value of an individual qubit:
163
+
164
+ >>> q.flip(1)
165
+ |0111>
166
+
167
+ We can take the dagger of a Qubit to get a bra:
168
+
169
+ >>> from sympy.physics.quantum.dagger import Dagger
170
+ >>> Dagger(q)
171
+ <0101|
172
+ >>> type(Dagger(q))
173
+ <class 'sympy.physics.quantum.qubit.QubitBra'>
174
+
175
+ Inner products work as expected:
176
+
177
+ >>> ip = Dagger(q)*q
178
+ >>> ip
179
+ <0101|0101>
180
+ >>> ip.doit()
181
+ 1
182
+ """
183
+
184
+ @classmethod
185
+ def dual_class(self):
186
+ return QubitBra
187
+
188
+ def _eval_innerproduct_QubitBra(self, bra, **hints):
189
+ if self.label == bra.label:
190
+ return S.One
191
+ else:
192
+ return S.Zero
193
+
194
+ def _represent_default_basis(self, **options):
195
+ return self._represent_ZGate(None, **options)
196
+
197
+ def _represent_ZGate(self, basis, **options):
198
+ """Represent this qubits in the computational basis (ZGate).
199
+ """
200
+ _format = options.get('format', 'sympy')
201
+ n = 1
202
+ definite_state = 0
203
+ for it in reversed(self.qubit_values):
204
+ definite_state += n*it
205
+ n = n*2
206
+ result = [0]*(2**self.dimension)
207
+ result[int(definite_state)] = 1
208
+ if _format == 'sympy':
209
+ return Matrix(result)
210
+ elif _format == 'numpy':
211
+ import numpy as np
212
+ return np.array(result, dtype='complex').transpose()
213
+ elif _format == 'scipy.sparse':
214
+ from scipy import sparse
215
+ return sparse.csr_matrix(result, dtype='complex').transpose()
216
+
217
+ def _eval_trace(self, bra, **kwargs):
218
+ indices = kwargs.get('indices', [])
219
+
220
+ #sort index list to begin trace from most-significant
221
+ #qubit
222
+ sorted_idx = list(indices)
223
+ if len(sorted_idx) == 0:
224
+ sorted_idx = list(range(0, self.nqubits))
225
+ sorted_idx.sort()
226
+
227
+ #trace out for each of index
228
+ new_mat = self*bra
229
+ for i in range(len(sorted_idx) - 1, -1, -1):
230
+ # start from tracing out from leftmost qubit
231
+ new_mat = self._reduced_density(new_mat, int(sorted_idx[i]))
232
+
233
+ if (len(sorted_idx) == self.nqubits):
234
+ #in case full trace was requested
235
+ return new_mat[0]
236
+ else:
237
+ return matrix_to_density(new_mat)
238
+
239
+ def _reduced_density(self, matrix, qubit, **options):
240
+ """Compute the reduced density matrix by tracing out one qubit.
241
+ The qubit argument should be of type Python int, since it is used
242
+ in bit operations
243
+ """
244
+ def find_index_that_is_projected(j, k, qubit):
245
+ bit_mask = 2**qubit - 1
246
+ return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit)
247
+
248
+ old_matrix = represent(matrix, **options)
249
+ old_size = old_matrix.cols
250
+ #we expect the old_size to be even
251
+ new_size = old_size//2
252
+ new_matrix = Matrix().zeros(new_size)
253
+
254
+ for i in range(new_size):
255
+ for j in range(new_size):
256
+ for k in range(2):
257
+ col = find_index_that_is_projected(j, k, qubit)
258
+ row = find_index_that_is_projected(i, k, qubit)
259
+ new_matrix[i, j] += old_matrix[row, col]
260
+
261
+ return new_matrix
262
+
263
+
264
+ class QubitBra(QubitState, Bra):
265
+ """A multi-qubit bra in the computational (z) basis.
266
+
267
+ We use the normal convention that the least significant qubit is on the
268
+ right, so ``|00001>`` has a 1 in the least significant qubit.
269
+
270
+ Parameters
271
+ ==========
272
+
273
+ values : list, str
274
+ The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
275
+
276
+ See also
277
+ ========
278
+
279
+ Qubit: Examples using qubits
280
+
281
+ """
282
+ @classmethod
283
+ def dual_class(self):
284
+ return Qubit
285
+
286
+
287
+ class IntQubitState(QubitState):
288
+ """A base class for qubits that work with binary representations."""
289
+
290
+ @classmethod
291
+ def _eval_args(cls, args, nqubits=None):
292
+ # The case of a QubitState instance
293
+ if len(args) == 1 and isinstance(args[0], QubitState):
294
+ return QubitState._eval_args(args)
295
+ # otherwise, args should be integer
296
+ elif not all(isinstance(a, (int, Integer)) for a in args):
297
+ raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),))
298
+ # use nqubits if specified
299
+ if nqubits is not None:
300
+ if not isinstance(nqubits, (int, Integer)):
301
+ raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits))
302
+ if len(args) != 1:
303
+ raise ValueError(
304
+ 'too many positional arguments (%s). should be (number, nqubits=n)' % (args,))
305
+ return cls._eval_args_with_nqubits(args[0], nqubits)
306
+ # For a single argument, we construct the binary representation of
307
+ # that integer with the minimal number of bits.
308
+ if len(args) == 1 and args[0] > 1:
309
+ #rvalues is the minimum number of bits needed to express the number
310
+ rvalues = reversed(range(bitcount(abs(args[0]))))
311
+ qubit_values = [(args[0] >> i) & 1 for i in rvalues]
312
+ return QubitState._eval_args(qubit_values)
313
+ # For two numbers, the second number is the number of bits
314
+ # on which it is expressed, so IntQubit(0,5) == |00000>.
315
+ elif len(args) == 2 and args[1] > 1:
316
+ return cls._eval_args_with_nqubits(args[0], args[1])
317
+ else:
318
+ return QubitState._eval_args(args)
319
+
320
+ @classmethod
321
+ def _eval_args_with_nqubits(cls, number, nqubits):
322
+ need = bitcount(abs(number))
323
+ if nqubits < need:
324
+ raise ValueError(
325
+ 'cannot represent %s with %s bits' % (number, nqubits))
326
+ qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]
327
+ return QubitState._eval_args(qubit_values)
328
+
329
+ def as_int(self):
330
+ """Return the numerical value of the qubit."""
331
+ number = 0
332
+ n = 1
333
+ for i in reversed(self.qubit_values):
334
+ number += n*i
335
+ n = n << 1
336
+ return number
337
+
338
+ def _print_label(self, printer, *args):
339
+ return str(self.as_int())
340
+
341
+ def _print_label_pretty(self, printer, *args):
342
+ label = self._print_label(printer, *args)
343
+ return prettyForm(label)
344
+
345
+ _print_label_repr = _print_label
346
+ _print_label_latex = _print_label
347
+
348
+
349
+ class IntQubit(IntQubitState, Qubit):
350
+ """A qubit ket that store integers as binary numbers in qubit values.
351
+
352
+ The differences between this class and ``Qubit`` are:
353
+
354
+ * The form of the constructor.
355
+ * The qubit values are printed as their corresponding integer, rather
356
+ than the raw qubit values. The internal storage format of the qubit
357
+ values in the same as ``Qubit``.
358
+
359
+ Parameters
360
+ ==========
361
+
362
+ values : int, tuple
363
+ If a single argument, the integer we want to represent in the qubit
364
+ values. This integer will be represented using the fewest possible
365
+ number of qubits.
366
+ If a pair of integers and the second value is more than one, the first
367
+ integer gives the integer to represent in binary form and the second
368
+ integer gives the number of qubits to use.
369
+ List of zeros and ones is also accepted to generate qubit by bit pattern.
370
+
371
+ nqubits : int
372
+ The integer that represents the number of qubits.
373
+ This number should be passed with keyword ``nqubits=N``.
374
+ You can use this in order to avoid ambiguity of Qubit-style tuple of bits.
375
+ Please see the example below for more details.
376
+
377
+ Examples
378
+ ========
379
+
380
+ Create a qubit for the integer 5:
381
+
382
+ >>> from sympy.physics.quantum.qubit import IntQubit
383
+ >>> from sympy.physics.quantum.qubit import Qubit
384
+ >>> q = IntQubit(5)
385
+ >>> q
386
+ |5>
387
+
388
+ We can also create an ``IntQubit`` by passing a ``Qubit`` instance.
389
+
390
+ >>> q = IntQubit(Qubit('101'))
391
+ >>> q
392
+ |5>
393
+ >>> q.as_int()
394
+ 5
395
+ >>> q.nqubits
396
+ 3
397
+ >>> q.qubit_values
398
+ (1, 0, 1)
399
+
400
+ We can go back to the regular qubit form.
401
+
402
+ >>> Qubit(q)
403
+ |101>
404
+
405
+ Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.
406
+ So, the code below yields qubits 3, not a single bit ``1``.
407
+
408
+ >>> IntQubit(1, 1)
409
+ |3>
410
+
411
+ To avoid ambiguity, use ``nqubits`` parameter.
412
+ Use of this keyword is recommended especially when you provide the values by variables.
413
+
414
+ >>> IntQubit(1, nqubits=1)
415
+ |1>
416
+ >>> a = 1
417
+ >>> IntQubit(a, nqubits=1)
418
+ |1>
419
+ """
420
+ @classmethod
421
+ def dual_class(self):
422
+ return IntQubitBra
423
+
424
+ def _eval_innerproduct_IntQubitBra(self, bra, **hints):
425
+ return Qubit._eval_innerproduct_QubitBra(self, bra)
426
+
427
+ class IntQubitBra(IntQubitState, QubitBra):
428
+ """A qubit bra that store integers as binary numbers in qubit values."""
429
+
430
+ @classmethod
431
+ def dual_class(self):
432
+ return IntQubit
433
+
434
+
435
+ #-----------------------------------------------------------------------------
436
+ # Qubit <---> Matrix conversion functions
437
+ #-----------------------------------------------------------------------------
438
+
439
+
440
+ def matrix_to_qubit(matrix):
441
+ """Convert from the matrix repr. to a sum of Qubit objects.
442
+
443
+ Parameters
444
+ ----------
445
+ matrix : Matrix, numpy.matrix, scipy.sparse
446
+ The matrix to build the Qubit representation of. This works with
447
+ SymPy matrices, numpy matrices and scipy.sparse sparse matrices.
448
+
449
+ Examples
450
+ ========
451
+
452
+ Represent a state and then go back to its qubit form:
453
+
454
+ >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit
455
+ >>> from sympy.physics.quantum.represent import represent
456
+ >>> q = Qubit('01')
457
+ >>> matrix_to_qubit(represent(q))
458
+ |01>
459
+ """
460
+ # Determine the format based on the type of the input matrix
461
+ format = 'sympy'
462
+ if isinstance(matrix, numpy_ndarray):
463
+ format = 'numpy'
464
+ if isinstance(matrix, scipy_sparse_matrix):
465
+ format = 'scipy.sparse'
466
+
467
+ # Make sure it is of correct dimensions for a Qubit-matrix representation.
468
+ # This logic should work with sympy, numpy or scipy.sparse matrices.
469
+ if matrix.shape[0] == 1:
470
+ mlistlen = matrix.shape[1]
471
+ nqubits = log(mlistlen, 2)
472
+ ket = False
473
+ cls = QubitBra
474
+ elif matrix.shape[1] == 1:
475
+ mlistlen = matrix.shape[0]
476
+ nqubits = log(mlistlen, 2)
477
+ ket = True
478
+ cls = Qubit
479
+ else:
480
+ raise QuantumError(
481
+ 'Matrix must be a row/column vector, got %r' % matrix
482
+ )
483
+ if not isinstance(nqubits, Integer):
484
+ raise QuantumError('Matrix must be a row/column vector of size '
485
+ '2**nqubits, got: %r' % matrix)
486
+ # Go through each item in matrix, if element is non-zero, make it into a
487
+ # Qubit item times the element.
488
+ result = 0
489
+ for i in range(mlistlen):
490
+ if ket:
491
+ element = matrix[i, 0]
492
+ else:
493
+ element = matrix[0, i]
494
+ if format in ('numpy', 'scipy.sparse'):
495
+ element = complex(element)
496
+ if element != 0.0:
497
+ # Form Qubit array; 0 in bit-locations where i is 0, 1 in
498
+ # bit-locations where i is 1
499
+ qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)]
500
+ qubit_array.reverse()
501
+ result = result + element*cls(*qubit_array)
502
+
503
+ # If SymPy simplified by pulling out a constant coefficient, undo that.
504
+ if isinstance(result, (Mul, Add, Pow)):
505
+ result = result.expand()
506
+
507
+ return result
508
+
509
+
510
+ def matrix_to_density(mat):
511
+ """
512
+ Works by finding the eigenvectors and eigenvalues of the matrix.
513
+ We know we can decompose rho by doing:
514
+ sum(EigenVal*|Eigenvect><Eigenvect|)
515
+ """
516
+ from sympy.physics.quantum.density import Density
517
+ eigen = mat.eigenvects()
518
+ args = [[matrix_to_qubit(Matrix(
519
+ [vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0]
520
+ if (len(args) == 0):
521
+ return S.Zero
522
+ else:
523
+ return Density(*args)
524
+
525
+
526
+ def qubit_to_matrix(qubit, format='sympy'):
527
+ """Converts an Add/Mul of Qubit objects into it's matrix representation
528
+
529
+ This function is the inverse of ``matrix_to_qubit`` and is a shorthand
530
+ for ``represent(qubit)``.
531
+ """
532
+ return represent(qubit, format=format)
533
+
534
+
535
+ #-----------------------------------------------------------------------------
536
+ # Measurement
537
+ #-----------------------------------------------------------------------------
538
+
539
+
540
+ def measure_all(qubit, format='sympy', normalize=True):
541
+ """Perform an ensemble measurement of all qubits.
542
+
543
+ Parameters
544
+ ==========
545
+
546
+ qubit : Qubit, Add
547
+ The qubit to measure. This can be any Qubit or a linear combination
548
+ of them.
549
+ format : str
550
+ The format of the intermediate matrices to use. Possible values are
551
+ ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
552
+ implemented.
553
+
554
+ Returns
555
+ =======
556
+
557
+ result : list
558
+ A list that consists of primitive states and their probabilities.
559
+
560
+ Examples
561
+ ========
562
+
563
+ >>> from sympy.physics.quantum.qubit import Qubit, measure_all
564
+ >>> from sympy.physics.quantum.gate import H
565
+ >>> from sympy.physics.quantum.qapply import qapply
566
+
567
+ >>> c = H(0)*H(1)*Qubit('00')
568
+ >>> c
569
+ H(0)*H(1)*|00>
570
+ >>> q = qapply(c)
571
+ >>> measure_all(q)
572
+ [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)]
573
+ """
574
+ m = qubit_to_matrix(qubit, format)
575
+
576
+ if format == 'sympy':
577
+ results = []
578
+
579
+ if normalize:
580
+ m = m.normalized()
581
+
582
+ size = max(m.shape) # Max of shape to account for bra or ket
583
+ nqubits = int(math.log(size)/math.log(2))
584
+ for i in range(size):
585
+ if m[i] != 0.0:
586
+ results.append(
587
+ (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))
588
+ )
589
+ return results
590
+ else:
591
+ raise NotImplementedError(
592
+ "This function cannot handle non-SymPy matrix formats yet"
593
+ )
594
+
595
+
596
+ def measure_partial(qubit, bits, format='sympy', normalize=True):
597
+ """Perform a partial ensemble measure on the specified qubits.
598
+
599
+ Parameters
600
+ ==========
601
+
602
+ qubits : Qubit
603
+ The qubit to measure. This can be any Qubit or a linear combination
604
+ of them.
605
+ bits : tuple
606
+ The qubits to measure.
607
+ format : str
608
+ The format of the intermediate matrices to use. Possible values are
609
+ ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
610
+ implemented.
611
+
612
+ Returns
613
+ =======
614
+
615
+ result : list
616
+ A list that consists of primitive states and their probabilities.
617
+
618
+ Examples
619
+ ========
620
+
621
+ >>> from sympy.physics.quantum.qubit import Qubit, measure_partial
622
+ >>> from sympy.physics.quantum.gate import H
623
+ >>> from sympy.physics.quantum.qapply import qapply
624
+
625
+ >>> c = H(0)*H(1)*Qubit('00')
626
+ >>> c
627
+ H(0)*H(1)*|00>
628
+ >>> q = qapply(c)
629
+ >>> measure_partial(q, (0,))
630
+ [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)]
631
+ """
632
+ m = qubit_to_matrix(qubit, format)
633
+
634
+ if isinstance(bits, (SYMPY_INTS, Integer)):
635
+ bits = (int(bits),)
636
+
637
+ if format == 'sympy':
638
+ if normalize:
639
+ m = m.normalized()
640
+
641
+ possible_outcomes = _get_possible_outcomes(m, bits)
642
+
643
+ # Form output from function.
644
+ output = []
645
+ for outcome in possible_outcomes:
646
+ # Calculate probability of finding the specified bits with
647
+ # given values.
648
+ prob_of_outcome = 0
649
+ prob_of_outcome += (outcome.H*outcome)[0]
650
+
651
+ # If the output has a chance, append it to output with found
652
+ # probability.
653
+ if prob_of_outcome != 0:
654
+ if normalize:
655
+ next_matrix = matrix_to_qubit(outcome.normalized())
656
+ else:
657
+ next_matrix = matrix_to_qubit(outcome)
658
+
659
+ output.append((
660
+ next_matrix,
661
+ prob_of_outcome
662
+ ))
663
+
664
+ return output
665
+ else:
666
+ raise NotImplementedError(
667
+ "This function cannot handle non-SymPy matrix formats yet"
668
+ )
669
+
670
+
671
+ def measure_partial_oneshot(qubit, bits, format='sympy'):
672
+ """Perform a partial oneshot measurement on the specified qubits.
673
+
674
+ A oneshot measurement is equivalent to performing a measurement on a
675
+ quantum system. This type of measurement does not return the probabilities
676
+ like an ensemble measurement does, but rather returns *one* of the
677
+ possible resulting states. The exact state that is returned is determined
678
+ by picking a state randomly according to the ensemble probabilities.
679
+
680
+ Parameters
681
+ ----------
682
+ qubits : Qubit
683
+ The qubit to measure. This can be any Qubit or a linear combination
684
+ of them.
685
+ bits : tuple
686
+ The qubits to measure.
687
+ format : str
688
+ The format of the intermediate matrices to use. Possible values are
689
+ ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
690
+ implemented.
691
+
692
+ Returns
693
+ -------
694
+ result : Qubit
695
+ The qubit that the system collapsed to upon measurement.
696
+ """
697
+ import random
698
+ m = qubit_to_matrix(qubit, format)
699
+
700
+ if format == 'sympy':
701
+ m = m.normalized()
702
+ possible_outcomes = _get_possible_outcomes(m, bits)
703
+
704
+ # Form output from function
705
+ random_number = random.random()
706
+ total_prob = 0
707
+ for outcome in possible_outcomes:
708
+ # Calculate probability of finding the specified bits
709
+ # with given values
710
+ total_prob += (outcome.H*outcome)[0]
711
+ if total_prob >= random_number:
712
+ return matrix_to_qubit(outcome.normalized())
713
+ else:
714
+ raise NotImplementedError(
715
+ "This function cannot handle non-SymPy matrix formats yet"
716
+ )
717
+
718
+
719
+ def _get_possible_outcomes(m, bits):
720
+ """Get the possible states that can be produced in a measurement.
721
+
722
+ Parameters
723
+ ----------
724
+ m : Matrix
725
+ The matrix representing the state of the system.
726
+ bits : tuple, list
727
+ Which bits will be measured.
728
+
729
+ Returns
730
+ -------
731
+ result : list
732
+ The list of possible states which can occur given this measurement.
733
+ These are un-normalized so we can derive the probability of finding
734
+ this state by taking the inner product with itself
735
+ """
736
+
737
+ # This is filled with loads of dirty binary tricks...You have been warned
738
+
739
+ size = max(m.shape) # Max of shape to account for bra or ket
740
+ nqubits = int(math.log(size, 2) + .1) # Number of qubits possible
741
+
742
+ # Make the output states and put in output_matrices, nothing in them now.
743
+ # Each state will represent a possible outcome of the measurement
744
+ # Thus, output_matrices[0] is the matrix which we get when all measured
745
+ # bits return 0. and output_matrices[1] is the matrix for only the 0th
746
+ # bit being true
747
+ output_matrices = []
748
+ for i in range(1 << len(bits)):
749
+ output_matrices.append(zeros(2**nqubits, 1))
750
+
751
+ # Bitmasks will help sort how to determine possible outcomes.
752
+ # When the bit mask is and-ed with a matrix-index,
753
+ # it will determine which state that index belongs to
754
+ bit_masks = []
755
+ for bit in bits:
756
+ bit_masks.append(1 << bit)
757
+
758
+ # Make possible outcome states
759
+ for i in range(2**nqubits):
760
+ trueness = 0 # This tells us to which output_matrix this value belongs
761
+ # Find trueness
762
+ for j in range(len(bit_masks)):
763
+ if i & bit_masks[j]:
764
+ trueness += j + 1
765
+ # Put the value in the correct output matrix
766
+ output_matrices[trueness][i] = m[i]
767
+ return output_matrices
768
+
769
+
770
+ def measure_all_oneshot(qubit, format='sympy'):
771
+ """Perform a oneshot ensemble measurement on all qubits.
772
+
773
+ A oneshot measurement is equivalent to performing a measurement on a
774
+ quantum system. This type of measurement does not return the probabilities
775
+ like an ensemble measurement does, but rather returns *one* of the
776
+ possible resulting states. The exact state that is returned is determined
777
+ by picking a state randomly according to the ensemble probabilities.
778
+
779
+ Parameters
780
+ ----------
781
+ qubits : Qubit
782
+ The qubit to measure. This can be any Qubit or a linear combination
783
+ of them.
784
+ format : str
785
+ The format of the intermediate matrices to use. Possible values are
786
+ ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
787
+ implemented.
788
+
789
+ Returns
790
+ -------
791
+ result : Qubit
792
+ The qubit that the system collapsed to upon measurement.
793
+ """
794
+ import random
795
+ m = qubit_to_matrix(qubit)
796
+
797
+ if format == 'sympy':
798
+ m = m.normalized()
799
+ random_number = random.random()
800
+ total = 0
801
+ result = 0
802
+ for i in m:
803
+ total += i*i.conjugate()
804
+ if total > random_number:
805
+ break
806
+ result += 1
807
+ return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1)))
808
+ else:
809
+ raise NotImplementedError(
810
+ "This function cannot handle non-SymPy matrix formats yet"
811
+ )
venv/lib/python3.10/site-packages/sympy/physics/quantum/represent.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for representing operators in state in various bases.
2
+
3
+ TODO:
4
+
5
+ * Get represent working with continuous hilbert spaces.
6
+ * Document default basis functionality.
7
+ """
8
+
9
+ from sympy.core.add import Add
10
+ from sympy.core.expr import Expr
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.numbers import I
13
+ from sympy.core.power import Pow
14
+ from sympy.integrals.integrals import integrate
15
+ from sympy.physics.quantum.dagger import Dagger
16
+ from sympy.physics.quantum.commutator import Commutator
17
+ from sympy.physics.quantum.anticommutator import AntiCommutator
18
+ from sympy.physics.quantum.innerproduct import InnerProduct
19
+ from sympy.physics.quantum.qexpr import QExpr
20
+ from sympy.physics.quantum.tensorproduct import TensorProduct
21
+ from sympy.physics.quantum.matrixutils import flatten_scalar
22
+ from sympy.physics.quantum.state import KetBase, BraBase, StateBase
23
+ from sympy.physics.quantum.operator import Operator, OuterProduct
24
+ from sympy.physics.quantum.qapply import qapply
25
+ from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators
26
+
27
+ __all__ = [
28
+ 'represent',
29
+ 'rep_innerproduct',
30
+ 'rep_expectation',
31
+ 'integrate_result',
32
+ 'get_basis',
33
+ 'enumerate_states'
34
+ ]
35
+
36
+ #-----------------------------------------------------------------------------
37
+ # Represent
38
+ #-----------------------------------------------------------------------------
39
+
40
+
41
+ def _sympy_to_scalar(e):
42
+ """Convert from a SymPy scalar to a Python scalar."""
43
+ if isinstance(e, Expr):
44
+ if e.is_Integer:
45
+ return int(e)
46
+ elif e.is_Float:
47
+ return float(e)
48
+ elif e.is_Rational:
49
+ return float(e)
50
+ elif e.is_Number or e.is_NumberSymbol or e == I:
51
+ return complex(e)
52
+ raise TypeError('Expected number, got: %r' % e)
53
+
54
+
55
+ def represent(expr, **options):
56
+ """Represent the quantum expression in the given basis.
57
+
58
+ In quantum mechanics abstract states and operators can be represented in
59
+ various basis sets. Under this operation the follow transforms happen:
60
+
61
+ * Ket -> column vector or function
62
+ * Bra -> row vector of function
63
+ * Operator -> matrix or differential operator
64
+
65
+ This function is the top-level interface for this action.
66
+
67
+ This function walks the SymPy expression tree looking for ``QExpr``
68
+ instances that have a ``_represent`` method. This method is then called
69
+ and the object is replaced by the representation returned by this method.
70
+ By default, the ``_represent`` method will dispatch to other methods
71
+ that handle the representation logic for a particular basis set. The
72
+ naming convention for these methods is the following::
73
+
74
+ def _represent_FooBasis(self, e, basis, **options)
75
+
76
+ This function will have the logic for representing instances of its class
77
+ in the basis set having a class named ``FooBasis``.
78
+
79
+ Parameters
80
+ ==========
81
+
82
+ expr : Expr
83
+ The expression to represent.
84
+ basis : Operator, basis set
85
+ An object that contains the information about the basis set. If an
86
+ operator is used, the basis is assumed to be the orthonormal
87
+ eigenvectors of that operator. In general though, the basis argument
88
+ can be any object that contains the basis set information.
89
+ options : dict
90
+ Key/value pairs of options that are passed to the underlying method
91
+ that finds the representation. These options can be used to
92
+ control how the representation is done. For example, this is where
93
+ the size of the basis set would be set.
94
+
95
+ Returns
96
+ =======
97
+
98
+ e : Expr
99
+ The SymPy expression of the represented quantum expression.
100
+
101
+ Examples
102
+ ========
103
+
104
+ Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator
105
+ and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp``
106
+ method, the ket can be represented in the z-spin basis.
107
+
108
+ >>> from sympy.physics.quantum import Operator, represent, Ket
109
+ >>> from sympy import Matrix
110
+
111
+ >>> class SzUpKet(Ket):
112
+ ... def _represent_SzOp(self, basis, **options):
113
+ ... return Matrix([1,0])
114
+ ...
115
+ >>> class SzOp(Operator):
116
+ ... pass
117
+ ...
118
+ >>> sz = SzOp('Sz')
119
+ >>> up = SzUpKet('up')
120
+ >>> represent(up, basis=sz)
121
+ Matrix([
122
+ [1],
123
+ [0]])
124
+
125
+ Here we see an example of representations in a continuous
126
+ basis. We see that the result of representing various combinations
127
+ of cartesian position operators and kets give us continuous
128
+ expressions involving DiracDelta functions.
129
+
130
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra
131
+ >>> X = XOp()
132
+ >>> x = XKet()
133
+ >>> y = XBra('y')
134
+ >>> represent(X*x)
135
+ x*DiracDelta(x - x_2)
136
+ >>> represent(X*x*y)
137
+ x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
138
+
139
+ """
140
+
141
+ format = options.get('format', 'sympy')
142
+ if format == 'numpy':
143
+ import numpy as np
144
+ if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
145
+ options['replace_none'] = False
146
+ temp_basis = get_basis(expr, **options)
147
+ if temp_basis is not None:
148
+ options['basis'] = temp_basis
149
+ try:
150
+ return expr._represent(**options)
151
+ except NotImplementedError as strerr:
152
+ #If no _represent_FOO method exists, map to the
153
+ #appropriate basis state and try
154
+ #the other methods of representation
155
+ options['replace_none'] = True
156
+
157
+ if isinstance(expr, (KetBase, BraBase)):
158
+ try:
159
+ return rep_innerproduct(expr, **options)
160
+ except NotImplementedError:
161
+ raise NotImplementedError(strerr)
162
+ elif isinstance(expr, Operator):
163
+ try:
164
+ return rep_expectation(expr, **options)
165
+ except NotImplementedError:
166
+ raise NotImplementedError(strerr)
167
+ else:
168
+ raise NotImplementedError(strerr)
169
+ elif isinstance(expr, Add):
170
+ result = represent(expr.args[0], **options)
171
+ for args in expr.args[1:]:
172
+ # scipy.sparse doesn't support += so we use plain = here.
173
+ result = result + represent(args, **options)
174
+ return result
175
+ elif isinstance(expr, Pow):
176
+ base, exp = expr.as_base_exp()
177
+ if format in ('numpy', 'scipy.sparse'):
178
+ exp = _sympy_to_scalar(exp)
179
+ base = represent(base, **options)
180
+ # scipy.sparse doesn't support negative exponents
181
+ # and warns when inverting a matrix in csr format.
182
+ if format == 'scipy.sparse' and exp < 0:
183
+ from scipy.sparse.linalg import inv
184
+ exp = - exp
185
+ base = inv(base.tocsc()).tocsr()
186
+ if format == 'numpy':
187
+ return np.linalg.matrix_power(base, exp)
188
+ return base ** exp
189
+ elif isinstance(expr, TensorProduct):
190
+ new_args = [represent(arg, **options) for arg in expr.args]
191
+ return TensorProduct(*new_args)
192
+ elif isinstance(expr, Dagger):
193
+ return Dagger(represent(expr.args[0], **options))
194
+ elif isinstance(expr, Commutator):
195
+ A = expr.args[0]
196
+ B = expr.args[1]
197
+ return represent(Mul(A, B) - Mul(B, A), **options)
198
+ elif isinstance(expr, AntiCommutator):
199
+ A = expr.args[0]
200
+ B = expr.args[1]
201
+ return represent(Mul(A, B) + Mul(B, A), **options)
202
+ elif isinstance(expr, InnerProduct):
203
+ return represent(Mul(expr.bra, expr.ket), **options)
204
+ elif not isinstance(expr, (Mul, OuterProduct)):
205
+ # For numpy and scipy.sparse, we can only handle numerical prefactors.
206
+ if format in ('numpy', 'scipy.sparse'):
207
+ return _sympy_to_scalar(expr)
208
+ return expr
209
+
210
+ if not isinstance(expr, (Mul, OuterProduct)):
211
+ raise TypeError('Mul expected, got: %r' % expr)
212
+
213
+ if "index" in options:
214
+ options["index"] += 1
215
+ else:
216
+ options["index"] = 1
217
+
218
+ if "unities" not in options:
219
+ options["unities"] = []
220
+
221
+ result = represent(expr.args[-1], **options)
222
+ last_arg = expr.args[-1]
223
+
224
+ for arg in reversed(expr.args[:-1]):
225
+ if isinstance(last_arg, Operator):
226
+ options["index"] += 1
227
+ options["unities"].append(options["index"])
228
+ elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase):
229
+ options["index"] += 1
230
+ elif isinstance(last_arg, KetBase) and isinstance(arg, Operator):
231
+ options["unities"].append(options["index"])
232
+ elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
233
+ options["unities"].append(options["index"])
234
+
235
+ next_arg = represent(arg, **options)
236
+ if format == 'numpy' and isinstance(next_arg, np.ndarray):
237
+ # Must use np.matmult to "matrix multiply" two np.ndarray
238
+ result = np.matmul(next_arg, result)
239
+ else:
240
+ result = next_arg*result
241
+ last_arg = arg
242
+
243
+ # All three matrix formats create 1 by 1 matrices when inner products of
244
+ # vectors are taken. In these cases, we simply return a scalar.
245
+ result = flatten_scalar(result)
246
+
247
+ result = integrate_result(expr, result, **options)
248
+
249
+ return result
250
+
251
+
252
+ def rep_innerproduct(expr, **options):
253
+ """
254
+ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the
255
+ given state.
256
+
257
+ Attempts to calculate inner product with a bra from the specified
258
+ basis. Should only be passed an instance of KetBase or BraBase
259
+
260
+ Parameters
261
+ ==========
262
+
263
+ expr : KetBase or BraBase
264
+ The expression to be represented
265
+
266
+ Examples
267
+ ========
268
+
269
+ >>> from sympy.physics.quantum.represent import rep_innerproduct
270
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
271
+ >>> rep_innerproduct(XKet())
272
+ DiracDelta(x - x_1)
273
+ >>> rep_innerproduct(XKet(), basis=PxOp())
274
+ sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi))
275
+ >>> rep_innerproduct(PxKet(), basis=XOp())
276
+ sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi))
277
+
278
+ """
279
+
280
+ if not isinstance(expr, (KetBase, BraBase)):
281
+ raise TypeError("expr passed is not a Bra or Ket")
282
+
283
+ basis = get_basis(expr, **options)
284
+
285
+ if not isinstance(basis, StateBase):
286
+ raise NotImplementedError("Can't form this representation!")
287
+
288
+ if "index" not in options:
289
+ options["index"] = 1
290
+
291
+ basis_kets = enumerate_states(basis, options["index"], 2)
292
+
293
+ if isinstance(expr, BraBase):
294
+ bra = expr
295
+ ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0])
296
+ else:
297
+ bra = (basis_kets[1].dual if basis_kets[0]
298
+ == expr else basis_kets[0].dual)
299
+ ket = expr
300
+
301
+ prod = InnerProduct(bra, ket)
302
+ result = prod.doit()
303
+
304
+ format = options.get('format', 'sympy')
305
+ return expr._format_represent(result, format)
306
+
307
+
308
+ def rep_expectation(expr, **options):
309
+ """
310
+ Returns an ``<x'|A|x>`` type representation for the given operator.
311
+
312
+ Parameters
313
+ ==========
314
+
315
+ expr : Operator
316
+ Operator to be represented in the specified basis
317
+
318
+ Examples
319
+ ========
320
+
321
+ >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet
322
+ >>> from sympy.physics.quantum.represent import rep_expectation
323
+ >>> rep_expectation(XOp())
324
+ x_1*DiracDelta(x_1 - x_2)
325
+ >>> rep_expectation(XOp(), basis=PxOp())
326
+ <px_2|*X*|px_1>
327
+ >>> rep_expectation(XOp(), basis=PxKet())
328
+ <px_2|*X*|px_1>
329
+
330
+ """
331
+
332
+ if "index" not in options:
333
+ options["index"] = 1
334
+
335
+ if not isinstance(expr, Operator):
336
+ raise TypeError("The passed expression is not an operator")
337
+
338
+ basis_state = get_basis(expr, **options)
339
+
340
+ if basis_state is None or not isinstance(basis_state, StateBase):
341
+ raise NotImplementedError("Could not get basis kets for this operator")
342
+
343
+ basis_kets = enumerate_states(basis_state, options["index"], 2)
344
+
345
+ bra = basis_kets[1].dual
346
+ ket = basis_kets[0]
347
+
348
+ return qapply(bra*expr*ket)
349
+
350
+
351
+ def integrate_result(orig_expr, result, **options):
352
+ """
353
+ Returns the result of integrating over any unities ``(|x><x|)`` in
354
+ the given expression. Intended for integrating over the result of
355
+ representations in continuous bases.
356
+
357
+ This function integrates over any unities that may have been
358
+ inserted into the quantum expression and returns the result.
359
+ It uses the interval of the Hilbert space of the basis state
360
+ passed to it in order to figure out the limits of integration.
361
+ The unities option must be
362
+ specified for this to work.
363
+
364
+ Note: This is mostly used internally by represent(). Examples are
365
+ given merely to show the use cases.
366
+
367
+ Parameters
368
+ ==========
369
+
370
+ orig_expr : quantum expression
371
+ The original expression which was to be represented
372
+
373
+ result: Expr
374
+ The resulting representation that we wish to integrate over
375
+
376
+ Examples
377
+ ========
378
+
379
+ >>> from sympy import symbols, DiracDelta
380
+ >>> from sympy.physics.quantum.represent import integrate_result
381
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet
382
+ >>> x_ket = XKet()
383
+ >>> X_op = XOp()
384
+ >>> x, x_1, x_2 = symbols('x, x_1, x_2')
385
+ >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2))
386
+ x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2)
387
+ >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2),
388
+ ... unities=[1])
389
+ x*DiracDelta(x - x_2)
390
+
391
+ """
392
+ if not isinstance(result, Expr):
393
+ return result
394
+
395
+ options['replace_none'] = True
396
+ if "basis" not in options:
397
+ arg = orig_expr.args[-1]
398
+ options["basis"] = get_basis(arg, **options)
399
+ elif not isinstance(options["basis"], StateBase):
400
+ options["basis"] = get_basis(orig_expr, **options)
401
+
402
+ basis = options.pop("basis", None)
403
+
404
+ if basis is None:
405
+ return result
406
+
407
+ unities = options.pop("unities", [])
408
+
409
+ if len(unities) == 0:
410
+ return result
411
+
412
+ kets = enumerate_states(basis, unities)
413
+ coords = [k.label[0] for k in kets]
414
+
415
+ for coord in coords:
416
+ if coord in result.free_symbols:
417
+ #TODO: Add support for sets of operators
418
+ basis_op = state_to_operators(basis)
419
+ start = basis_op.hilbert_space.interval.start
420
+ end = basis_op.hilbert_space.interval.end
421
+ result = integrate(result, (coord, start, end))
422
+
423
+ return result
424
+
425
+
426
+ def get_basis(expr, *, basis=None, replace_none=True, **options):
427
+ """
428
+ Returns a basis state instance corresponding to the basis specified in
429
+ options=s. If no basis is specified, the function tries to form a default
430
+ basis state of the given expression.
431
+
432
+ There are three behaviors:
433
+
434
+ 1. The basis specified in options is already an instance of StateBase. If
435
+ this is the case, it is simply returned. If the class is specified but
436
+ not an instance, a default instance is returned.
437
+
438
+ 2. The basis specified is an operator or set of operators. If this
439
+ is the case, the operator_to_state mapping method is used.
440
+
441
+ 3. No basis is specified. If expr is a state, then a default instance of
442
+ its class is returned. If expr is an operator, then it is mapped to the
443
+ corresponding state. If it is neither, then we cannot obtain the basis
444
+ state.
445
+
446
+ If the basis cannot be mapped, then it is not changed.
447
+
448
+ This will be called from within represent, and represent will
449
+ only pass QExpr's.
450
+
451
+ TODO (?): Support for Muls and other types of expressions?
452
+
453
+ Parameters
454
+ ==========
455
+
456
+ expr : Operator or StateBase
457
+ Expression whose basis is sought
458
+
459
+ Examples
460
+ ========
461
+
462
+ >>> from sympy.physics.quantum.represent import get_basis
463
+ >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
464
+ >>> x = XKet()
465
+ >>> X = XOp()
466
+ >>> get_basis(x)
467
+ |x>
468
+ >>> get_basis(X)
469
+ |x>
470
+ >>> get_basis(x, basis=PxOp())
471
+ |px>
472
+ >>> get_basis(x, basis=PxKet)
473
+ |px>
474
+
475
+ """
476
+
477
+ if basis is None and not replace_none:
478
+ return None
479
+
480
+ if basis is None:
481
+ if isinstance(expr, KetBase):
482
+ return _make_default(expr.__class__)
483
+ elif isinstance(expr, BraBase):
484
+ return _make_default(expr.dual_class())
485
+ elif isinstance(expr, Operator):
486
+ state_inst = operators_to_state(expr)
487
+ return (state_inst if state_inst is not None else None)
488
+ else:
489
+ return None
490
+ elif (isinstance(basis, Operator) or
491
+ (not isinstance(basis, StateBase) and issubclass(basis, Operator))):
492
+ state = operators_to_state(basis)
493
+ if state is None:
494
+ return None
495
+ elif isinstance(state, StateBase):
496
+ return state
497
+ else:
498
+ return _make_default(state)
499
+ elif isinstance(basis, StateBase):
500
+ return basis
501
+ elif issubclass(basis, StateBase):
502
+ return _make_default(basis)
503
+ else:
504
+ return None
505
+
506
+
507
+ def _make_default(expr):
508
+ # XXX: Catching TypeError like this is a bad way of distinguishing
509
+ # instances from classes. The logic using this function should be
510
+ # rewritten somehow.
511
+ try:
512
+ expr = expr()
513
+ except TypeError:
514
+ return expr
515
+
516
+ return expr
517
+
518
+
519
+ def enumerate_states(*args, **options):
520
+ """
521
+ Returns instances of the given state with dummy indices appended
522
+
523
+ Operates in two different modes:
524
+
525
+ 1. Two arguments are passed to it. The first is the base state which is to
526
+ be indexed, and the second argument is a list of indices to append.
527
+
528
+ 2. Three arguments are passed. The first is again the base state to be
529
+ indexed. The second is the start index for counting. The final argument
530
+ is the number of kets you wish to receive.
531
+
532
+ Tries to call state._enumerate_state. If this fails, returns an empty list
533
+
534
+ Parameters
535
+ ==========
536
+
537
+ args : list
538
+ See list of operation modes above for explanation
539
+
540
+ Examples
541
+ ========
542
+
543
+ >>> from sympy.physics.quantum.cartesian import XBra, XKet
544
+ >>> from sympy.physics.quantum.represent import enumerate_states
545
+ >>> test = XKet('foo')
546
+ >>> enumerate_states(test, 1, 3)
547
+ [|foo_1>, |foo_2>, |foo_3>]
548
+ >>> test2 = XBra('bar')
549
+ >>> enumerate_states(test2, [4, 5, 10])
550
+ [<bar_4|, <bar_5|, <bar_10|]
551
+
552
+ """
553
+
554
+ state = args[0]
555
+
556
+ if len(args) not in (2, 3):
557
+ raise NotImplementedError("Wrong number of arguments!")
558
+
559
+ if not isinstance(state, StateBase):
560
+ raise TypeError("First argument is not a state!")
561
+
562
+ if len(args) == 3:
563
+ num_states = args[2]
564
+ options['start_index'] = args[1]
565
+ else:
566
+ num_states = len(args[1])
567
+ options['index_list'] = args[1]
568
+
569
+ try:
570
+ ret = state._enumerate_state(num_states, **options)
571
+ except NotImplementedError:
572
+ ret = []
573
+
574
+ return ret
venv/lib/python3.10/site-packages/sympy/physics/quantum/sho1d.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple Harmonic Oscillator 1-Dimension"""
2
+
3
+ from sympy.core.numbers import (I, Integer)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.physics.quantum.constants import hbar
8
+ from sympy.physics.quantum.operator import Operator
9
+ from sympy.physics.quantum.state import Bra, Ket, State
10
+ from sympy.physics.quantum.qexpr import QExpr
11
+ from sympy.physics.quantum.cartesian import X, Px
12
+ from sympy.functions.special.tensor_functions import KroneckerDelta
13
+ from sympy.physics.quantum.hilbert import ComplexSpace
14
+ from sympy.physics.quantum.matrixutils import matrix_zeros
15
+
16
+ #------------------------------------------------------------------------------
17
+
18
+ class SHOOp(Operator):
19
+ """A base class for the SHO Operators.
20
+
21
+ We are limiting the number of arguments to be 1.
22
+
23
+ """
24
+
25
+ @classmethod
26
+ def _eval_args(cls, args):
27
+ args = QExpr._eval_args(args)
28
+ if len(args) == 1:
29
+ return args
30
+ else:
31
+ raise ValueError("Too many arguments")
32
+
33
+ @classmethod
34
+ def _eval_hilbert_space(cls, label):
35
+ return ComplexSpace(S.Infinity)
36
+
37
+ class RaisingOp(SHOOp):
38
+ """The Raising Operator or a^dagger.
39
+
40
+ When a^dagger acts on a state it raises the state up by one. Taking
41
+ the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger
42
+ can be rewritten in terms of position and momentum. We can represent
43
+ a^dagger as a matrix, which will be its default basis.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ args : tuple
49
+ The list of numbers or parameters that uniquely specify the
50
+ operator.
51
+
52
+ Examples
53
+ ========
54
+
55
+ Create a Raising Operator and rewrite it in terms of position and
56
+ momentum, and show that taking its adjoint returns 'a':
57
+
58
+ >>> from sympy.physics.quantum.sho1d import RaisingOp
59
+ >>> from sympy.physics.quantum import Dagger
60
+
61
+ >>> ad = RaisingOp('a')
62
+ >>> ad.rewrite('xp').doit()
63
+ sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
64
+
65
+ >>> Dagger(ad)
66
+ a
67
+
68
+ Taking the commutator of a^dagger with other Operators:
69
+
70
+ >>> from sympy.physics.quantum import Commutator
71
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
72
+ >>> from sympy.physics.quantum.sho1d import NumberOp
73
+
74
+ >>> ad = RaisingOp('a')
75
+ >>> a = LoweringOp('a')
76
+ >>> N = NumberOp('N')
77
+ >>> Commutator(ad, a).doit()
78
+ -1
79
+ >>> Commutator(ad, N).doit()
80
+ -RaisingOp(a)
81
+
82
+ Apply a^dagger to a state:
83
+
84
+ >>> from sympy.physics.quantum import qapply
85
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet
86
+
87
+ >>> ad = RaisingOp('a')
88
+ >>> k = SHOKet('k')
89
+ >>> qapply(ad*k)
90
+ sqrt(k + 1)*|k + 1>
91
+
92
+ Matrix Representation
93
+
94
+ >>> from sympy.physics.quantum.sho1d import RaisingOp
95
+ >>> from sympy.physics.quantum.represent import represent
96
+ >>> ad = RaisingOp('a')
97
+ >>> represent(ad, basis=N, ndim=4, format='sympy')
98
+ Matrix([
99
+ [0, 0, 0, 0],
100
+ [1, 0, 0, 0],
101
+ [0, sqrt(2), 0, 0],
102
+ [0, 0, sqrt(3), 0]])
103
+
104
+ """
105
+
106
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
107
+ return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
108
+ S.NegativeOne*I*Px + m*omega*X)
109
+
110
+ def _eval_adjoint(self):
111
+ return LoweringOp(*self.args)
112
+
113
+ def _eval_commutator_LoweringOp(self, other):
114
+ return S.NegativeOne
115
+
116
+ def _eval_commutator_NumberOp(self, other):
117
+ return S.NegativeOne*self
118
+
119
+ def _apply_operator_SHOKet(self, ket, **options):
120
+ temp = ket.n + S.One
121
+ return sqrt(temp)*SHOKet(temp)
122
+
123
+ def _represent_default_basis(self, **options):
124
+ return self._represent_NumberOp(None, **options)
125
+
126
+ def _represent_XOp(self, basis, **options):
127
+ # This logic is good but the underlying position
128
+ # representation logic is broken.
129
+ # temp = self.rewrite('xp').doit()
130
+ # result = represent(temp, basis=X)
131
+ # return result
132
+ raise NotImplementedError('Position representation is not implemented')
133
+
134
+ def _represent_NumberOp(self, basis, **options):
135
+ ndim_info = options.get('ndim', 4)
136
+ format = options.get('format','sympy')
137
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
138
+ for i in range(ndim_info - 1):
139
+ value = sqrt(i + 1)
140
+ if format == 'scipy.sparse':
141
+ value = float(value)
142
+ matrix[i + 1, i] = value
143
+ if format == 'scipy.sparse':
144
+ matrix = matrix.tocsr()
145
+ return matrix
146
+
147
+ #--------------------------------------------------------------------------
148
+ # Printing Methods
149
+ #--------------------------------------------------------------------------
150
+
151
+ def _print_contents(self, printer, *args):
152
+ arg0 = printer._print(self.args[0], *args)
153
+ return '%s(%s)' % (self.__class__.__name__, arg0)
154
+
155
+ def _print_contents_pretty(self, printer, *args):
156
+ from sympy.printing.pretty.stringpict import prettyForm
157
+ pform = printer._print(self.args[0], *args)
158
+ pform = pform**prettyForm('\N{DAGGER}')
159
+ return pform
160
+
161
+ def _print_contents_latex(self, printer, *args):
162
+ arg = printer._print(self.args[0])
163
+ return '%s^{\\dagger}' % arg
164
+
165
+ class LoweringOp(SHOOp):
166
+ """The Lowering Operator or 'a'.
167
+
168
+ When 'a' acts on a state it lowers the state up by one. Taking
169
+ the adjoint of 'a' returns a^dagger, the Raising Operator. 'a'
170
+ can be rewritten in terms of position and momentum. We can
171
+ represent 'a' as a matrix, which will be its default basis.
172
+
173
+ Parameters
174
+ ==========
175
+
176
+ args : tuple
177
+ The list of numbers or parameters that uniquely specify the
178
+ operator.
179
+
180
+ Examples
181
+ ========
182
+
183
+ Create a Lowering Operator and rewrite it in terms of position and
184
+ momentum, and show that taking its adjoint returns a^dagger:
185
+
186
+ >>> from sympy.physics.quantum.sho1d import LoweringOp
187
+ >>> from sympy.physics.quantum import Dagger
188
+
189
+ >>> a = LoweringOp('a')
190
+ >>> a.rewrite('xp').doit()
191
+ sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
192
+
193
+ >>> Dagger(a)
194
+ RaisingOp(a)
195
+
196
+ Taking the commutator of 'a' with other Operators:
197
+
198
+ >>> from sympy.physics.quantum import Commutator
199
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp
200
+ >>> from sympy.physics.quantum.sho1d import NumberOp
201
+
202
+ >>> a = LoweringOp('a')
203
+ >>> ad = RaisingOp('a')
204
+ >>> N = NumberOp('N')
205
+ >>> Commutator(a, ad).doit()
206
+ 1
207
+ >>> Commutator(a, N).doit()
208
+ a
209
+
210
+ Apply 'a' to a state:
211
+
212
+ >>> from sympy.physics.quantum import qapply
213
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
214
+
215
+ >>> a = LoweringOp('a')
216
+ >>> k = SHOKet('k')
217
+ >>> qapply(a*k)
218
+ sqrt(k)*|k - 1>
219
+
220
+ Taking 'a' of the lowest state will return 0:
221
+
222
+ >>> from sympy.physics.quantum import qapply
223
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
224
+
225
+ >>> a = LoweringOp('a')
226
+ >>> k = SHOKet(0)
227
+ >>> qapply(a*k)
228
+ 0
229
+
230
+ Matrix Representation
231
+
232
+ >>> from sympy.physics.quantum.sho1d import LoweringOp
233
+ >>> from sympy.physics.quantum.represent import represent
234
+ >>> a = LoweringOp('a')
235
+ >>> represent(a, basis=N, ndim=4, format='sympy')
236
+ Matrix([
237
+ [0, 1, 0, 0],
238
+ [0, 0, sqrt(2), 0],
239
+ [0, 0, 0, sqrt(3)],
240
+ [0, 0, 0, 0]])
241
+
242
+ """
243
+
244
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
245
+ return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
246
+ I*Px + m*omega*X)
247
+
248
+ def _eval_adjoint(self):
249
+ return RaisingOp(*self.args)
250
+
251
+ def _eval_commutator_RaisingOp(self, other):
252
+ return S.One
253
+
254
+ def _eval_commutator_NumberOp(self, other):
255
+ return self
256
+
257
+ def _apply_operator_SHOKet(self, ket, **options):
258
+ temp = ket.n - Integer(1)
259
+ if ket.n is S.Zero:
260
+ return S.Zero
261
+ else:
262
+ return sqrt(ket.n)*SHOKet(temp)
263
+
264
+ def _represent_default_basis(self, **options):
265
+ return self._represent_NumberOp(None, **options)
266
+
267
+ def _represent_XOp(self, basis, **options):
268
+ # This logic is good but the underlying position
269
+ # representation logic is broken.
270
+ # temp = self.rewrite('xp').doit()
271
+ # result = represent(temp, basis=X)
272
+ # return result
273
+ raise NotImplementedError('Position representation is not implemented')
274
+
275
+ def _represent_NumberOp(self, basis, **options):
276
+ ndim_info = options.get('ndim', 4)
277
+ format = options.get('format', 'sympy')
278
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
279
+ for i in range(ndim_info - 1):
280
+ value = sqrt(i + 1)
281
+ if format == 'scipy.sparse':
282
+ value = float(value)
283
+ matrix[i,i + 1] = value
284
+ if format == 'scipy.sparse':
285
+ matrix = matrix.tocsr()
286
+ return matrix
287
+
288
+
289
+ class NumberOp(SHOOp):
290
+ """The Number Operator is simply a^dagger*a
291
+
292
+ It is often useful to write a^dagger*a as simply the Number Operator
293
+ because the Number Operator commutes with the Hamiltonian. And can be
294
+ expressed using the Number Operator. Also the Number Operator can be
295
+ applied to states. We can represent the Number Operator as a matrix,
296
+ which will be its default basis.
297
+
298
+ Parameters
299
+ ==========
300
+
301
+ args : tuple
302
+ The list of numbers or parameters that uniquely specify the
303
+ operator.
304
+
305
+ Examples
306
+ ========
307
+
308
+ Create a Number Operator and rewrite it in terms of the ladder
309
+ operators, position and momentum operators, and Hamiltonian:
310
+
311
+ >>> from sympy.physics.quantum.sho1d import NumberOp
312
+
313
+ >>> N = NumberOp('N')
314
+ >>> N.rewrite('a').doit()
315
+ RaisingOp(a)*a
316
+ >>> N.rewrite('xp').doit()
317
+ -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega)
318
+ >>> N.rewrite('H').doit()
319
+ -1/2 + H/(hbar*omega)
320
+
321
+ Take the Commutator of the Number Operator with other Operators:
322
+
323
+ >>> from sympy.physics.quantum import Commutator
324
+ >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian
325
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
326
+
327
+ >>> N = NumberOp('N')
328
+ >>> H = Hamiltonian('H')
329
+ >>> ad = RaisingOp('a')
330
+ >>> a = LoweringOp('a')
331
+ >>> Commutator(N,H).doit()
332
+ 0
333
+ >>> Commutator(N,ad).doit()
334
+ RaisingOp(a)
335
+ >>> Commutator(N,a).doit()
336
+ -a
337
+
338
+ Apply the Number Operator to a state:
339
+
340
+ >>> from sympy.physics.quantum import qapply
341
+ >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet
342
+
343
+ >>> N = NumberOp('N')
344
+ >>> k = SHOKet('k')
345
+ >>> qapply(N*k)
346
+ k*|k>
347
+
348
+ Matrix Representation
349
+
350
+ >>> from sympy.physics.quantum.sho1d import NumberOp
351
+ >>> from sympy.physics.quantum.represent import represent
352
+ >>> N = NumberOp('N')
353
+ >>> represent(N, basis=N, ndim=4, format='sympy')
354
+ Matrix([
355
+ [0, 0, 0, 0],
356
+ [0, 1, 0, 0],
357
+ [0, 0, 2, 0],
358
+ [0, 0, 0, 3]])
359
+
360
+ """
361
+
362
+ def _eval_rewrite_as_a(self, *args, **kwargs):
363
+ return ad*a
364
+
365
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
366
+ return (S.One/(Integer(2)*m*hbar*omega))*(Px**2 + (
367
+ m*omega*X)**2) - S.Half
368
+
369
+ def _eval_rewrite_as_H(self, *args, **kwargs):
370
+ return H/(hbar*omega) - S.Half
371
+
372
+ def _apply_operator_SHOKet(self, ket, **options):
373
+ return ket.n*ket
374
+
375
+ def _eval_commutator_Hamiltonian(self, other):
376
+ return S.Zero
377
+
378
+ def _eval_commutator_RaisingOp(self, other):
379
+ return other
380
+
381
+ def _eval_commutator_LoweringOp(self, other):
382
+ return S.NegativeOne*other
383
+
384
+ def _represent_default_basis(self, **options):
385
+ return self._represent_NumberOp(None, **options)
386
+
387
+ def _represent_XOp(self, basis, **options):
388
+ # This logic is good but the underlying position
389
+ # representation logic is broken.
390
+ # temp = self.rewrite('xp').doit()
391
+ # result = represent(temp, basis=X)
392
+ # return result
393
+ raise NotImplementedError('Position representation is not implemented')
394
+
395
+ def _represent_NumberOp(self, basis, **options):
396
+ ndim_info = options.get('ndim', 4)
397
+ format = options.get('format', 'sympy')
398
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
399
+ for i in range(ndim_info):
400
+ value = i
401
+ if format == 'scipy.sparse':
402
+ value = float(value)
403
+ matrix[i,i] = value
404
+ if format == 'scipy.sparse':
405
+ matrix = matrix.tocsr()
406
+ return matrix
407
+
408
+
409
+ class Hamiltonian(SHOOp):
410
+ """The Hamiltonian Operator.
411
+
412
+ The Hamiltonian is used to solve the time-independent Schrodinger
413
+ equation. The Hamiltonian can be expressed using the ladder operators,
414
+ as well as by position and momentum. We can represent the Hamiltonian
415
+ Operator as a matrix, which will be its default basis.
416
+
417
+ Parameters
418
+ ==========
419
+
420
+ args : tuple
421
+ The list of numbers or parameters that uniquely specify the
422
+ operator.
423
+
424
+ Examples
425
+ ========
426
+
427
+ Create a Hamiltonian Operator and rewrite it in terms of the ladder
428
+ operators, position and momentum, and the Number Operator:
429
+
430
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian
431
+
432
+ >>> H = Hamiltonian('H')
433
+ >>> H.rewrite('a').doit()
434
+ hbar*omega*(1/2 + RaisingOp(a)*a)
435
+ >>> H.rewrite('xp').doit()
436
+ (m**2*omega**2*X**2 + Px**2)/(2*m)
437
+ >>> H.rewrite('N').doit()
438
+ hbar*omega*(1/2 + N)
439
+
440
+ Take the Commutator of the Hamiltonian and the Number Operator:
441
+
442
+ >>> from sympy.physics.quantum import Commutator
443
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp
444
+
445
+ >>> H = Hamiltonian('H')
446
+ >>> N = NumberOp('N')
447
+ >>> Commutator(H,N).doit()
448
+ 0
449
+
450
+ Apply the Hamiltonian Operator to a state:
451
+
452
+ >>> from sympy.physics.quantum import qapply
453
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet
454
+
455
+ >>> H = Hamiltonian('H')
456
+ >>> k = SHOKet('k')
457
+ >>> qapply(H*k)
458
+ hbar*k*omega*|k> + hbar*omega*|k>/2
459
+
460
+ Matrix Representation
461
+
462
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian
463
+ >>> from sympy.physics.quantum.represent import represent
464
+
465
+ >>> H = Hamiltonian('H')
466
+ >>> represent(H, basis=N, ndim=4, format='sympy')
467
+ Matrix([
468
+ [hbar*omega/2, 0, 0, 0],
469
+ [ 0, 3*hbar*omega/2, 0, 0],
470
+ [ 0, 0, 5*hbar*omega/2, 0],
471
+ [ 0, 0, 0, 7*hbar*omega/2]])
472
+
473
+ """
474
+
475
+ def _eval_rewrite_as_a(self, *args, **kwargs):
476
+ return hbar*omega*(ad*a + S.Half)
477
+
478
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
479
+ return (S.One/(Integer(2)*m))*(Px**2 + (m*omega*X)**2)
480
+
481
+ def _eval_rewrite_as_N(self, *args, **kwargs):
482
+ return hbar*omega*(N + S.Half)
483
+
484
+ def _apply_operator_SHOKet(self, ket, **options):
485
+ return (hbar*omega*(ket.n + S.Half))*ket
486
+
487
+ def _eval_commutator_NumberOp(self, other):
488
+ return S.Zero
489
+
490
+ def _represent_default_basis(self, **options):
491
+ return self._represent_NumberOp(None, **options)
492
+
493
+ def _represent_XOp(self, basis, **options):
494
+ # This logic is good but the underlying position
495
+ # representation logic is broken.
496
+ # temp = self.rewrite('xp').doit()
497
+ # result = represent(temp, basis=X)
498
+ # return result
499
+ raise NotImplementedError('Position representation is not implemented')
500
+
501
+ def _represent_NumberOp(self, basis, **options):
502
+ ndim_info = options.get('ndim', 4)
503
+ format = options.get('format', 'sympy')
504
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
505
+ for i in range(ndim_info):
506
+ value = i + S.Half
507
+ if format == 'scipy.sparse':
508
+ value = float(value)
509
+ matrix[i,i] = value
510
+ if format == 'scipy.sparse':
511
+ matrix = matrix.tocsr()
512
+ return hbar*omega*matrix
513
+
514
+ #------------------------------------------------------------------------------
515
+
516
+ class SHOState(State):
517
+ """State class for SHO states"""
518
+
519
+ @classmethod
520
+ def _eval_hilbert_space(cls, label):
521
+ return ComplexSpace(S.Infinity)
522
+
523
+ @property
524
+ def n(self):
525
+ return self.args[0]
526
+
527
+
528
+ class SHOKet(SHOState, Ket):
529
+ """1D eigenket.
530
+
531
+ Inherits from SHOState and Ket.
532
+
533
+ Parameters
534
+ ==========
535
+
536
+ args : tuple
537
+ The list of numbers or parameters that uniquely specify the ket
538
+ This is usually its quantum numbers or its symbol.
539
+
540
+ Examples
541
+ ========
542
+
543
+ Ket's know about their associated bra:
544
+
545
+ >>> from sympy.physics.quantum.sho1d import SHOKet
546
+
547
+ >>> k = SHOKet('k')
548
+ >>> k.dual
549
+ <k|
550
+ >>> k.dual_class()
551
+ <class 'sympy.physics.quantum.sho1d.SHOBra'>
552
+
553
+ Take the Inner Product with a bra:
554
+
555
+ >>> from sympy.physics.quantum import InnerProduct
556
+ >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra
557
+
558
+ >>> k = SHOKet('k')
559
+ >>> b = SHOBra('b')
560
+ >>> InnerProduct(b,k).doit()
561
+ KroneckerDelta(b, k)
562
+
563
+ Vector representation of a numerical state ket:
564
+
565
+ >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp
566
+ >>> from sympy.physics.quantum.represent import represent
567
+
568
+ >>> k = SHOKet(3)
569
+ >>> N = NumberOp('N')
570
+ >>> represent(k, basis=N, ndim=4)
571
+ Matrix([
572
+ [0],
573
+ [0],
574
+ [0],
575
+ [1]])
576
+
577
+ """
578
+
579
+ @classmethod
580
+ def dual_class(self):
581
+ return SHOBra
582
+
583
+ def _eval_innerproduct_SHOBra(self, bra, **hints):
584
+ result = KroneckerDelta(self.n, bra.n)
585
+ return result
586
+
587
+ def _represent_default_basis(self, **options):
588
+ return self._represent_NumberOp(None, **options)
589
+
590
+ def _represent_NumberOp(self, basis, **options):
591
+ ndim_info = options.get('ndim', 4)
592
+ format = options.get('format', 'sympy')
593
+ options['spmatrix'] = 'lil'
594
+ vector = matrix_zeros(ndim_info, 1, **options)
595
+ if isinstance(self.n, Integer):
596
+ if self.n >= ndim_info:
597
+ return ValueError("N-Dimension too small")
598
+ if format == 'scipy.sparse':
599
+ vector[int(self.n), 0] = 1.0
600
+ vector = vector.tocsr()
601
+ elif format == 'numpy':
602
+ vector[int(self.n), 0] = 1.0
603
+ else:
604
+ vector[self.n, 0] = S.One
605
+ return vector
606
+ else:
607
+ return ValueError("Not Numerical State")
608
+
609
+
610
+ class SHOBra(SHOState, Bra):
611
+ """A time-independent Bra in SHO.
612
+
613
+ Inherits from SHOState and Bra.
614
+
615
+ Parameters
616
+ ==========
617
+
618
+ args : tuple
619
+ The list of numbers or parameters that uniquely specify the ket
620
+ This is usually its quantum numbers or its symbol.
621
+
622
+ Examples
623
+ ========
624
+
625
+ Bra's know about their associated ket:
626
+
627
+ >>> from sympy.physics.quantum.sho1d import SHOBra
628
+
629
+ >>> b = SHOBra('b')
630
+ >>> b.dual
631
+ |b>
632
+ >>> b.dual_class()
633
+ <class 'sympy.physics.quantum.sho1d.SHOKet'>
634
+
635
+ Vector representation of a numerical state bra:
636
+
637
+ >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp
638
+ >>> from sympy.physics.quantum.represent import represent
639
+
640
+ >>> b = SHOBra(3)
641
+ >>> N = NumberOp('N')
642
+ >>> represent(b, basis=N, ndim=4)
643
+ Matrix([[0, 0, 0, 1]])
644
+
645
+ """
646
+
647
+ @classmethod
648
+ def dual_class(self):
649
+ return SHOKet
650
+
651
+ def _represent_default_basis(self, **options):
652
+ return self._represent_NumberOp(None, **options)
653
+
654
+ def _represent_NumberOp(self, basis, **options):
655
+ ndim_info = options.get('ndim', 4)
656
+ format = options.get('format', 'sympy')
657
+ options['spmatrix'] = 'lil'
658
+ vector = matrix_zeros(1, ndim_info, **options)
659
+ if isinstance(self.n, Integer):
660
+ if self.n >= ndim_info:
661
+ return ValueError("N-Dimension too small")
662
+ if format == 'scipy.sparse':
663
+ vector[0, int(self.n)] = 1.0
664
+ vector = vector.tocsr()
665
+ elif format == 'numpy':
666
+ vector[0, int(self.n)] = 1.0
667
+ else:
668
+ vector[0, self.n] = S.One
669
+ return vector
670
+ else:
671
+ return ValueError("Not Numerical State")
672
+
673
+
674
+ ad = RaisingOp('a')
675
+ a = LoweringOp('a')
676
+ H = Hamiltonian('H')
677
+ N = NumberOp('N')
678
+ omega = Symbol('omega')
679
+ m = Symbol('m')
venv/lib/python3.10/site-packages/sympy/physics/quantum/shor.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shor's algorithm and helper functions.
2
+
3
+ Todo:
4
+
5
+ * Get the CMod gate working again using the new Gate API.
6
+ * Fix everything.
7
+ * Update docstrings and reformat.
8
+ """
9
+
10
+ import math
11
+ import random
12
+
13
+ from sympy.core.mul import Mul
14
+ from sympy.core.singleton import S
15
+ from sympy.functions.elementary.exponential import log
16
+ from sympy.functions.elementary.miscellaneous import sqrt
17
+ from sympy.core.numbers import igcd
18
+ from sympy.ntheory import continued_fraction_periodic as continued_fraction
19
+ from sympy.utilities.iterables import variations
20
+
21
+ from sympy.physics.quantum.gate import Gate
22
+ from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot
23
+ from sympy.physics.quantum.qapply import qapply
24
+ from sympy.physics.quantum.qft import QFT
25
+ from sympy.physics.quantum.qexpr import QuantumError
26
+
27
+
28
+ class OrderFindingException(QuantumError):
29
+ pass
30
+
31
+
32
+ class CMod(Gate):
33
+ """A controlled mod gate.
34
+
35
+ This is black box controlled Mod function for use by shor's algorithm.
36
+ TODO: implement a decompose property that returns how to do this in terms
37
+ of elementary gates
38
+ """
39
+
40
+ @classmethod
41
+ def _eval_args(cls, args):
42
+ # t = args[0]
43
+ # a = args[1]
44
+ # N = args[2]
45
+ raise NotImplementedError('The CMod gate has not been completed.')
46
+
47
+ @property
48
+ def t(self):
49
+ """Size of 1/2 input register. First 1/2 holds output."""
50
+ return self.label[0]
51
+
52
+ @property
53
+ def a(self):
54
+ """Base of the controlled mod function."""
55
+ return self.label[1]
56
+
57
+ @property
58
+ def N(self):
59
+ """N is the type of modular arithmetic we are doing."""
60
+ return self.label[2]
61
+
62
+ def _apply_operator_Qubit(self, qubits, **options):
63
+ """
64
+ This directly calculates the controlled mod of the second half of
65
+ the register and puts it in the second
66
+ This will look pretty when we get Tensor Symbolically working
67
+ """
68
+ n = 1
69
+ k = 0
70
+ # Determine the value stored in high memory.
71
+ for i in range(self.t):
72
+ k += n*qubits[self.t + i]
73
+ n *= 2
74
+
75
+ # The value to go in low memory will be out.
76
+ out = int(self.a**k % self.N)
77
+
78
+ # Create array for new qbit-ket which will have high memory unaffected
79
+ outarray = list(qubits.args[0][:self.t])
80
+
81
+ # Place out in low memory
82
+ for i in reversed(range(self.t)):
83
+ outarray.append((out >> i) & 1)
84
+
85
+ return Qubit(*outarray)
86
+
87
+
88
+ def shor(N):
89
+ """This function implements Shor's factoring algorithm on the Integer N
90
+
91
+ The algorithm starts by picking a random number (a) and seeing if it is
92
+ coprime with N. If it is not, then the gcd of the two numbers is a factor
93
+ and we are done. Otherwise, it begins the period_finding subroutine which
94
+ finds the period of a in modulo N arithmetic. This period, if even, can
95
+ be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1.
96
+ These values are returned.
97
+ """
98
+ a = random.randrange(N - 2) + 2
99
+ if igcd(N, a) != 1:
100
+ return igcd(N, a)
101
+ r = period_find(a, N)
102
+ if r % 2 == 1:
103
+ shor(N)
104
+ answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N))
105
+ return answer
106
+
107
+
108
+ def getr(x, y, N):
109
+ fraction = continued_fraction(x, y)
110
+ # Now convert into r
111
+ total = ratioize(fraction, N)
112
+ return total
113
+
114
+
115
+ def ratioize(list, N):
116
+ if list[0] > N:
117
+ return S.Zero
118
+ if len(list) == 1:
119
+ return list[0]
120
+ return list[0] + ratioize(list[1:], N)
121
+
122
+
123
+ def period_find(a, N):
124
+ """Finds the period of a in modulo N arithmetic
125
+
126
+ This is quantum part of Shor's algorithm. It takes two registers,
127
+ puts first in superposition of states with Hadamards so: ``|k>|0>``
128
+ with k being all possible choices. It then does a controlled mod and
129
+ a QFT to determine the order of a.
130
+ """
131
+ epsilon = .5
132
+ # picks out t's such that maintains accuracy within epsilon
133
+ t = int(2*math.ceil(log(N, 2)))
134
+ # make the first half of register be 0's |000...000>
135
+ start = [0 for x in range(t)]
136
+ # Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0>
137
+ factor = 1/sqrt(2**t)
138
+ qubits = 0
139
+ for arr in variations(range(2), t, repetition=True):
140
+ qbitArray = list(arr) + start
141
+ qubits = qubits + Qubit(*qbitArray)
142
+ circuit = (factor*qubits).expand()
143
+ # Controlled second half of register so that we have:
144
+ # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n>
145
+ circuit = CMod(t, a, N)*circuit
146
+ # will measure first half of register giving one of the a**k%N's
147
+
148
+ circuit = qapply(circuit)
149
+ for i in range(t):
150
+ circuit = measure_partial_oneshot(circuit, i)
151
+ # Now apply Inverse Quantum Fourier Transform on the second half of the register
152
+
153
+ circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True)
154
+ for i in range(t):
155
+ circuit = measure_partial_oneshot(circuit, i + t)
156
+ if isinstance(circuit, Qubit):
157
+ register = circuit
158
+ elif isinstance(circuit, Mul):
159
+ register = circuit.args[-1]
160
+ else:
161
+ register = circuit.args[-1].args[-1]
162
+
163
+ n = 1
164
+ answer = 0
165
+ for i in range(len(register)/2):
166
+ answer += n*register[i + t]
167
+ n = n << 1
168
+ if answer == 0:
169
+ raise OrderFindingException(
170
+ "Order finder returned 0. Happens with chance %f" % epsilon)
171
+ #turn answer into r using continued fractions
172
+ g = getr(answer, 2**t, N)
173
+ return g
venv/lib/python3.10/site-packages/sympy/physics/quantum/spin.py ADDED
@@ -0,0 +1,2149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quantum mechanical angular momemtum."""
2
+
3
+ from sympy.concrete.summations import Sum
4
+ from sympy.core.add import Add
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.expr import Expr
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.numbers import (I, Integer, Rational, pi)
9
+ from sympy.core.singleton import S
10
+ from sympy.core.symbol import (Dummy, symbols)
11
+ from sympy.core.sympify import sympify
12
+ from sympy.functions.combinatorial.factorials import (binomial, factorial)
13
+ from sympy.functions.elementary.exponential import exp
14
+ from sympy.functions.elementary.miscellaneous import sqrt
15
+ from sympy.functions.elementary.trigonometric import (cos, sin)
16
+ from sympy.simplify.simplify import simplify
17
+ from sympy.matrices import zeros
18
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
19
+ from sympy.printing.pretty.pretty_symbology import pretty_symbol
20
+
21
+ from sympy.physics.quantum.qexpr import QExpr
22
+ from sympy.physics.quantum.operator import (HermitianOperator, Operator,
23
+ UnitaryOperator)
24
+ from sympy.physics.quantum.state import Bra, Ket, State
25
+ from sympy.functions.special.tensor_functions import KroneckerDelta
26
+ from sympy.physics.quantum.constants import hbar
27
+ from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
28
+ from sympy.physics.quantum.tensorproduct import TensorProduct
29
+ from sympy.physics.quantum.cg import CG
30
+ from sympy.physics.quantum.qapply import qapply
31
+
32
+
33
+ __all__ = [
34
+ 'm_values',
35
+ 'Jplus',
36
+ 'Jminus',
37
+ 'Jx',
38
+ 'Jy',
39
+ 'Jz',
40
+ 'J2',
41
+ 'Rotation',
42
+ 'WignerD',
43
+ 'JxKet',
44
+ 'JxBra',
45
+ 'JyKet',
46
+ 'JyBra',
47
+ 'JzKet',
48
+ 'JzBra',
49
+ 'JzOp',
50
+ 'J2Op',
51
+ 'JxKetCoupled',
52
+ 'JxBraCoupled',
53
+ 'JyKetCoupled',
54
+ 'JyBraCoupled',
55
+ 'JzKetCoupled',
56
+ 'JzBraCoupled',
57
+ 'couple',
58
+ 'uncouple'
59
+ ]
60
+
61
+
62
+ def m_values(j):
63
+ j = sympify(j)
64
+ size = 2*j + 1
65
+ if not size.is_Integer or not size > 0:
66
+ raise ValueError(
67
+ 'Only integer or half-integer values allowed for j, got: : %r' % j
68
+ )
69
+ return size, [j - i for i in range(int(2*j + 1))]
70
+
71
+
72
+ #-----------------------------------------------------------------------------
73
+ # Spin Operators
74
+ #-----------------------------------------------------------------------------
75
+
76
+
77
+ class SpinOpBase:
78
+ """Base class for spin operators."""
79
+
80
+ @classmethod
81
+ def _eval_hilbert_space(cls, label):
82
+ # We consider all j values so our space is infinite.
83
+ return ComplexSpace(S.Infinity)
84
+
85
+ @property
86
+ def name(self):
87
+ return self.args[0]
88
+
89
+ def _print_contents(self, printer, *args):
90
+ return '%s%s' % (self.name, self._coord)
91
+
92
+ def _print_contents_pretty(self, printer, *args):
93
+ a = stringPict(str(self.name))
94
+ b = stringPict(self._coord)
95
+ return self._print_subscript_pretty(a, b)
96
+
97
+ def _print_contents_latex(self, printer, *args):
98
+ return r'%s_%s' % ((self.name, self._coord))
99
+
100
+ def _represent_base(self, basis, **options):
101
+ j = options.get('j', S.Half)
102
+ size, mvals = m_values(j)
103
+ result = zeros(size, size)
104
+ for p in range(size):
105
+ for q in range(size):
106
+ me = self.matrix_element(j, mvals[p], j, mvals[q])
107
+ result[p, q] = me
108
+ return result
109
+
110
+ def _apply_op(self, ket, orig_basis, **options):
111
+ state = ket.rewrite(self.basis)
112
+ # If the state has only one term
113
+ if isinstance(state, State):
114
+ ret = (hbar*state.m)*state
115
+ # state is a linear combination of states
116
+ elif isinstance(state, Sum):
117
+ ret = self._apply_operator_Sum(state, **options)
118
+ else:
119
+ ret = qapply(self*state)
120
+ if ret == self*state:
121
+ raise NotImplementedError
122
+ return ret.rewrite(orig_basis)
123
+
124
+ def _apply_operator_JxKet(self, ket, **options):
125
+ return self._apply_op(ket, 'Jx', **options)
126
+
127
+ def _apply_operator_JxKetCoupled(self, ket, **options):
128
+ return self._apply_op(ket, 'Jx', **options)
129
+
130
+ def _apply_operator_JyKet(self, ket, **options):
131
+ return self._apply_op(ket, 'Jy', **options)
132
+
133
+ def _apply_operator_JyKetCoupled(self, ket, **options):
134
+ return self._apply_op(ket, 'Jy', **options)
135
+
136
+ def _apply_operator_JzKet(self, ket, **options):
137
+ return self._apply_op(ket, 'Jz', **options)
138
+
139
+ def _apply_operator_JzKetCoupled(self, ket, **options):
140
+ return self._apply_op(ket, 'Jz', **options)
141
+
142
+ def _apply_operator_TensorProduct(self, tp, **options):
143
+ # Uncoupling operator is only easily found for coordinate basis spin operators
144
+ # TODO: add methods for uncoupling operators
145
+ if not isinstance(self, (JxOp, JyOp, JzOp)):
146
+ raise NotImplementedError
147
+ result = []
148
+ for n in range(len(tp.args)):
149
+ arg = []
150
+ arg.extend(tp.args[:n])
151
+ arg.append(self._apply_operator(tp.args[n]))
152
+ arg.extend(tp.args[n + 1:])
153
+ result.append(tp.__class__(*arg))
154
+ return Add(*result).expand()
155
+
156
+ # TODO: move this to qapply_Mul
157
+ def _apply_operator_Sum(self, s, **options):
158
+ new_func = qapply(self*s.function)
159
+ if new_func == self*s.function:
160
+ raise NotImplementedError
161
+ return Sum(new_func, *s.limits)
162
+
163
+ def _eval_trace(self, **options):
164
+ #TODO: use options to use different j values
165
+ #For now eval at default basis
166
+
167
+ # is it efficient to represent each time
168
+ # to do a trace?
169
+ return self._represent_default_basis().trace()
170
+
171
+
172
+ class JplusOp(SpinOpBase, Operator):
173
+ """The J+ operator."""
174
+
175
+ _coord = '+'
176
+
177
+ basis = 'Jz'
178
+
179
+ def _eval_commutator_JminusOp(self, other):
180
+ return 2*hbar*JzOp(self.name)
181
+
182
+ def _apply_operator_JzKet(self, ket, **options):
183
+ j = ket.j
184
+ m = ket.m
185
+ if m.is_Number and j.is_Number:
186
+ if m >= j:
187
+ return S.Zero
188
+ return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
189
+
190
+ def _apply_operator_JzKetCoupled(self, ket, **options):
191
+ j = ket.j
192
+ m = ket.m
193
+ jn = ket.jn
194
+ coupling = ket.coupling
195
+ if m.is_Number and j.is_Number:
196
+ if m >= j:
197
+ return S.Zero
198
+ return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
199
+
200
+ def matrix_element(self, j, m, jp, mp):
201
+ result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
202
+ result *= KroneckerDelta(m, mp + 1)
203
+ result *= KroneckerDelta(j, jp)
204
+ return result
205
+
206
+ def _represent_default_basis(self, **options):
207
+ return self._represent_JzOp(None, **options)
208
+
209
+ def _represent_JzOp(self, basis, **options):
210
+ return self._represent_base(basis, **options)
211
+
212
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
213
+ return JxOp(args[0]) + I*JyOp(args[0])
214
+
215
+
216
+ class JminusOp(SpinOpBase, Operator):
217
+ """The J- operator."""
218
+
219
+ _coord = '-'
220
+
221
+ basis = 'Jz'
222
+
223
+ def _apply_operator_JzKet(self, ket, **options):
224
+ j = ket.j
225
+ m = ket.m
226
+ if m.is_Number and j.is_Number:
227
+ if m <= -j:
228
+ return S.Zero
229
+ return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
230
+
231
+ def _apply_operator_JzKetCoupled(self, ket, **options):
232
+ j = ket.j
233
+ m = ket.m
234
+ jn = ket.jn
235
+ coupling = ket.coupling
236
+ if m.is_Number and j.is_Number:
237
+ if m <= -j:
238
+ return S.Zero
239
+ return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
240
+
241
+ def matrix_element(self, j, m, jp, mp):
242
+ result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
243
+ result *= KroneckerDelta(m, mp - 1)
244
+ result *= KroneckerDelta(j, jp)
245
+ return result
246
+
247
+ def _represent_default_basis(self, **options):
248
+ return self._represent_JzOp(None, **options)
249
+
250
+ def _represent_JzOp(self, basis, **options):
251
+ return self._represent_base(basis, **options)
252
+
253
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
254
+ return JxOp(args[0]) - I*JyOp(args[0])
255
+
256
+
257
+ class JxOp(SpinOpBase, HermitianOperator):
258
+ """The Jx operator."""
259
+
260
+ _coord = 'x'
261
+
262
+ basis = 'Jx'
263
+
264
+ def _eval_commutator_JyOp(self, other):
265
+ return I*hbar*JzOp(self.name)
266
+
267
+ def _eval_commutator_JzOp(self, other):
268
+ return -I*hbar*JyOp(self.name)
269
+
270
+ def _apply_operator_JzKet(self, ket, **options):
271
+ jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
272
+ jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
273
+ return (jp + jm)/Integer(2)
274
+
275
+ def _apply_operator_JzKetCoupled(self, ket, **options):
276
+ jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
277
+ jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
278
+ return (jp + jm)/Integer(2)
279
+
280
+ def _represent_default_basis(self, **options):
281
+ return self._represent_JzOp(None, **options)
282
+
283
+ def _represent_JzOp(self, basis, **options):
284
+ jp = JplusOp(self.name)._represent_JzOp(basis, **options)
285
+ jm = JminusOp(self.name)._represent_JzOp(basis, **options)
286
+ return (jp + jm)/Integer(2)
287
+
288
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
289
+ return (JplusOp(args[0]) + JminusOp(args[0]))/2
290
+
291
+
292
+ class JyOp(SpinOpBase, HermitianOperator):
293
+ """The Jy operator."""
294
+
295
+ _coord = 'y'
296
+
297
+ basis = 'Jy'
298
+
299
+ def _eval_commutator_JzOp(self, other):
300
+ return I*hbar*JxOp(self.name)
301
+
302
+ def _eval_commutator_JxOp(self, other):
303
+ return -I*hbar*J2Op(self.name)
304
+
305
+ def _apply_operator_JzKet(self, ket, **options):
306
+ jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
307
+ jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
308
+ return (jp - jm)/(Integer(2)*I)
309
+
310
+ def _apply_operator_JzKetCoupled(self, ket, **options):
311
+ jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
312
+ jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
313
+ return (jp - jm)/(Integer(2)*I)
314
+
315
+ def _represent_default_basis(self, **options):
316
+ return self._represent_JzOp(None, **options)
317
+
318
+ def _represent_JzOp(self, basis, **options):
319
+ jp = JplusOp(self.name)._represent_JzOp(basis, **options)
320
+ jm = JminusOp(self.name)._represent_JzOp(basis, **options)
321
+ return (jp - jm)/(Integer(2)*I)
322
+
323
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
324
+ return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
325
+
326
+
327
+ class JzOp(SpinOpBase, HermitianOperator):
328
+ """The Jz operator."""
329
+
330
+ _coord = 'z'
331
+
332
+ basis = 'Jz'
333
+
334
+ def _eval_commutator_JxOp(self, other):
335
+ return I*hbar*JyOp(self.name)
336
+
337
+ def _eval_commutator_JyOp(self, other):
338
+ return -I*hbar*JxOp(self.name)
339
+
340
+ def _eval_commutator_JplusOp(self, other):
341
+ return hbar*JplusOp(self.name)
342
+
343
+ def _eval_commutator_JminusOp(self, other):
344
+ return -hbar*JminusOp(self.name)
345
+
346
+ def matrix_element(self, j, m, jp, mp):
347
+ result = hbar*mp
348
+ result *= KroneckerDelta(m, mp)
349
+ result *= KroneckerDelta(j, jp)
350
+ return result
351
+
352
+ def _represent_default_basis(self, **options):
353
+ return self._represent_JzOp(None, **options)
354
+
355
+ def _represent_JzOp(self, basis, **options):
356
+ return self._represent_base(basis, **options)
357
+
358
+
359
+ class J2Op(SpinOpBase, HermitianOperator):
360
+ """The J^2 operator."""
361
+
362
+ _coord = '2'
363
+
364
+ def _eval_commutator_JxOp(self, other):
365
+ return S.Zero
366
+
367
+ def _eval_commutator_JyOp(self, other):
368
+ return S.Zero
369
+
370
+ def _eval_commutator_JzOp(self, other):
371
+ return S.Zero
372
+
373
+ def _eval_commutator_JplusOp(self, other):
374
+ return S.Zero
375
+
376
+ def _eval_commutator_JminusOp(self, other):
377
+ return S.Zero
378
+
379
+ def _apply_operator_JxKet(self, ket, **options):
380
+ j = ket.j
381
+ return hbar**2*j*(j + 1)*ket
382
+
383
+ def _apply_operator_JxKetCoupled(self, ket, **options):
384
+ j = ket.j
385
+ return hbar**2*j*(j + 1)*ket
386
+
387
+ def _apply_operator_JyKet(self, ket, **options):
388
+ j = ket.j
389
+ return hbar**2*j*(j + 1)*ket
390
+
391
+ def _apply_operator_JyKetCoupled(self, ket, **options):
392
+ j = ket.j
393
+ return hbar**2*j*(j + 1)*ket
394
+
395
+ def _apply_operator_JzKet(self, ket, **options):
396
+ j = ket.j
397
+ return hbar**2*j*(j + 1)*ket
398
+
399
+ def _apply_operator_JzKetCoupled(self, ket, **options):
400
+ j = ket.j
401
+ return hbar**2*j*(j + 1)*ket
402
+
403
+ def matrix_element(self, j, m, jp, mp):
404
+ result = (hbar**2)*j*(j + 1)
405
+ result *= KroneckerDelta(m, mp)
406
+ result *= KroneckerDelta(j, jp)
407
+ return result
408
+
409
+ def _represent_default_basis(self, **options):
410
+ return self._represent_JzOp(None, **options)
411
+
412
+ def _represent_JzOp(self, basis, **options):
413
+ return self._represent_base(basis, **options)
414
+
415
+ def _print_contents_pretty(self, printer, *args):
416
+ a = prettyForm(str(self.name))
417
+ b = prettyForm('2')
418
+ return a**b
419
+
420
+ def _print_contents_latex(self, printer, *args):
421
+ return r'%s^2' % str(self.name)
422
+
423
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
424
+ return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
425
+
426
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
427
+ a = args[0]
428
+ return JzOp(a)**2 + \
429
+ S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
430
+
431
+
432
+ class Rotation(UnitaryOperator):
433
+ """Wigner D operator in terms of Euler angles.
434
+
435
+ Defines the rotation operator in terms of the Euler angles defined by
436
+ the z-y-z convention for a passive transformation. That is the coordinate
437
+ axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
438
+ this new coordinate system is rotated about the new y'-axis, giving new
439
+ x''-y''-z'' axes. Then this new coordinate system is rotated about the
440
+ z''-axis. Conventions follow those laid out in [1]_.
441
+
442
+ Parameters
443
+ ==========
444
+
445
+ alpha : Number, Symbol
446
+ First Euler Angle
447
+ beta : Number, Symbol
448
+ Second Euler angle
449
+ gamma : Number, Symbol
450
+ Third Euler angle
451
+
452
+ Examples
453
+ ========
454
+
455
+ A simple example rotation operator:
456
+
457
+ >>> from sympy import pi
458
+ >>> from sympy.physics.quantum.spin import Rotation
459
+ >>> Rotation(pi, 0, pi/2)
460
+ R(pi,0,pi/2)
461
+
462
+ With symbolic Euler angles and calculating the inverse rotation operator:
463
+
464
+ >>> from sympy import symbols
465
+ >>> a, b, c = symbols('a b c')
466
+ >>> Rotation(a, b, c)
467
+ R(a,b,c)
468
+ >>> Rotation(a, b, c).inverse()
469
+ R(-c,-b,-a)
470
+
471
+ See Also
472
+ ========
473
+
474
+ WignerD: Symbolic Wigner-D function
475
+ D: Wigner-D function
476
+ d: Wigner small-d function
477
+
478
+ References
479
+ ==========
480
+
481
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
482
+ """
483
+
484
+ @classmethod
485
+ def _eval_args(cls, args):
486
+ args = QExpr._eval_args(args)
487
+ if len(args) != 3:
488
+ raise ValueError('3 Euler angles required, got: %r' % args)
489
+ return args
490
+
491
+ @classmethod
492
+ def _eval_hilbert_space(cls, label):
493
+ # We consider all j values so our space is infinite.
494
+ return ComplexSpace(S.Infinity)
495
+
496
+ @property
497
+ def alpha(self):
498
+ return self.label[0]
499
+
500
+ @property
501
+ def beta(self):
502
+ return self.label[1]
503
+
504
+ @property
505
+ def gamma(self):
506
+ return self.label[2]
507
+
508
+ def _print_operator_name(self, printer, *args):
509
+ return 'R'
510
+
511
+ def _print_operator_name_pretty(self, printer, *args):
512
+ if printer._use_unicode:
513
+ return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
514
+ else:
515
+ return prettyForm("R ")
516
+
517
+ def _print_operator_name_latex(self, printer, *args):
518
+ return r'\mathcal{R}'
519
+
520
+ def _eval_inverse(self):
521
+ return Rotation(-self.gamma, -self.beta, -self.alpha)
522
+
523
+ @classmethod
524
+ def D(cls, j, m, mp, alpha, beta, gamma):
525
+ """Wigner D-function.
526
+
527
+ Returns an instance of the WignerD class corresponding to the Wigner-D
528
+ function specified by the parameters.
529
+
530
+ Parameters
531
+ ===========
532
+
533
+ j : Number
534
+ Total angular momentum
535
+ m : Number
536
+ Eigenvalue of angular momentum along axis after rotation
537
+ mp : Number
538
+ Eigenvalue of angular momentum along rotated axis
539
+ alpha : Number, Symbol
540
+ First Euler angle of rotation
541
+ beta : Number, Symbol
542
+ Second Euler angle of rotation
543
+ gamma : Number, Symbol
544
+ Third Euler angle of rotation
545
+
546
+ Examples
547
+ ========
548
+
549
+ Return the Wigner-D matrix element for a defined rotation, both
550
+ numerical and symbolic:
551
+
552
+ >>> from sympy.physics.quantum.spin import Rotation
553
+ >>> from sympy import pi, symbols
554
+ >>> alpha, beta, gamma = symbols('alpha beta gamma')
555
+ >>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
556
+ WignerD(1, 1, 0, pi, pi/2, -pi)
557
+
558
+ See Also
559
+ ========
560
+
561
+ WignerD: Symbolic Wigner-D function
562
+
563
+ """
564
+ return WignerD(j, m, mp, alpha, beta, gamma)
565
+
566
+ @classmethod
567
+ def d(cls, j, m, mp, beta):
568
+ """Wigner small-d function.
569
+
570
+ Returns an instance of the WignerD class corresponding to the Wigner-D
571
+ function specified by the parameters with the alpha and gamma angles
572
+ given as 0.
573
+
574
+ Parameters
575
+ ===========
576
+
577
+ j : Number
578
+ Total angular momentum
579
+ m : Number
580
+ Eigenvalue of angular momentum along axis after rotation
581
+ mp : Number
582
+ Eigenvalue of angular momentum along rotated axis
583
+ beta : Number, Symbol
584
+ Second Euler angle of rotation
585
+
586
+ Examples
587
+ ========
588
+
589
+ Return the Wigner-D matrix element for a defined rotation, both
590
+ numerical and symbolic:
591
+
592
+ >>> from sympy.physics.quantum.spin import Rotation
593
+ >>> from sympy import pi, symbols
594
+ >>> beta = symbols('beta')
595
+ >>> Rotation.d(1, 1, 0, pi/2)
596
+ WignerD(1, 1, 0, 0, pi/2, 0)
597
+
598
+ See Also
599
+ ========
600
+
601
+ WignerD: Symbolic Wigner-D function
602
+
603
+ """
604
+ return WignerD(j, m, mp, 0, beta, 0)
605
+
606
+ def matrix_element(self, j, m, jp, mp):
607
+ result = self.__class__.D(
608
+ jp, m, mp, self.alpha, self.beta, self.gamma
609
+ )
610
+ result *= KroneckerDelta(j, jp)
611
+ return result
612
+
613
+ def _represent_base(self, basis, **options):
614
+ j = sympify(options.get('j', S.Half))
615
+ # TODO: move evaluation up to represent function/implement elsewhere
616
+ evaluate = sympify(options.get('doit'))
617
+ size, mvals = m_values(j)
618
+ result = zeros(size, size)
619
+ for p in range(size):
620
+ for q in range(size):
621
+ me = self.matrix_element(j, mvals[p], j, mvals[q])
622
+ if evaluate:
623
+ result[p, q] = me.doit()
624
+ else:
625
+ result[p, q] = me
626
+ return result
627
+
628
+ def _represent_default_basis(self, **options):
629
+ return self._represent_JzOp(None, **options)
630
+
631
+ def _represent_JzOp(self, basis, **options):
632
+ return self._represent_base(basis, **options)
633
+
634
+ def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
635
+ a = self.alpha
636
+ b = self.beta
637
+ g = self.gamma
638
+ j = ket.j
639
+ m = ket.m
640
+ if j.is_number:
641
+ s = []
642
+ size = m_values(j)
643
+ sz = size[1]
644
+ for mp in sz:
645
+ r = Rotation.D(j, m, mp, a, b, g)
646
+ z = r.doit()
647
+ s.append(z*state(j, mp))
648
+ return Add(*s)
649
+ else:
650
+ if dummy:
651
+ mp = Dummy('mp')
652
+ else:
653
+ mp = symbols('mp')
654
+ return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
655
+
656
+ def _apply_operator_JxKet(self, ket, **options):
657
+ return self._apply_operator_uncoupled(JxKet, ket, **options)
658
+
659
+ def _apply_operator_JyKet(self, ket, **options):
660
+ return self._apply_operator_uncoupled(JyKet, ket, **options)
661
+
662
+ def _apply_operator_JzKet(self, ket, **options):
663
+ return self._apply_operator_uncoupled(JzKet, ket, **options)
664
+
665
+ def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
666
+ a = self.alpha
667
+ b = self.beta
668
+ g = self.gamma
669
+ j = ket.j
670
+ m = ket.m
671
+ jn = ket.jn
672
+ coupling = ket.coupling
673
+ if j.is_number:
674
+ s = []
675
+ size = m_values(j)
676
+ sz = size[1]
677
+ for mp in sz:
678
+ r = Rotation.D(j, m, mp, a, b, g)
679
+ z = r.doit()
680
+ s.append(z*state(j, mp, jn, coupling))
681
+ return Add(*s)
682
+ else:
683
+ if dummy:
684
+ mp = Dummy('mp')
685
+ else:
686
+ mp = symbols('mp')
687
+ return Sum(Rotation.D(j, m, mp, a, b, g)*state(
688
+ j, mp, jn, coupling), (mp, -j, j))
689
+
690
+ def _apply_operator_JxKetCoupled(self, ket, **options):
691
+ return self._apply_operator_coupled(JxKetCoupled, ket, **options)
692
+
693
+ def _apply_operator_JyKetCoupled(self, ket, **options):
694
+ return self._apply_operator_coupled(JyKetCoupled, ket, **options)
695
+
696
+ def _apply_operator_JzKetCoupled(self, ket, **options):
697
+ return self._apply_operator_coupled(JzKetCoupled, ket, **options)
698
+
699
+ class WignerD(Expr):
700
+ r"""Wigner-D function
701
+
702
+ The Wigner D-function gives the matrix elements of the rotation
703
+ operator in the jm-representation. For the Euler angles `\alpha`,
704
+ `\beta`, `\gamma`, the D-function is defined such that:
705
+
706
+ .. math ::
707
+ <j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
708
+
709
+ Where the rotation operator is as defined by the Rotation class [1]_.
710
+
711
+ The Wigner D-function defined in this way gives:
712
+
713
+ .. math ::
714
+ D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
715
+
716
+ Where d is the Wigner small-d function, which is given by Rotation.d.
717
+
718
+ The Wigner small-d function gives the component of the Wigner
719
+ D-function that is determined by the second Euler angle. That is the
720
+ Wigner D-function is:
721
+
722
+ .. math ::
723
+ D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
724
+
725
+ Where d is the small-d function. The Wigner D-function is given by
726
+ Rotation.D.
727
+
728
+ Note that to evaluate the D-function, the j, m and mp parameters must
729
+ be integer or half integer numbers.
730
+
731
+ Parameters
732
+ ==========
733
+
734
+ j : Number
735
+ Total angular momentum
736
+ m : Number
737
+ Eigenvalue of angular momentum along axis after rotation
738
+ mp : Number
739
+ Eigenvalue of angular momentum along rotated axis
740
+ alpha : Number, Symbol
741
+ First Euler angle of rotation
742
+ beta : Number, Symbol
743
+ Second Euler angle of rotation
744
+ gamma : Number, Symbol
745
+ Third Euler angle of rotation
746
+
747
+ Examples
748
+ ========
749
+
750
+ Evaluate the Wigner-D matrix elements of a simple rotation:
751
+
752
+ >>> from sympy.physics.quantum.spin import Rotation
753
+ >>> from sympy import pi
754
+ >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
755
+ >>> rot
756
+ WignerD(1, 1, 0, pi, pi/2, 0)
757
+ >>> rot.doit()
758
+ sqrt(2)/2
759
+
760
+ Evaluate the Wigner-d matrix elements of a simple rotation
761
+
762
+ >>> rot = Rotation.d(1, 1, 0, pi/2)
763
+ >>> rot
764
+ WignerD(1, 1, 0, 0, pi/2, 0)
765
+ >>> rot.doit()
766
+ -sqrt(2)/2
767
+
768
+ See Also
769
+ ========
770
+
771
+ Rotation: Rotation operator
772
+
773
+ References
774
+ ==========
775
+
776
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
777
+ """
778
+
779
+ is_commutative = True
780
+
781
+ def __new__(cls, *args, **hints):
782
+ if not len(args) == 6:
783
+ raise ValueError('6 parameters expected, got %s' % args)
784
+ args = sympify(args)
785
+ evaluate = hints.get('evaluate', False)
786
+ if evaluate:
787
+ return Expr.__new__(cls, *args)._eval_wignerd()
788
+ return Expr.__new__(cls, *args)
789
+
790
+ @property
791
+ def j(self):
792
+ return self.args[0]
793
+
794
+ @property
795
+ def m(self):
796
+ return self.args[1]
797
+
798
+ @property
799
+ def mp(self):
800
+ return self.args[2]
801
+
802
+ @property
803
+ def alpha(self):
804
+ return self.args[3]
805
+
806
+ @property
807
+ def beta(self):
808
+ return self.args[4]
809
+
810
+ @property
811
+ def gamma(self):
812
+ return self.args[5]
813
+
814
+ def _latex(self, printer, *args):
815
+ if self.alpha == 0 and self.gamma == 0:
816
+ return r'd^{%s}_{%s,%s}\left(%s\right)' % \
817
+ (
818
+ printer._print(self.j), printer._print(
819
+ self.m), printer._print(self.mp),
820
+ printer._print(self.beta) )
821
+ return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
822
+ (
823
+ printer._print(
824
+ self.j), printer._print(self.m), printer._print(self.mp),
825
+ printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
826
+
827
+ def _pretty(self, printer, *args):
828
+ top = printer._print(self.j)
829
+
830
+ bot = printer._print(self.m)
831
+ bot = prettyForm(*bot.right(','))
832
+ bot = prettyForm(*bot.right(printer._print(self.mp)))
833
+
834
+ pad = max(top.width(), bot.width())
835
+ top = prettyForm(*top.left(' '))
836
+ bot = prettyForm(*bot.left(' '))
837
+ if pad > top.width():
838
+ top = prettyForm(*top.right(' '*(pad - top.width())))
839
+ if pad > bot.width():
840
+ bot = prettyForm(*bot.right(' '*(pad - bot.width())))
841
+ if self.alpha == 0 and self.gamma == 0:
842
+ args = printer._print(self.beta)
843
+ s = stringPict('d' + ' '*pad)
844
+ else:
845
+ args = printer._print(self.alpha)
846
+ args = prettyForm(*args.right(','))
847
+ args = prettyForm(*args.right(printer._print(self.beta)))
848
+ args = prettyForm(*args.right(','))
849
+ args = prettyForm(*args.right(printer._print(self.gamma)))
850
+
851
+ s = stringPict('D' + ' '*pad)
852
+
853
+ args = prettyForm(*args.parens())
854
+ s = prettyForm(*s.above(top))
855
+ s = prettyForm(*s.below(bot))
856
+ s = prettyForm(*s.right(args))
857
+ return s
858
+
859
+ def doit(self, **hints):
860
+ hints['evaluate'] = True
861
+ return WignerD(*self.args, **hints)
862
+
863
+ def _eval_wignerd(self):
864
+ j = self.j
865
+ m = self.m
866
+ mp = self.mp
867
+ alpha = self.alpha
868
+ beta = self.beta
869
+ gamma = self.gamma
870
+ if alpha == 0 and beta == 0 and gamma == 0:
871
+ return KroneckerDelta(m, mp)
872
+ if not j.is_number:
873
+ raise ValueError(
874
+ 'j parameter must be numerical to evaluate, got %s' % j)
875
+ r = 0
876
+ if beta == pi/2:
877
+ # Varshalovich Equation (5), Section 4.16, page 113, setting
878
+ # alpha=gamma=0.
879
+ for k in range(2*j + 1):
880
+ if k > j + mp or k > j - m or k < mp - m:
881
+ continue
882
+ r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
883
+ r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
884
+ factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
885
+ else:
886
+ # Varshalovich Equation(5), Section 4.7.2, page 87, where we set
887
+ # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
888
+ # then we use the Eq. (1), Section 4.4. page 79, to simplify:
889
+ # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
890
+ # This happens to be almost the same as in Eq.(10), Section 4.16,
891
+ # except that we need to substitute -mp for mp.
892
+ size, mvals = m_values(j)
893
+ for mpp in mvals:
894
+ r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
895
+ Rotation.d(j, mpp, -mp, pi/2).doit()
896
+ # Empirical normalization factor so results match Varshalovich
897
+ # Tables 4.3-4.12
898
+ # Note that this exact normalization does not follow from the
899
+ # above equations
900
+ r = r*I**(2*j - m - mp)*(-1)**(2*m)
901
+ # Finally, simplify the whole expression
902
+ r = simplify(r)
903
+ r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
904
+ return r
905
+
906
+
907
+ Jx = JxOp('J')
908
+ Jy = JyOp('J')
909
+ Jz = JzOp('J')
910
+ J2 = J2Op('J')
911
+ Jplus = JplusOp('J')
912
+ Jminus = JminusOp('J')
913
+
914
+
915
+ #-----------------------------------------------------------------------------
916
+ # Spin States
917
+ #-----------------------------------------------------------------------------
918
+
919
+
920
+ class SpinState(State):
921
+ """Base class for angular momentum states."""
922
+
923
+ _label_separator = ','
924
+
925
+ def __new__(cls, j, m):
926
+ j = sympify(j)
927
+ m = sympify(m)
928
+ if j.is_number:
929
+ if 2*j != int(2*j):
930
+ raise ValueError(
931
+ 'j must be integer or half-integer, got: %s' % j)
932
+ if j < 0:
933
+ raise ValueError('j must be >= 0, got: %s' % j)
934
+ if m.is_number:
935
+ if 2*m != int(2*m):
936
+ raise ValueError(
937
+ 'm must be integer or half-integer, got: %s' % m)
938
+ if j.is_number and m.is_number:
939
+ if abs(m) > j:
940
+ raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
941
+ if int(j - m) != j - m:
942
+ raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
943
+ return State.__new__(cls, j, m)
944
+
945
+ @property
946
+ def j(self):
947
+ return self.label[0]
948
+
949
+ @property
950
+ def m(self):
951
+ return self.label[1]
952
+
953
+ @classmethod
954
+ def _eval_hilbert_space(cls, label):
955
+ return ComplexSpace(2*label[0] + 1)
956
+
957
+ def _represent_base(self, **options):
958
+ j = self.j
959
+ m = self.m
960
+ alpha = sympify(options.get('alpha', 0))
961
+ beta = sympify(options.get('beta', 0))
962
+ gamma = sympify(options.get('gamma', 0))
963
+ size, mvals = m_values(j)
964
+ result = zeros(size, 1)
965
+ # breaks finding angles on L930
966
+ for p, mval in enumerate(mvals):
967
+ if m.is_number:
968
+ result[p, 0] = Rotation.D(
969
+ self.j, mval, self.m, alpha, beta, gamma).doit()
970
+ else:
971
+ result[p, 0] = Rotation.D(self.j, mval,
972
+ self.m, alpha, beta, gamma)
973
+ return result
974
+
975
+ def _eval_rewrite_as_Jx(self, *args, **options):
976
+ if isinstance(self, Bra):
977
+ return self._rewrite_basis(Jx, JxBra, **options)
978
+ return self._rewrite_basis(Jx, JxKet, **options)
979
+
980
+ def _eval_rewrite_as_Jy(self, *args, **options):
981
+ if isinstance(self, Bra):
982
+ return self._rewrite_basis(Jy, JyBra, **options)
983
+ return self._rewrite_basis(Jy, JyKet, **options)
984
+
985
+ def _eval_rewrite_as_Jz(self, *args, **options):
986
+ if isinstance(self, Bra):
987
+ return self._rewrite_basis(Jz, JzBra, **options)
988
+ return self._rewrite_basis(Jz, JzKet, **options)
989
+
990
+ def _rewrite_basis(self, basis, evect, **options):
991
+ from sympy.physics.quantum.represent import represent
992
+ j = self.j
993
+ args = self.args[2:]
994
+ if j.is_number:
995
+ if isinstance(self, CoupledSpinState):
996
+ if j == int(j):
997
+ start = j**2
998
+ else:
999
+ start = (2*j - 1)*(2*j + 1)/4
1000
+ else:
1001
+ start = 0
1002
+ vect = represent(self, basis=basis, **options)
1003
+ result = Add(
1004
+ *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
1005
+ if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
1006
+ return uncouple(result)
1007
+ return result
1008
+ else:
1009
+ i = 0
1010
+ mi = symbols('mi')
1011
+ # make sure not to introduce a symbol already in the state
1012
+ while self.subs(mi, 0) != self:
1013
+ i += 1
1014
+ mi = symbols('mi%d' % i)
1015
+ break
1016
+ # TODO: better way to get angles of rotation
1017
+ if isinstance(self, CoupledSpinState):
1018
+ test_args = (0, mi, (0, 0))
1019
+ else:
1020
+ test_args = (0, mi)
1021
+ if isinstance(self, Ket):
1022
+ angles = represent(
1023
+ self.__class__(*test_args), basis=basis)[0].args[3:6]
1024
+ else:
1025
+ angles = represent(self.__class__(
1026
+ *test_args), basis=basis)[0].args[0].args[3:6]
1027
+ if angles == (0, 0, 0):
1028
+ return self
1029
+ else:
1030
+ state = evect(j, mi, *args)
1031
+ lt = Rotation.D(j, mi, self.m, *angles)
1032
+ return Sum(lt*state, (mi, -j, j))
1033
+
1034
+ def _eval_innerproduct_JxBra(self, bra, **hints):
1035
+ result = KroneckerDelta(self.j, bra.j)
1036
+ if bra.dual_class() is not self.__class__:
1037
+ result *= self._represent_JxOp(None)[bra.j - bra.m]
1038
+ else:
1039
+ result *= KroneckerDelta(
1040
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1041
+ return result
1042
+
1043
+ def _eval_innerproduct_JyBra(self, bra, **hints):
1044
+ result = KroneckerDelta(self.j, bra.j)
1045
+ if bra.dual_class() is not self.__class__:
1046
+ result *= self._represent_JyOp(None)[bra.j - bra.m]
1047
+ else:
1048
+ result *= KroneckerDelta(
1049
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1050
+ return result
1051
+
1052
+ def _eval_innerproduct_JzBra(self, bra, **hints):
1053
+ result = KroneckerDelta(self.j, bra.j)
1054
+ if bra.dual_class() is not self.__class__:
1055
+ result *= self._represent_JzOp(None)[bra.j - bra.m]
1056
+ else:
1057
+ result *= KroneckerDelta(
1058
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1059
+ return result
1060
+
1061
+ def _eval_trace(self, bra, **hints):
1062
+
1063
+ # One way to implement this method is to assume the basis set k is
1064
+ # passed.
1065
+ # Then we can apply the discrete form of Trace formula here
1066
+ # Tr(|i><j| ) = \Sum_k <k|i><j|k>
1067
+ #then we do qapply() on each each inner product and sum over them.
1068
+
1069
+ # OR
1070
+
1071
+ # Inner product of |i><j| = Trace(Outer Product).
1072
+ # we could just use this unless there are cases when this is not true
1073
+
1074
+ return (bra*self).doit()
1075
+
1076
+
1077
+ class JxKet(SpinState, Ket):
1078
+ """Eigenket of Jx.
1079
+
1080
+ See JzKet for the usage of spin eigenstates.
1081
+
1082
+ See Also
1083
+ ========
1084
+
1085
+ JzKet: Usage of spin states
1086
+
1087
+ """
1088
+
1089
+ @classmethod
1090
+ def dual_class(self):
1091
+ return JxBra
1092
+
1093
+ @classmethod
1094
+ def coupled_class(self):
1095
+ return JxKetCoupled
1096
+
1097
+ def _represent_default_basis(self, **options):
1098
+ return self._represent_JxOp(None, **options)
1099
+
1100
+ def _represent_JxOp(self, basis, **options):
1101
+ return self._represent_base(**options)
1102
+
1103
+ def _represent_JyOp(self, basis, **options):
1104
+ return self._represent_base(alpha=pi*Rational(3, 2), **options)
1105
+
1106
+ def _represent_JzOp(self, basis, **options):
1107
+ return self._represent_base(beta=pi/2, **options)
1108
+
1109
+
1110
+ class JxBra(SpinState, Bra):
1111
+ """Eigenbra of Jx.
1112
+
1113
+ See JzKet for the usage of spin eigenstates.
1114
+
1115
+ See Also
1116
+ ========
1117
+
1118
+ JzKet: Usage of spin states
1119
+
1120
+ """
1121
+
1122
+ @classmethod
1123
+ def dual_class(self):
1124
+ return JxKet
1125
+
1126
+ @classmethod
1127
+ def coupled_class(self):
1128
+ return JxBraCoupled
1129
+
1130
+
1131
+ class JyKet(SpinState, Ket):
1132
+ """Eigenket of Jy.
1133
+
1134
+ See JzKet for the usage of spin eigenstates.
1135
+
1136
+ See Also
1137
+ ========
1138
+
1139
+ JzKet: Usage of spin states
1140
+
1141
+ """
1142
+
1143
+ @classmethod
1144
+ def dual_class(self):
1145
+ return JyBra
1146
+
1147
+ @classmethod
1148
+ def coupled_class(self):
1149
+ return JyKetCoupled
1150
+
1151
+ def _represent_default_basis(self, **options):
1152
+ return self._represent_JyOp(None, **options)
1153
+
1154
+ def _represent_JxOp(self, basis, **options):
1155
+ return self._represent_base(gamma=pi/2, **options)
1156
+
1157
+ def _represent_JyOp(self, basis, **options):
1158
+ return self._represent_base(**options)
1159
+
1160
+ def _represent_JzOp(self, basis, **options):
1161
+ return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
1162
+
1163
+
1164
+ class JyBra(SpinState, Bra):
1165
+ """Eigenbra of Jy.
1166
+
1167
+ See JzKet for the usage of spin eigenstates.
1168
+
1169
+ See Also
1170
+ ========
1171
+
1172
+ JzKet: Usage of spin states
1173
+
1174
+ """
1175
+
1176
+ @classmethod
1177
+ def dual_class(self):
1178
+ return JyKet
1179
+
1180
+ @classmethod
1181
+ def coupled_class(self):
1182
+ return JyBraCoupled
1183
+
1184
+
1185
+ class JzKet(SpinState, Ket):
1186
+ """Eigenket of Jz.
1187
+
1188
+ Spin state which is an eigenstate of the Jz operator. Uncoupled states,
1189
+ that is states representing the interaction of multiple separate spin
1190
+ states, are defined as a tensor product of states.
1191
+
1192
+ Parameters
1193
+ ==========
1194
+
1195
+ j : Number, Symbol
1196
+ Total spin angular momentum
1197
+ m : Number, Symbol
1198
+ Eigenvalue of the Jz spin operator
1199
+
1200
+ Examples
1201
+ ========
1202
+
1203
+ *Normal States:*
1204
+
1205
+ Defining simple spin states, both numerical and symbolic:
1206
+
1207
+ >>> from sympy.physics.quantum.spin import JzKet, JxKet
1208
+ >>> from sympy import symbols
1209
+ >>> JzKet(1, 0)
1210
+ |1,0>
1211
+ >>> j, m = symbols('j m')
1212
+ >>> JzKet(j, m)
1213
+ |j,m>
1214
+
1215
+ Rewriting the JzKet in terms of eigenkets of the Jx operator:
1216
+ Note: that the resulting eigenstates are JxKet's
1217
+
1218
+ >>> JzKet(1,1).rewrite("Jx")
1219
+ |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
1220
+
1221
+ Get the vector representation of a state in terms of the basis elements
1222
+ of the Jx operator:
1223
+
1224
+ >>> from sympy.physics.quantum.represent import represent
1225
+ >>> from sympy.physics.quantum.spin import Jx, Jz
1226
+ >>> represent(JzKet(1,-1), basis=Jx)
1227
+ Matrix([
1228
+ [ 1/2],
1229
+ [sqrt(2)/2],
1230
+ [ 1/2]])
1231
+
1232
+ Apply innerproducts between states:
1233
+
1234
+ >>> from sympy.physics.quantum.innerproduct import InnerProduct
1235
+ >>> from sympy.physics.quantum.spin import JxBra
1236
+ >>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
1237
+ >>> i
1238
+ <1,1|1,1>
1239
+ >>> i.doit()
1240
+ 1/2
1241
+
1242
+ *Uncoupled States:*
1243
+
1244
+ Define an uncoupled state as a TensorProduct between two Jz eigenkets:
1245
+
1246
+ >>> from sympy.physics.quantum.tensorproduct import TensorProduct
1247
+ >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
1248
+ >>> TensorProduct(JzKet(1,0), JzKet(1,1))
1249
+ |1,0>x|1,1>
1250
+ >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
1251
+ |j1,m1>x|j2,m2>
1252
+
1253
+ A TensorProduct can be rewritten, in which case the eigenstates that make
1254
+ up the tensor product is rewritten to the new basis:
1255
+
1256
+ >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
1257
+ |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
1258
+
1259
+ The represent method for TensorProduct's gives the vector representation of
1260
+ the state. Note that the state in the product basis is the equivalent of the
1261
+ tensor product of the vector representation of the component eigenstates:
1262
+
1263
+ >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
1264
+ Matrix([
1265
+ [0],
1266
+ [0],
1267
+ [0],
1268
+ [1],
1269
+ [0],
1270
+ [0],
1271
+ [0],
1272
+ [0],
1273
+ [0]])
1274
+ >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
1275
+ Matrix([
1276
+ [ 1/2],
1277
+ [sqrt(2)/2],
1278
+ [ 1/2],
1279
+ [ 0],
1280
+ [ 0],
1281
+ [ 0],
1282
+ [ 0],
1283
+ [ 0],
1284
+ [ 0]])
1285
+
1286
+ See Also
1287
+ ========
1288
+
1289
+ JzKetCoupled: Coupled eigenstates
1290
+ sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
1291
+ uncouple: Uncouples states given coupling parameters
1292
+ couple: Couples uncoupled states
1293
+
1294
+ """
1295
+
1296
+ @classmethod
1297
+ def dual_class(self):
1298
+ return JzBra
1299
+
1300
+ @classmethod
1301
+ def coupled_class(self):
1302
+ return JzKetCoupled
1303
+
1304
+ def _represent_default_basis(self, **options):
1305
+ return self._represent_JzOp(None, **options)
1306
+
1307
+ def _represent_JxOp(self, basis, **options):
1308
+ return self._represent_base(beta=pi*Rational(3, 2), **options)
1309
+
1310
+ def _represent_JyOp(self, basis, **options):
1311
+ return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
1312
+
1313
+ def _represent_JzOp(self, basis, **options):
1314
+ return self._represent_base(**options)
1315
+
1316
+
1317
+ class JzBra(SpinState, Bra):
1318
+ """Eigenbra of Jz.
1319
+
1320
+ See the JzKet for the usage of spin eigenstates.
1321
+
1322
+ See Also
1323
+ ========
1324
+
1325
+ JzKet: Usage of spin states
1326
+
1327
+ """
1328
+
1329
+ @classmethod
1330
+ def dual_class(self):
1331
+ return JzKet
1332
+
1333
+ @classmethod
1334
+ def coupled_class(self):
1335
+ return JzBraCoupled
1336
+
1337
+
1338
+ # Method used primarily to create coupled_n and coupled_jn by __new__ in
1339
+ # CoupledSpinState
1340
+ # This same method is also used by the uncouple method, and is separated from
1341
+ # the CoupledSpinState class to maintain consistency in defining coupling
1342
+ def _build_coupled(jcoupling, length):
1343
+ n_list = [ [n + 1] for n in range(length) ]
1344
+ coupled_jn = []
1345
+ coupled_n = []
1346
+ for n1, n2, j_new in jcoupling:
1347
+ coupled_jn.append(j_new)
1348
+ coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
1349
+ n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
1350
+ n_list[n_sort[0] - 1] = n_sort
1351
+ return coupled_n, coupled_jn
1352
+
1353
+
1354
+ class CoupledSpinState(SpinState):
1355
+ """Base class for coupled angular momentum states."""
1356
+
1357
+ def __new__(cls, j, m, jn, *jcoupling):
1358
+ # Check j and m values using SpinState
1359
+ SpinState(j, m)
1360
+ # Build and check coupling scheme from arguments
1361
+ if len(jcoupling) == 0:
1362
+ # Use default coupling scheme
1363
+ jcoupling = []
1364
+ for n in range(2, len(jn)):
1365
+ jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
1366
+ jcoupling.append( (1, len(jn), j) )
1367
+ elif len(jcoupling) == 1:
1368
+ # Use specified coupling scheme
1369
+ jcoupling = jcoupling[0]
1370
+ else:
1371
+ raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
1372
+ # Check arguments have correct form
1373
+ if not isinstance(jn, (list, tuple, Tuple)):
1374
+ raise TypeError('jn must be Tuple, list or tuple, got %s' %
1375
+ jn.__class__.__name__)
1376
+ if not isinstance(jcoupling, (list, tuple, Tuple)):
1377
+ raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
1378
+ jcoupling.__class__.__name__)
1379
+ if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
1380
+ raise TypeError(
1381
+ 'All elements of jcoupling must be list, tuple or Tuple')
1382
+ if not len(jn) - 1 == len(jcoupling):
1383
+ raise ValueError('jcoupling must have length of %d, got %d' %
1384
+ (len(jn) - 1, len(jcoupling)))
1385
+ if not all(len(x) == 3 for x in jcoupling):
1386
+ raise ValueError('All elements of jcoupling must have length 3')
1387
+ # Build sympified args
1388
+ j = sympify(j)
1389
+ m = sympify(m)
1390
+ jn = Tuple( *[sympify(ji) for ji in jn] )
1391
+ jcoupling = Tuple( *[Tuple(sympify(
1392
+ n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
1393
+ # Check values in coupling scheme give physical state
1394
+ if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
1395
+ raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
1396
+ if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
1397
+ raise ValueError('Indices in jcoupling must be integers')
1398
+ if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
1399
+ raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
1400
+ if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
1401
+ raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
1402
+ coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
1403
+ jvals = list(jn)
1404
+ for n, (n1, n2) in enumerate(coupled_n):
1405
+ j1 = jvals[min(n1) - 1]
1406
+ j2 = jvals[min(n2) - 1]
1407
+ j3 = coupled_jn[n]
1408
+ if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
1409
+ if j1 + j2 < j3:
1410
+ raise ValueError('All couplings must have j1+j2 >= j3, '
1411
+ 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
1412
+ if abs(j1 - j2) > j3:
1413
+ raise ValueError("All couplings must have |j1+j2| <= j3, "
1414
+ "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
1415
+ if int(j1 + j2) == j1 + j2:
1416
+ pass
1417
+ jvals[min(n1 + n2) - 1] = j3
1418
+ if len(jcoupling) > 0 and jcoupling[-1][2] != j:
1419
+ raise ValueError('Last j value coupled together must be the final j of the state')
1420
+ # Return state
1421
+ return State.__new__(cls, j, m, jn, jcoupling)
1422
+
1423
+ def _print_label(self, printer, *args):
1424
+ label = [printer._print(self.j), printer._print(self.m)]
1425
+ for i, ji in enumerate(self.jn, start=1):
1426
+ label.append('j%d=%s' % (
1427
+ i, printer._print(ji)
1428
+ ))
1429
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1430
+ label.append('j(%s)=%s' % (
1431
+ ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
1432
+ ))
1433
+ return ','.join(label)
1434
+
1435
+ def _print_label_pretty(self, printer, *args):
1436
+ label = [self.j, self.m]
1437
+ for i, ji in enumerate(self.jn, start=1):
1438
+ symb = 'j%d' % i
1439
+ symb = pretty_symbol(symb)
1440
+ symb = prettyForm(symb + '=')
1441
+ item = prettyForm(*symb.right(printer._print(ji)))
1442
+ label.append(item)
1443
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1444
+ n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
1445
+ symb = prettyForm('j' + n + '=')
1446
+ item = prettyForm(*symb.right(printer._print(jn)))
1447
+ label.append(item)
1448
+ return self._print_sequence_pretty(
1449
+ label, self._label_separator, printer, *args
1450
+ )
1451
+
1452
+ def _print_label_latex(self, printer, *args):
1453
+ label = [
1454
+ printer._print(self.j, *args),
1455
+ printer._print(self.m, *args)
1456
+ ]
1457
+ for i, ji in enumerate(self.jn, start=1):
1458
+ label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
1459
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1460
+ n = ','.join(str(i) for i in sorted(n1 + n2))
1461
+ label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
1462
+ return self._label_separator.join(label)
1463
+
1464
+ @property
1465
+ def jn(self):
1466
+ return self.label[2]
1467
+
1468
+ @property
1469
+ def coupling(self):
1470
+ return self.label[3]
1471
+
1472
+ @property
1473
+ def coupled_jn(self):
1474
+ return _build_coupled(self.label[3], len(self.label[2]))[1]
1475
+
1476
+ @property
1477
+ def coupled_n(self):
1478
+ return _build_coupled(self.label[3], len(self.label[2]))[0]
1479
+
1480
+ @classmethod
1481
+ def _eval_hilbert_space(cls, label):
1482
+ j = Add(*label[2])
1483
+ if j.is_number:
1484
+ return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
1485
+ else:
1486
+ # TODO: Need hilbert space fix, see issue 5732
1487
+ # Desired behavior:
1488
+ #ji = symbols('ji')
1489
+ #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
1490
+ # Temporary fix:
1491
+ return ComplexSpace(2*j + 1)
1492
+
1493
+ def _represent_coupled_base(self, **options):
1494
+ evect = self.uncoupled_class()
1495
+ if not self.j.is_number:
1496
+ raise ValueError(
1497
+ 'State must not have symbolic j value to represent')
1498
+ if not self.hilbert_space.dimension.is_number:
1499
+ raise ValueError(
1500
+ 'State must not have symbolic j values to represent')
1501
+ result = zeros(self.hilbert_space.dimension, 1)
1502
+ if self.j == int(self.j):
1503
+ start = self.j**2
1504
+ else:
1505
+ start = (2*self.j - 1)*(1 + 2*self.j)/4
1506
+ result[start:start + 2*self.j + 1, 0] = evect(
1507
+ self.j, self.m)._represent_base(**options)
1508
+ return result
1509
+
1510
+ def _eval_rewrite_as_Jx(self, *args, **options):
1511
+ if isinstance(self, Bra):
1512
+ return self._rewrite_basis(Jx, JxBraCoupled, **options)
1513
+ return self._rewrite_basis(Jx, JxKetCoupled, **options)
1514
+
1515
+ def _eval_rewrite_as_Jy(self, *args, **options):
1516
+ if isinstance(self, Bra):
1517
+ return self._rewrite_basis(Jy, JyBraCoupled, **options)
1518
+ return self._rewrite_basis(Jy, JyKetCoupled, **options)
1519
+
1520
+ def _eval_rewrite_as_Jz(self, *args, **options):
1521
+ if isinstance(self, Bra):
1522
+ return self._rewrite_basis(Jz, JzBraCoupled, **options)
1523
+ return self._rewrite_basis(Jz, JzKetCoupled, **options)
1524
+
1525
+
1526
+ class JxKetCoupled(CoupledSpinState, Ket):
1527
+ """Coupled eigenket of Jx.
1528
+
1529
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1530
+
1531
+ See Also
1532
+ ========
1533
+
1534
+ JzKetCoupled: Usage of coupled spin states
1535
+
1536
+ """
1537
+
1538
+ @classmethod
1539
+ def dual_class(self):
1540
+ return JxBraCoupled
1541
+
1542
+ @classmethod
1543
+ def uncoupled_class(self):
1544
+ return JxKet
1545
+
1546
+ def _represent_default_basis(self, **options):
1547
+ return self._represent_JzOp(None, **options)
1548
+
1549
+ def _represent_JxOp(self, basis, **options):
1550
+ return self._represent_coupled_base(**options)
1551
+
1552
+ def _represent_JyOp(self, basis, **options):
1553
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
1554
+
1555
+ def _represent_JzOp(self, basis, **options):
1556
+ return self._represent_coupled_base(beta=pi/2, **options)
1557
+
1558
+
1559
+ class JxBraCoupled(CoupledSpinState, Bra):
1560
+ """Coupled eigenbra of Jx.
1561
+
1562
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1563
+
1564
+ See Also
1565
+ ========
1566
+
1567
+ JzKetCoupled: Usage of coupled spin states
1568
+
1569
+ """
1570
+
1571
+ @classmethod
1572
+ def dual_class(self):
1573
+ return JxKetCoupled
1574
+
1575
+ @classmethod
1576
+ def uncoupled_class(self):
1577
+ return JxBra
1578
+
1579
+
1580
+ class JyKetCoupled(CoupledSpinState, Ket):
1581
+ """Coupled eigenket of Jy.
1582
+
1583
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1584
+
1585
+ See Also
1586
+ ========
1587
+
1588
+ JzKetCoupled: Usage of coupled spin states
1589
+
1590
+ """
1591
+
1592
+ @classmethod
1593
+ def dual_class(self):
1594
+ return JyBraCoupled
1595
+
1596
+ @classmethod
1597
+ def uncoupled_class(self):
1598
+ return JyKet
1599
+
1600
+ def _represent_default_basis(self, **options):
1601
+ return self._represent_JzOp(None, **options)
1602
+
1603
+ def _represent_JxOp(self, basis, **options):
1604
+ return self._represent_coupled_base(gamma=pi/2, **options)
1605
+
1606
+ def _represent_JyOp(self, basis, **options):
1607
+ return self._represent_coupled_base(**options)
1608
+
1609
+ def _represent_JzOp(self, basis, **options):
1610
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
1611
+
1612
+
1613
+ class JyBraCoupled(CoupledSpinState, Bra):
1614
+ """Coupled eigenbra of Jy.
1615
+
1616
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1617
+
1618
+ See Also
1619
+ ========
1620
+
1621
+ JzKetCoupled: Usage of coupled spin states
1622
+
1623
+ """
1624
+
1625
+ @classmethod
1626
+ def dual_class(self):
1627
+ return JyKetCoupled
1628
+
1629
+ @classmethod
1630
+ def uncoupled_class(self):
1631
+ return JyBra
1632
+
1633
+
1634
+ class JzKetCoupled(CoupledSpinState, Ket):
1635
+ r"""Coupled eigenket of Jz
1636
+
1637
+ Spin state that is an eigenket of Jz which represents the coupling of
1638
+ separate spin spaces.
1639
+
1640
+ The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
1641
+ ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
1642
+ are the total angular momentum quantum numbers, as used for normal states
1643
+ (e.g. JzKet).
1644
+
1645
+ The other required parameter in ``jn``, which is a tuple defining the `j_n`
1646
+ angular momentum quantum numbers of the product spaces. So for example, if
1647
+ a state represented the coupling of the product basis state
1648
+ `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
1649
+ for this state would be ``(j1,j2)``.
1650
+
1651
+ The final option is ``jcoupling``, which is used to define how the spaces
1652
+ specified by ``jn`` are coupled, which includes both the order these spaces
1653
+ are coupled together and the quantum numbers that arise from these
1654
+ couplings. The ``jcoupling`` parameter itself is a list of lists, such that
1655
+ each of the sublists defines a single coupling between the spin spaces. If
1656
+ there are N coupled angular momentum spaces, that is ``jn`` has N elements,
1657
+ then there must be N-1 sublists. Each of these sublists making up the
1658
+ ``jcoupling`` parameter have length 3. The first two elements are the
1659
+ indices of the product spaces that are considered to be coupled together.
1660
+ For example, if we want to couple `j_1` and `j_4`, the indices would be 1
1661
+ and 4. If a state has already been coupled, it is referenced by the
1662
+ smallest index that is coupled, so if `j_2` and `j_4` has already been
1663
+ coupled to some `j_{24}`, then this value can be coupled by referencing it
1664
+ with index 2. The final element of the sublist is the quantum number of the
1665
+ coupled state. So putting everything together, into a valid sublist for
1666
+ ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
1667
+ with quantum number `j_{12}` with the value ``j12``, the sublist would be
1668
+ ``(1,2,j12)``, N-1 of these sublists are used in the list for
1669
+ ``jcoupling``.
1670
+
1671
+ Note the ``jcoupling`` parameter is optional, if it is not specified, the
1672
+ default coupling is taken. This default value is to coupled the spaces in
1673
+ order and take the quantum number of the coupling to be the maximum value.
1674
+ For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
1675
+ default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
1676
+ `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
1677
+ `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
1678
+ correspond to this is:
1679
+
1680
+ ``((1,2,j1+j2),(1,3,j1+j2+j3))``
1681
+
1682
+ Parameters
1683
+ ==========
1684
+
1685
+ args : tuple
1686
+ The arguments that must be passed are ``j``, ``m``, ``jn``, and
1687
+ ``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
1688
+ value is the eigenvalue of the Jz spin operator. The ``jn`` list are
1689
+ the j values of argular momentum spaces coupled together. The
1690
+ ``jcoupling`` parameter is an optional parameter defining how the spaces
1691
+ are coupled together. See the above description for how these coupling
1692
+ parameters are defined.
1693
+
1694
+ Examples
1695
+ ========
1696
+
1697
+ Defining simple spin states, both numerical and symbolic:
1698
+
1699
+ >>> from sympy.physics.quantum.spin import JzKetCoupled
1700
+ >>> from sympy import symbols
1701
+ >>> JzKetCoupled(1, 0, (1, 1))
1702
+ |1,0,j1=1,j2=1>
1703
+ >>> j, m, j1, j2 = symbols('j m j1 j2')
1704
+ >>> JzKetCoupled(j, m, (j1, j2))
1705
+ |j,m,j1=j1,j2=j2>
1706
+
1707
+ Defining coupled spin states for more than 2 coupled spaces with various
1708
+ coupling parameters:
1709
+
1710
+ >>> JzKetCoupled(2, 1, (1, 1, 1))
1711
+ |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
1712
+ >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
1713
+ |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
1714
+ >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
1715
+ |2,1,j1=1,j2=1,j3=1,j(2,3)=1>
1716
+
1717
+ Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
1718
+ Note: that the resulting eigenstates are JxKetCoupled
1719
+
1720
+ >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
1721
+ |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
1722
+
1723
+ The rewrite method can be used to convert a coupled state to an uncoupled
1724
+ state. This is done by passing coupled=False to the rewrite function:
1725
+
1726
+ >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
1727
+ -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
1728
+
1729
+ Get the vector representation of a state in terms of the basis elements
1730
+ of the Jx operator:
1731
+
1732
+ >>> from sympy.physics.quantum.represent import represent
1733
+ >>> from sympy.physics.quantum.spin import Jx
1734
+ >>> from sympy import S
1735
+ >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
1736
+ Matrix([
1737
+ [ 0],
1738
+ [ 1/2],
1739
+ [sqrt(2)/2],
1740
+ [ 1/2]])
1741
+
1742
+ See Also
1743
+ ========
1744
+
1745
+ JzKet: Normal spin eigenstates
1746
+ uncouple: Uncoupling of coupling spin states
1747
+ couple: Coupling of uncoupled spin states
1748
+
1749
+ """
1750
+
1751
+ @classmethod
1752
+ def dual_class(self):
1753
+ return JzBraCoupled
1754
+
1755
+ @classmethod
1756
+ def uncoupled_class(self):
1757
+ return JzKet
1758
+
1759
+ def _represent_default_basis(self, **options):
1760
+ return self._represent_JzOp(None, **options)
1761
+
1762
+ def _represent_JxOp(self, basis, **options):
1763
+ return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
1764
+
1765
+ def _represent_JyOp(self, basis, **options):
1766
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
1767
+
1768
+ def _represent_JzOp(self, basis, **options):
1769
+ return self._represent_coupled_base(**options)
1770
+
1771
+
1772
+ class JzBraCoupled(CoupledSpinState, Bra):
1773
+ """Coupled eigenbra of Jz.
1774
+
1775
+ See the JzKetCoupled for the usage of coupled spin eigenstates.
1776
+
1777
+ See Also
1778
+ ========
1779
+
1780
+ JzKetCoupled: Usage of coupled spin states
1781
+
1782
+ """
1783
+
1784
+ @classmethod
1785
+ def dual_class(self):
1786
+ return JzKetCoupled
1787
+
1788
+ @classmethod
1789
+ def uncoupled_class(self):
1790
+ return JzBra
1791
+
1792
+ #-----------------------------------------------------------------------------
1793
+ # Coupling/uncoupling
1794
+ #-----------------------------------------------------------------------------
1795
+
1796
+
1797
+ def couple(expr, jcoupling_list=None):
1798
+ """ Couple a tensor product of spin states
1799
+
1800
+ This function can be used to couple an uncoupled tensor product of spin
1801
+ states. All of the eigenstates to be coupled must be of the same class. It
1802
+ will return a linear combination of eigenstates that are subclasses of
1803
+ CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
1804
+ coefficients.
1805
+
1806
+ Parameters
1807
+ ==========
1808
+
1809
+ expr : Expr
1810
+ An expression involving TensorProducts of spin states to be coupled.
1811
+ Each state must be a subclass of SpinState and they all must be the
1812
+ same class.
1813
+
1814
+ jcoupling_list : list or tuple
1815
+ Elements of this list are sub-lists of length 2 specifying the order of
1816
+ the coupling of the spin spaces. The length of this must be N-1, where N
1817
+ is the number of states in the tensor product to be coupled. The
1818
+ elements of this sublist are the same as the first two elements of each
1819
+ sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
1820
+ parameter is not specified, the default value is taken, which couples
1821
+ the first and second product basis spaces, then couples this new coupled
1822
+ space to the third product space, etc
1823
+
1824
+ Examples
1825
+ ========
1826
+
1827
+ Couple a tensor product of numerical states for two spaces:
1828
+
1829
+ >>> from sympy.physics.quantum.spin import JzKet, couple
1830
+ >>> from sympy.physics.quantum.tensorproduct import TensorProduct
1831
+ >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
1832
+ -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
1833
+
1834
+
1835
+ Numerical coupling of three spaces using the default coupling method, i.e.
1836
+ first and second spaces couple, then this couples to the third space:
1837
+
1838
+ >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
1839
+ sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
1840
+
1841
+ Perform this same coupling, but we define the coupling to first couple
1842
+ the first and third spaces:
1843
+
1844
+ >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
1845
+ sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
1846
+
1847
+ Couple a tensor product of symbolic states:
1848
+
1849
+ >>> from sympy import symbols
1850
+ >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
1851
+ >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
1852
+ Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
1853
+
1854
+ """
1855
+ a = expr.atoms(TensorProduct)
1856
+ for tp in a:
1857
+ # Allow other tensor products to be in expression
1858
+ if not all(isinstance(state, SpinState) for state in tp.args):
1859
+ continue
1860
+ # If tensor product has all spin states, raise error for invalid tensor product state
1861
+ if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
1862
+ raise TypeError('All states must be the same basis')
1863
+ expr = expr.subs(tp, _couple(tp, jcoupling_list))
1864
+ return expr
1865
+
1866
+
1867
+ def _couple(tp, jcoupling_list):
1868
+ states = tp.args
1869
+ coupled_evect = states[0].coupled_class()
1870
+
1871
+ # Define default coupling if none is specified
1872
+ if jcoupling_list is None:
1873
+ jcoupling_list = []
1874
+ for n in range(1, len(states)):
1875
+ jcoupling_list.append( (1, n + 1) )
1876
+
1877
+ # Check jcoupling_list valid
1878
+ if not len(jcoupling_list) == len(states) - 1:
1879
+ raise TypeError('jcoupling_list must be length %d, got %d' %
1880
+ (len(states) - 1, len(jcoupling_list)))
1881
+ if not all( len(coupling) == 2 for coupling in jcoupling_list):
1882
+ raise ValueError('Each coupling must define 2 spaces')
1883
+ if any(n1 == n2 for n1, n2 in jcoupling_list):
1884
+ raise ValueError('Spin spaces cannot couple to themselves')
1885
+ if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
1886
+ j_test = [0]*len(states)
1887
+ for n1, n2 in jcoupling_list:
1888
+ if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
1889
+ raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
1890
+ j_test[max(n1, n2) - 1] = -1
1891
+
1892
+ # j values of states to be coupled together
1893
+ jn = [state.j for state in states]
1894
+ mn = [state.m for state in states]
1895
+
1896
+ # Create coupling_list, which defines all the couplings between all
1897
+ # the spaces from jcoupling_list
1898
+ coupling_list = []
1899
+ n_list = [ [i + 1] for i in range(len(states)) ]
1900
+ for j_coupling in jcoupling_list:
1901
+ # Least n for all j_n which is coupled as first and second spaces
1902
+ n1, n2 = j_coupling
1903
+ # List of all n's coupled in first and second spaces
1904
+ j1_n = list(n_list[n1 - 1])
1905
+ j2_n = list(n_list[n2 - 1])
1906
+ coupling_list.append( (j1_n, j2_n) )
1907
+ # Set new j_n to be coupling of all j_n in both first and second spaces
1908
+ n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
1909
+
1910
+ if all(state.j.is_number and state.m.is_number for state in states):
1911
+ # Numerical coupling
1912
+ # Iterate over difference between maximum possible j value of each coupling and the actual value
1913
+ diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
1914
+ coupling[1] ] ) for coupling in coupling_list ]
1915
+ result = []
1916
+ for diff in range(diff_max[-1] + 1):
1917
+ # Determine available configurations
1918
+ n = len(coupling_list)
1919
+ tot = binomial(diff + n - 1, diff)
1920
+
1921
+ for config_num in range(tot):
1922
+ diff_list = _confignum_to_difflist(config_num, diff, n)
1923
+
1924
+ # Skip the configuration if non-physical
1925
+ # This is a lazy check for physical states given the loose restrictions of diff_max
1926
+ if any(d > m for d, m in zip(diff_list, diff_max)):
1927
+ continue
1928
+
1929
+ # Determine term
1930
+ cg_terms = []
1931
+ coupled_j = list(jn)
1932
+ jcoupling = []
1933
+ for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
1934
+ j1 = coupled_j[ min(j1_n) - 1 ]
1935
+ j2 = coupled_j[ min(j2_n) - 1 ]
1936
+ j3 = j1 + j2 - coupling_diff
1937
+ coupled_j[ min(j1_n + j2_n) - 1 ] = j3
1938
+ m1 = Add( *[ mn[x - 1] for x in j1_n] )
1939
+ m2 = Add( *[ mn[x - 1] for x in j2_n] )
1940
+ m3 = m1 + m2
1941
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
1942
+ jcoupling.append( (min(j1_n), min(j2_n), j3) )
1943
+ # Better checks that state is physical
1944
+ if any(abs(term[5]) > term[4] for term in cg_terms):
1945
+ continue
1946
+ if any(term[0] + term[2] < term[4] for term in cg_terms):
1947
+ continue
1948
+ if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
1949
+ continue
1950
+ coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
1951
+ state = coupled_evect(j3, m3, jn, jcoupling)
1952
+ result.append(coeff*state)
1953
+ return Add(*result)
1954
+ else:
1955
+ # Symbolic coupling
1956
+ cg_terms = []
1957
+ jcoupling = []
1958
+ sum_terms = []
1959
+ coupled_j = list(jn)
1960
+ for j1_n, j2_n in coupling_list:
1961
+ j1 = coupled_j[ min(j1_n) - 1 ]
1962
+ j2 = coupled_j[ min(j2_n) - 1 ]
1963
+ if len(j1_n + j2_n) == len(states):
1964
+ j3 = symbols('j')
1965
+ else:
1966
+ j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
1967
+ j3 = symbols(j3_name)
1968
+ coupled_j[ min(j1_n + j2_n) - 1 ] = j3
1969
+ m1 = Add( *[ mn[x - 1] for x in j1_n] )
1970
+ m2 = Add( *[ mn[x - 1] for x in j2_n] )
1971
+ m3 = m1 + m2
1972
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
1973
+ jcoupling.append( (min(j1_n), min(j2_n), j3) )
1974
+ sum_terms.append((j3, m3, j1 + j2))
1975
+ coeff = Mul( *[ CG(*term) for term in cg_terms] )
1976
+ state = coupled_evect(j3, m3, jn, jcoupling)
1977
+ return Sum(coeff*state, *sum_terms)
1978
+
1979
+
1980
+ def uncouple(expr, jn=None, jcoupling_list=None):
1981
+ """ Uncouple a coupled spin state
1982
+
1983
+ Gives the uncoupled representation of a coupled spin state. Arguments must
1984
+ be either a spin state that is a subclass of CoupledSpinState or a spin
1985
+ state that is a subclass of SpinState and an array giving the j values
1986
+ of the spaces that are to be coupled
1987
+
1988
+ Parameters
1989
+ ==========
1990
+
1991
+ expr : Expr
1992
+ The expression containing states that are to be coupled. If the states
1993
+ are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
1994
+ must be defined. If the states are a subclass of CoupledSpinState,
1995
+ ``jn`` and ``jcoupling`` will be taken from the state.
1996
+
1997
+ jn : list or tuple
1998
+ The list of the j-values that are coupled. If state is a
1999
+ CoupledSpinState, this parameter is ignored. This must be defined if
2000
+ state is not a subclass of CoupledSpinState. The syntax of this
2001
+ parameter is the same as the ``jn`` parameter of JzKetCoupled.
2002
+
2003
+ jcoupling_list : list or tuple
2004
+ The list defining how the j-values are coupled together. If state is a
2005
+ CoupledSpinState, this parameter is ignored. This must be defined if
2006
+ state is not a subclass of CoupledSpinState. The syntax of this
2007
+ parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
2008
+
2009
+ Examples
2010
+ ========
2011
+
2012
+ Uncouple a numerical state using a CoupledSpinState state:
2013
+
2014
+ >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
2015
+ >>> from sympy import S
2016
+ >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
2017
+ sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
2018
+
2019
+ Perform the same calculation using a SpinState state:
2020
+
2021
+ >>> from sympy.physics.quantum.spin import JzKet
2022
+ >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
2023
+ sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
2024
+
2025
+ Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
2026
+
2027
+ >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
2028
+ |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
2029
+
2030
+ Perform the same calculation using a SpinState state:
2031
+
2032
+ >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
2033
+ |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
2034
+
2035
+ Uncouple a symbolic state using a CoupledSpinState state:
2036
+
2037
+ >>> from sympy import symbols
2038
+ >>> j,m,j1,j2 = symbols('j m j1 j2')
2039
+ >>> uncouple(JzKetCoupled(j, m, (j1, j2)))
2040
+ Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
2041
+
2042
+ Perform the same calculation using a SpinState state
2043
+
2044
+ >>> uncouple(JzKet(j, m), (j1, j2))
2045
+ Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
2046
+
2047
+ """
2048
+ a = expr.atoms(SpinState)
2049
+ for state in a:
2050
+ expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
2051
+ return expr
2052
+
2053
+
2054
+ def _uncouple(state, jn, jcoupling_list):
2055
+ if isinstance(state, CoupledSpinState):
2056
+ jn = state.jn
2057
+ coupled_n = state.coupled_n
2058
+ coupled_jn = state.coupled_jn
2059
+ evect = state.uncoupled_class()
2060
+ elif isinstance(state, SpinState):
2061
+ if jn is None:
2062
+ raise ValueError("Must specify j-values for coupled state")
2063
+ if not isinstance(jn, (list, tuple)):
2064
+ raise TypeError("jn must be list or tuple")
2065
+ if jcoupling_list is None:
2066
+ # Use default
2067
+ jcoupling_list = []
2068
+ for i in range(1, len(jn)):
2069
+ jcoupling_list.append(
2070
+ (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
2071
+ if not isinstance(jcoupling_list, (list, tuple)):
2072
+ raise TypeError("jcoupling must be a list or tuple")
2073
+ if not len(jcoupling_list) == len(jn) - 1:
2074
+ raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
2075
+ coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
2076
+ evect = state.__class__
2077
+ else:
2078
+ raise TypeError("state must be a spin state")
2079
+ j = state.j
2080
+ m = state.m
2081
+ coupling_list = []
2082
+ j_list = list(jn)
2083
+
2084
+ # Create coupling, which defines all the couplings between all the spaces
2085
+ for j3, (n1, n2) in zip(coupled_jn, coupled_n):
2086
+ # j's which are coupled as first and second spaces
2087
+ j1 = j_list[n1[0] - 1]
2088
+ j2 = j_list[n2[0] - 1]
2089
+ # Build coupling list
2090
+ coupling_list.append( (n1, n2, j1, j2, j3) )
2091
+ # Set new value in j_list
2092
+ j_list[min(n1 + n2) - 1] = j3
2093
+
2094
+ if j.is_number and m.is_number:
2095
+ diff_max = [ 2*x for x in jn ]
2096
+ diff = Add(*jn) - m
2097
+
2098
+ n = len(jn)
2099
+ tot = binomial(diff + n - 1, diff)
2100
+
2101
+ result = []
2102
+ for config_num in range(tot):
2103
+ diff_list = _confignum_to_difflist(config_num, diff, n)
2104
+ if any(d > p for d, p in zip(diff_list, diff_max)):
2105
+ continue
2106
+
2107
+ cg_terms = []
2108
+ for coupling in coupling_list:
2109
+ j1_n, j2_n, j1, j2, j3 = coupling
2110
+ m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
2111
+ m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
2112
+ m3 = m1 + m2
2113
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
2114
+ coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
2115
+ state = TensorProduct(
2116
+ *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
2117
+ result.append(coeff*state)
2118
+ return Add(*result)
2119
+ else:
2120
+ # Symbolic coupling
2121
+ m_str = "m1:%d" % (len(jn) + 1)
2122
+ mvals = symbols(m_str)
2123
+ cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
2124
+ j2, Add(*[mvals[n - 1] for n in j2_n]),
2125
+ j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
2126
+ cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
2127
+ j2, Add(*[mvals[n - 1] for n in j2_n]),
2128
+ j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
2129
+ cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
2130
+ sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
2131
+ state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
2132
+ return Sum(cg_coeff*state, *sum_terms)
2133
+
2134
+
2135
+ def _confignum_to_difflist(config_num, diff, list_len):
2136
+ # Determines configuration of diffs into list_len number of slots
2137
+ diff_list = []
2138
+ for n in range(list_len):
2139
+ prev_diff = diff
2140
+ # Number of spots after current one
2141
+ rem_spots = list_len - n - 1
2142
+ # Number of configurations of distributing diff among the remaining spots
2143
+ rem_configs = binomial(diff + rem_spots - 1, diff)
2144
+ while config_num >= rem_configs:
2145
+ config_num -= rem_configs
2146
+ diff -= 1
2147
+ rem_configs = binomial(diff + rem_spots - 1, diff)
2148
+ diff_list.append(prev_diff - diff)
2149
+ return diff_list
venv/lib/python3.10/site-packages/sympy/physics/quantum/state.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dirac notation for states."""
2
+
3
+ from sympy.core.cache import cacheit
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.function import Function
7
+ from sympy.core.numbers import oo, equal_valued
8
+ from sympy.core.singleton import S
9
+ from sympy.functions.elementary.complexes import conjugate
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.integrals.integrals import integrate
12
+ from sympy.printing.pretty.stringpict import stringPict
13
+ from sympy.physics.quantum.qexpr import QExpr, dispatch_method
14
+
15
+ __all__ = [
16
+ 'KetBase',
17
+ 'BraBase',
18
+ 'StateBase',
19
+ 'State',
20
+ 'Ket',
21
+ 'Bra',
22
+ 'TimeDepState',
23
+ 'TimeDepBra',
24
+ 'TimeDepKet',
25
+ 'OrthogonalKet',
26
+ 'OrthogonalBra',
27
+ 'OrthogonalState',
28
+ 'Wavefunction'
29
+ ]
30
+
31
+
32
+ #-----------------------------------------------------------------------------
33
+ # States, bras and kets.
34
+ #-----------------------------------------------------------------------------
35
+
36
+ # ASCII brackets
37
+ _lbracket = "<"
38
+ _rbracket = ">"
39
+ _straight_bracket = "|"
40
+
41
+
42
+ # Unicode brackets
43
+ # MATHEMATICAL ANGLE BRACKETS
44
+ _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
45
+ _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
46
+ # LIGHT VERTICAL BAR
47
+ _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
48
+
49
+ # Other options for unicode printing of <, > and | for Dirac notation.
50
+
51
+ # LEFT-POINTING ANGLE BRACKET
52
+ # _lbracket = "\u2329"
53
+ # _rbracket = "\u232A"
54
+
55
+ # LEFT ANGLE BRACKET
56
+ # _lbracket = "\u3008"
57
+ # _rbracket = "\u3009"
58
+
59
+ # VERTICAL LINE
60
+ # _straight_bracket = "\u007C"
61
+
62
+
63
+ class StateBase(QExpr):
64
+ """Abstract base class for general abstract states in quantum mechanics.
65
+
66
+ All other state classes defined will need to inherit from this class. It
67
+ carries the basic structure for all other states such as dual, _eval_adjoint
68
+ and label.
69
+
70
+ This is an abstract base class and you should not instantiate it directly,
71
+ instead use State.
72
+ """
73
+
74
+ @classmethod
75
+ def _operators_to_state(self, ops, **options):
76
+ """ Returns the eigenstate instance for the passed operators.
77
+
78
+ This method should be overridden in subclasses. It will handle being
79
+ passed either an Operator instance or set of Operator instances. It
80
+ should return the corresponding state INSTANCE or simply raise a
81
+ NotImplementedError. See cartesian.py for an example.
82
+ """
83
+
84
+ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
85
+
86
+ def _state_to_operators(self, op_classes, **options):
87
+ """ Returns the operators which this state instance is an eigenstate
88
+ of.
89
+
90
+ This method should be overridden in subclasses. It will be called on
91
+ state instances and be passed the operator classes that we wish to make
92
+ into instances. The state instance will then transform the classes
93
+ appropriately, or raise a NotImplementedError if it cannot return
94
+ operator instances. See cartesian.py for examples,
95
+ """
96
+
97
+ raise NotImplementedError(
98
+ "Cannot map this state to operators. Method not implemented!")
99
+
100
+ @property
101
+ def operators(self):
102
+ """Return the operator(s) that this state is an eigenstate of"""
103
+ from .operatorset import state_to_operators # import internally to avoid circular import errors
104
+ return state_to_operators(self)
105
+
106
+ def _enumerate_state(self, num_states, **options):
107
+ raise NotImplementedError("Cannot enumerate this state!")
108
+
109
+ def _represent_default_basis(self, **options):
110
+ return self._represent(basis=self.operators)
111
+
112
+ #-------------------------------------------------------------------------
113
+ # Dagger/dual
114
+ #-------------------------------------------------------------------------
115
+
116
+ @property
117
+ def dual(self):
118
+ """Return the dual state of this one."""
119
+ return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
120
+
121
+ @classmethod
122
+ def dual_class(self):
123
+ """Return the class used to construct the dual."""
124
+ raise NotImplementedError(
125
+ 'dual_class must be implemented in a subclass'
126
+ )
127
+
128
+ def _eval_adjoint(self):
129
+ """Compute the dagger of this state using the dual."""
130
+ return self.dual
131
+
132
+ #-------------------------------------------------------------------------
133
+ # Printing
134
+ #-------------------------------------------------------------------------
135
+
136
+ def _pretty_brackets(self, height, use_unicode=True):
137
+ # Return pretty printed brackets for the state
138
+ # Ideally, this could be done by pform.parens but it does not support the angled < and >
139
+
140
+ # Setup for unicode vs ascii
141
+ if use_unicode:
142
+ lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
143
+ slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
144
+ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
145
+ '\N{BOX DRAWINGS LIGHT VERTICAL}'
146
+ else:
147
+ lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
148
+ slash, bslash, vert = '/', '\\', '|'
149
+
150
+ # If height is 1, just return brackets
151
+ if height == 1:
152
+ return stringPict(lbracket), stringPict(rbracket)
153
+ # Make height even
154
+ height += (height % 2)
155
+
156
+ brackets = []
157
+ for bracket in lbracket, rbracket:
158
+ # Create left bracket
159
+ if bracket in {_lbracket, _lbracket_ucode}:
160
+ bracket_args = [ ' ' * (height//2 - i - 1) +
161
+ slash for i in range(height // 2)]
162
+ bracket_args.extend(
163
+ [' ' * i + bslash for i in range(height // 2)])
164
+ # Create right bracket
165
+ elif bracket in {_rbracket, _rbracket_ucode}:
166
+ bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
167
+ bracket_args.extend([ ' ' * (
168
+ height//2 - i - 1) + slash for i in range(height // 2)])
169
+ # Create straight bracket
170
+ elif bracket in {_straight_bracket, _straight_bracket_ucode}:
171
+ bracket_args = [vert] * height
172
+ else:
173
+ raise ValueError(bracket)
174
+ brackets.append(
175
+ stringPict('\n'.join(bracket_args), baseline=height//2))
176
+ return brackets
177
+
178
+ def _sympystr(self, printer, *args):
179
+ contents = self._print_contents(printer, *args)
180
+ return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
181
+
182
+ def _pretty(self, printer, *args):
183
+ from sympy.printing.pretty.stringpict import prettyForm
184
+ # Get brackets
185
+ pform = self._print_contents_pretty(printer, *args)
186
+ lbracket, rbracket = self._pretty_brackets(
187
+ pform.height(), printer._use_unicode)
188
+ # Put together state
189
+ pform = prettyForm(*pform.left(lbracket))
190
+ pform = prettyForm(*pform.right(rbracket))
191
+ return pform
192
+
193
+ def _latex(self, printer, *args):
194
+ contents = self._print_contents_latex(printer, *args)
195
+ # The extra {} brackets are needed to get matplotlib's latex
196
+ # rendered to render this properly.
197
+ return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
198
+
199
+
200
+ class KetBase(StateBase):
201
+ """Base class for Kets.
202
+
203
+ This class defines the dual property and the brackets for printing. This is
204
+ an abstract base class and you should not instantiate it directly, instead
205
+ use Ket.
206
+ """
207
+
208
+ lbracket = _straight_bracket
209
+ rbracket = _rbracket
210
+ lbracket_ucode = _straight_bracket_ucode
211
+ rbracket_ucode = _rbracket_ucode
212
+ lbracket_latex = r'\left|'
213
+ rbracket_latex = r'\right\rangle '
214
+
215
+ @classmethod
216
+ def default_args(self):
217
+ return ("psi",)
218
+
219
+ @classmethod
220
+ def dual_class(self):
221
+ return BraBase
222
+
223
+ def __mul__(self, other):
224
+ """KetBase*other"""
225
+ from sympy.physics.quantum.operator import OuterProduct
226
+ if isinstance(other, BraBase):
227
+ return OuterProduct(self, other)
228
+ else:
229
+ return Expr.__mul__(self, other)
230
+
231
+ def __rmul__(self, other):
232
+ """other*KetBase"""
233
+ from sympy.physics.quantum.innerproduct import InnerProduct
234
+ if isinstance(other, BraBase):
235
+ return InnerProduct(other, self)
236
+ else:
237
+ return Expr.__rmul__(self, other)
238
+
239
+ #-------------------------------------------------------------------------
240
+ # _eval_* methods
241
+ #-------------------------------------------------------------------------
242
+
243
+ def _eval_innerproduct(self, bra, **hints):
244
+ """Evaluate the inner product between this ket and a bra.
245
+
246
+ This is called to compute <bra|ket>, where the ket is ``self``.
247
+
248
+ This method will dispatch to sub-methods having the format::
249
+
250
+ ``def _eval_innerproduct_BraClass(self, **hints):``
251
+
252
+ Subclasses should define these methods (one for each BraClass) to
253
+ teach the ket how to take inner products with bras.
254
+ """
255
+ return dispatch_method(self, '_eval_innerproduct', bra, **hints)
256
+
257
+ def _apply_from_right_to(self, op, **options):
258
+ """Apply an Operator to this Ket as Operator*Ket
259
+
260
+ This method will dispatch to methods having the format::
261
+
262
+ ``def _apply_from_right_to_OperatorName(op, **options):``
263
+
264
+ Subclasses should define these methods (one for each OperatorName) to
265
+ teach the Ket how to implement OperatorName*Ket
266
+
267
+ Parameters
268
+ ==========
269
+
270
+ op : Operator
271
+ The Operator that is acting on the Ket as op*Ket
272
+ options : dict
273
+ A dict of key/value pairs that control how the operator is applied
274
+ to the Ket.
275
+ """
276
+ return dispatch_method(self, '_apply_from_right_to', op, **options)
277
+
278
+
279
+ class BraBase(StateBase):
280
+ """Base class for Bras.
281
+
282
+ This class defines the dual property and the brackets for printing. This
283
+ is an abstract base class and you should not instantiate it directly,
284
+ instead use Bra.
285
+ """
286
+
287
+ lbracket = _lbracket
288
+ rbracket = _straight_bracket
289
+ lbracket_ucode = _lbracket_ucode
290
+ rbracket_ucode = _straight_bracket_ucode
291
+ lbracket_latex = r'\left\langle '
292
+ rbracket_latex = r'\right|'
293
+
294
+ @classmethod
295
+ def _operators_to_state(self, ops, **options):
296
+ state = self.dual_class()._operators_to_state(ops, **options)
297
+ return state.dual
298
+
299
+ def _state_to_operators(self, op_classes, **options):
300
+ return self.dual._state_to_operators(op_classes, **options)
301
+
302
+ def _enumerate_state(self, num_states, **options):
303
+ dual_states = self.dual._enumerate_state(num_states, **options)
304
+ return [x.dual for x in dual_states]
305
+
306
+ @classmethod
307
+ def default_args(self):
308
+ return self.dual_class().default_args()
309
+
310
+ @classmethod
311
+ def dual_class(self):
312
+ return KetBase
313
+
314
+ def __mul__(self, other):
315
+ """BraBase*other"""
316
+ from sympy.physics.quantum.innerproduct import InnerProduct
317
+ if isinstance(other, KetBase):
318
+ return InnerProduct(self, other)
319
+ else:
320
+ return Expr.__mul__(self, other)
321
+
322
+ def __rmul__(self, other):
323
+ """other*BraBase"""
324
+ from sympy.physics.quantum.operator import OuterProduct
325
+ if isinstance(other, KetBase):
326
+ return OuterProduct(other, self)
327
+ else:
328
+ return Expr.__rmul__(self, other)
329
+
330
+ def _represent(self, **options):
331
+ """A default represent that uses the Ket's version."""
332
+ from sympy.physics.quantum.dagger import Dagger
333
+ return Dagger(self.dual._represent(**options))
334
+
335
+
336
+ class State(StateBase):
337
+ """General abstract quantum state used as a base class for Ket and Bra."""
338
+ pass
339
+
340
+
341
+ class Ket(State, KetBase):
342
+ """A general time-independent Ket in quantum mechanics.
343
+
344
+ Inherits from State and KetBase. This class should be used as the base
345
+ class for all physical, time-independent Kets in a system. This class
346
+ and its subclasses will be the main classes that users will use for
347
+ expressing Kets in Dirac notation [1]_.
348
+
349
+ Parameters
350
+ ==========
351
+
352
+ args : tuple
353
+ The list of numbers or parameters that uniquely specify the
354
+ ket. This will usually be its symbol or its quantum numbers. For
355
+ time-dependent state, this will include the time.
356
+
357
+ Examples
358
+ ========
359
+
360
+ Create a simple Ket and looking at its properties::
361
+
362
+ >>> from sympy.physics.quantum import Ket
363
+ >>> from sympy import symbols, I
364
+ >>> k = Ket('psi')
365
+ >>> k
366
+ |psi>
367
+ >>> k.hilbert_space
368
+ H
369
+ >>> k.is_commutative
370
+ False
371
+ >>> k.label
372
+ (psi,)
373
+
374
+ Ket's know about their associated bra::
375
+
376
+ >>> k.dual
377
+ <psi|
378
+ >>> k.dual_class()
379
+ <class 'sympy.physics.quantum.state.Bra'>
380
+
381
+ Take a linear combination of two kets::
382
+
383
+ >>> k0 = Ket(0)
384
+ >>> k1 = Ket(1)
385
+ >>> 2*I*k0 - 4*k1
386
+ 2*I*|0> - 4*|1>
387
+
388
+ Compound labels are passed as tuples::
389
+
390
+ >>> n, m = symbols('n,m')
391
+ >>> k = Ket(n,m)
392
+ >>> k
393
+ |nm>
394
+
395
+ References
396
+ ==========
397
+
398
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
399
+ """
400
+
401
+ @classmethod
402
+ def dual_class(self):
403
+ return Bra
404
+
405
+
406
+ class Bra(State, BraBase):
407
+ """A general time-independent Bra in quantum mechanics.
408
+
409
+ Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
410
+ class and its subclasses will be the main classes that users will use for
411
+ expressing Bras in Dirac notation.
412
+
413
+ Parameters
414
+ ==========
415
+
416
+ args : tuple
417
+ The list of numbers or parameters that uniquely specify the
418
+ ket. This will usually be its symbol or its quantum numbers. For
419
+ time-dependent state, this will include the time.
420
+
421
+ Examples
422
+ ========
423
+
424
+ Create a simple Bra and look at its properties::
425
+
426
+ >>> from sympy.physics.quantum import Bra
427
+ >>> from sympy import symbols, I
428
+ >>> b = Bra('psi')
429
+ >>> b
430
+ <psi|
431
+ >>> b.hilbert_space
432
+ H
433
+ >>> b.is_commutative
434
+ False
435
+
436
+ Bra's know about their dual Ket's::
437
+
438
+ >>> b.dual
439
+ |psi>
440
+ >>> b.dual_class()
441
+ <class 'sympy.physics.quantum.state.Ket'>
442
+
443
+ Like Kets, Bras can have compound labels and be manipulated in a similar
444
+ manner::
445
+
446
+ >>> n, m = symbols('n,m')
447
+ >>> b = Bra(n,m) - I*Bra(m,n)
448
+ >>> b
449
+ -I*<mn| + <nm|
450
+
451
+ Symbols in a Bra can be substituted using ``.subs``::
452
+
453
+ >>> b.subs(n,m)
454
+ <mm| - I*<mm|
455
+
456
+ References
457
+ ==========
458
+
459
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
460
+ """
461
+
462
+ @classmethod
463
+ def dual_class(self):
464
+ return Ket
465
+
466
+ #-----------------------------------------------------------------------------
467
+ # Time dependent states, bras and kets.
468
+ #-----------------------------------------------------------------------------
469
+
470
+
471
+ class TimeDepState(StateBase):
472
+ """Base class for a general time-dependent quantum state.
473
+
474
+ This class is used as a base class for any time-dependent state. The main
475
+ difference between this class and the time-independent state is that this
476
+ class takes a second argument that is the time in addition to the usual
477
+ label argument.
478
+
479
+ Parameters
480
+ ==========
481
+
482
+ args : tuple
483
+ The list of numbers or parameters that uniquely specify the ket. This
484
+ will usually be its symbol or its quantum numbers. For time-dependent
485
+ state, this will include the time as the final argument.
486
+ """
487
+
488
+ #-------------------------------------------------------------------------
489
+ # Initialization
490
+ #-------------------------------------------------------------------------
491
+
492
+ @classmethod
493
+ def default_args(self):
494
+ return ("psi", "t")
495
+
496
+ #-------------------------------------------------------------------------
497
+ # Properties
498
+ #-------------------------------------------------------------------------
499
+
500
+ @property
501
+ def label(self):
502
+ """The label of the state."""
503
+ return self.args[:-1]
504
+
505
+ @property
506
+ def time(self):
507
+ """The time of the state."""
508
+ return self.args[-1]
509
+
510
+ #-------------------------------------------------------------------------
511
+ # Printing
512
+ #-------------------------------------------------------------------------
513
+
514
+ def _print_time(self, printer, *args):
515
+ return printer._print(self.time, *args)
516
+
517
+ _print_time_repr = _print_time
518
+ _print_time_latex = _print_time
519
+
520
+ def _print_time_pretty(self, printer, *args):
521
+ pform = printer._print(self.time, *args)
522
+ return pform
523
+
524
+ def _print_contents(self, printer, *args):
525
+ label = self._print_label(printer, *args)
526
+ time = self._print_time(printer, *args)
527
+ return '%s;%s' % (label, time)
528
+
529
+ def _print_label_repr(self, printer, *args):
530
+ label = self._print_sequence(self.label, ',', printer, *args)
531
+ time = self._print_time_repr(printer, *args)
532
+ return '%s,%s' % (label, time)
533
+
534
+ def _print_contents_pretty(self, printer, *args):
535
+ label = self._print_label_pretty(printer, *args)
536
+ time = self._print_time_pretty(printer, *args)
537
+ return printer._print_seq((label, time), delimiter=';')
538
+
539
+ def _print_contents_latex(self, printer, *args):
540
+ label = self._print_sequence(
541
+ self.label, self._label_separator, printer, *args)
542
+ time = self._print_time_latex(printer, *args)
543
+ return '%s;%s' % (label, time)
544
+
545
+
546
+ class TimeDepKet(TimeDepState, KetBase):
547
+ """General time-dependent Ket in quantum mechanics.
548
+
549
+ This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
550
+ that should be used for Kets that vary with time. Its dual is a
551
+ ``TimeDepBra``.
552
+
553
+ Parameters
554
+ ==========
555
+
556
+ args : tuple
557
+ The list of numbers or parameters that uniquely specify the ket. This
558
+ will usually be its symbol or its quantum numbers. For time-dependent
559
+ state, this will include the time as the final argument.
560
+
561
+ Examples
562
+ ========
563
+
564
+ Create a TimeDepKet and look at its attributes::
565
+
566
+ >>> from sympy.physics.quantum import TimeDepKet
567
+ >>> k = TimeDepKet('psi', 't')
568
+ >>> k
569
+ |psi;t>
570
+ >>> k.time
571
+ t
572
+ >>> k.label
573
+ (psi,)
574
+ >>> k.hilbert_space
575
+ H
576
+
577
+ TimeDepKets know about their dual bra::
578
+
579
+ >>> k.dual
580
+ <psi;t|
581
+ >>> k.dual_class()
582
+ <class 'sympy.physics.quantum.state.TimeDepBra'>
583
+ """
584
+
585
+ @classmethod
586
+ def dual_class(self):
587
+ return TimeDepBra
588
+
589
+
590
+ class TimeDepBra(TimeDepState, BraBase):
591
+ """General time-dependent Bra in quantum mechanics.
592
+
593
+ This inherits from TimeDepState and BraBase and is the main class that
594
+ should be used for Bras that vary with time. Its dual is a TimeDepBra.
595
+
596
+ Parameters
597
+ ==========
598
+
599
+ args : tuple
600
+ The list of numbers or parameters that uniquely specify the ket. This
601
+ will usually be its symbol or its quantum numbers. For time-dependent
602
+ state, this will include the time as the final argument.
603
+
604
+ Examples
605
+ ========
606
+
607
+ >>> from sympy.physics.quantum import TimeDepBra
608
+ >>> b = TimeDepBra('psi', 't')
609
+ >>> b
610
+ <psi;t|
611
+ >>> b.time
612
+ t
613
+ >>> b.label
614
+ (psi,)
615
+ >>> b.hilbert_space
616
+ H
617
+ >>> b.dual
618
+ |psi;t>
619
+ """
620
+
621
+ @classmethod
622
+ def dual_class(self):
623
+ return TimeDepKet
624
+
625
+
626
+ class OrthogonalState(State, StateBase):
627
+ """General abstract quantum state used as a base class for Ket and Bra."""
628
+ pass
629
+
630
+ class OrthogonalKet(OrthogonalState, KetBase):
631
+ """Orthogonal Ket in quantum mechanics.
632
+
633
+ The inner product of two states with different labels will give zero,
634
+ states with the same label will give one.
635
+
636
+ >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
637
+ >>> from sympy.abc import m, n
638
+ >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
639
+ 1
640
+ >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
641
+ 0
642
+ >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
643
+ <n|m>
644
+ """
645
+
646
+ @classmethod
647
+ def dual_class(self):
648
+ return OrthogonalBra
649
+
650
+ def _eval_innerproduct(self, bra, **hints):
651
+
652
+ if len(self.args) != len(bra.args):
653
+ raise ValueError('Cannot multiply a ket that has a different number of labels.')
654
+
655
+ for arg, bra_arg in zip(self.args, bra.args):
656
+ diff = arg - bra_arg
657
+ diff = diff.expand()
658
+
659
+ is_zero = diff.is_zero
660
+
661
+ if is_zero is False:
662
+ return S.Zero # i.e. Integer(0)
663
+
664
+ if is_zero is None:
665
+ return None
666
+
667
+ return S.One # i.e. Integer(1)
668
+
669
+
670
+ class OrthogonalBra(OrthogonalState, BraBase):
671
+ """Orthogonal Bra in quantum mechanics.
672
+ """
673
+
674
+ @classmethod
675
+ def dual_class(self):
676
+ return OrthogonalKet
677
+
678
+
679
+ class Wavefunction(Function):
680
+ """Class for representations in continuous bases
681
+
682
+ This class takes an expression and coordinates in its constructor. It can
683
+ be used to easily calculate normalizations and probabilities.
684
+
685
+ Parameters
686
+ ==========
687
+
688
+ expr : Expr
689
+ The expression representing the functional form of the w.f.
690
+
691
+ coords : Symbol or tuple
692
+ The coordinates to be integrated over, and their bounds
693
+
694
+ Examples
695
+ ========
696
+
697
+ Particle in a box, specifying bounds in the more primitive way of using
698
+ Piecewise:
699
+
700
+ >>> from sympy import Symbol, Piecewise, pi, N
701
+ >>> from sympy.functions import sqrt, sin
702
+ >>> from sympy.physics.quantum.state import Wavefunction
703
+ >>> x = Symbol('x', real=True)
704
+ >>> n = 1
705
+ >>> L = 1
706
+ >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
707
+ >>> f = Wavefunction(g, x)
708
+ >>> f.norm
709
+ 1
710
+ >>> f.is_normalized
711
+ True
712
+ >>> p = f.prob()
713
+ >>> p(0)
714
+ 0
715
+ >>> p(L)
716
+ 0
717
+ >>> p(0.5)
718
+ 2
719
+ >>> p(0.85*L)
720
+ 2*sin(0.85*pi)**2
721
+ >>> N(p(0.85*L))
722
+ 0.412214747707527
723
+
724
+ Additionally, you can specify the bounds of the function and the indices in
725
+ a more compact way:
726
+
727
+ >>> from sympy import symbols, pi, diff
728
+ >>> from sympy.functions import sqrt, sin
729
+ >>> from sympy.physics.quantum.state import Wavefunction
730
+ >>> x, L = symbols('x,L', positive=True)
731
+ >>> n = symbols('n', integer=True, positive=True)
732
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
733
+ >>> f = Wavefunction(g, (x, 0, L))
734
+ >>> f.norm
735
+ 1
736
+ >>> f(L+1)
737
+ 0
738
+ >>> f(L-1)
739
+ sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
740
+ >>> f(-1)
741
+ 0
742
+ >>> f(0.85)
743
+ sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
744
+ >>> f(0.85, n=1, L=1)
745
+ sqrt(2)*sin(0.85*pi)
746
+ >>> f.is_commutative
747
+ False
748
+
749
+ All arguments are automatically sympified, so you can define the variables
750
+ as strings rather than symbols:
751
+
752
+ >>> expr = x**2
753
+ >>> f = Wavefunction(expr, 'x')
754
+ >>> type(f.variables[0])
755
+ <class 'sympy.core.symbol.Symbol'>
756
+
757
+ Derivatives of Wavefunctions will return Wavefunctions:
758
+
759
+ >>> diff(f, x)
760
+ Wavefunction(2*x, x)
761
+
762
+ """
763
+
764
+ #Any passed tuples for coordinates and their bounds need to be
765
+ #converted to Tuples before Function's constructor is called, to
766
+ #avoid errors from calling is_Float in the constructor
767
+ def __new__(cls, *args, **options):
768
+ new_args = [None for i in args]
769
+ ct = 0
770
+ for arg in args:
771
+ if isinstance(arg, tuple):
772
+ new_args[ct] = Tuple(*arg)
773
+ else:
774
+ new_args[ct] = arg
775
+ ct += 1
776
+
777
+ return super().__new__(cls, *new_args, **options)
778
+
779
+ def __call__(self, *args, **options):
780
+ var = self.variables
781
+
782
+ if len(args) != len(var):
783
+ raise NotImplementedError(
784
+ "Incorrect number of arguments to function!")
785
+
786
+ ct = 0
787
+ #If the passed value is outside the specified bounds, return 0
788
+ for v in var:
789
+ lower, upper = self.limits[v]
790
+
791
+ #Do the comparison to limits only if the passed symbol is actually
792
+ #a symbol present in the limits;
793
+ #Had problems with a comparison of x > L
794
+ if isinstance(args[ct], Expr) and \
795
+ not (lower in args[ct].free_symbols
796
+ or upper in args[ct].free_symbols):
797
+ continue
798
+
799
+ if (args[ct] < lower) == True or (args[ct] > upper) == True:
800
+ return S.Zero
801
+
802
+ ct += 1
803
+
804
+ expr = self.expr
805
+
806
+ #Allows user to make a call like f(2, 4, m=1, n=1)
807
+ for symbol in list(expr.free_symbols):
808
+ if str(symbol) in options.keys():
809
+ val = options[str(symbol)]
810
+ expr = expr.subs(symbol, val)
811
+
812
+ return expr.subs(zip(var, args))
813
+
814
+ def _eval_derivative(self, symbol):
815
+ expr = self.expr
816
+ deriv = expr._eval_derivative(symbol)
817
+
818
+ return Wavefunction(deriv, *self.args[1:])
819
+
820
+ def _eval_conjugate(self):
821
+ return Wavefunction(conjugate(self.expr), *self.args[1:])
822
+
823
+ def _eval_transpose(self):
824
+ return self
825
+
826
+ @property
827
+ def free_symbols(self):
828
+ return self.expr.free_symbols
829
+
830
+ @property
831
+ def is_commutative(self):
832
+ """
833
+ Override Function's is_commutative so that order is preserved in
834
+ represented expressions
835
+ """
836
+ return False
837
+
838
+ @classmethod
839
+ def eval(self, *args):
840
+ return None
841
+
842
+ @property
843
+ def variables(self):
844
+ """
845
+ Return the coordinates which the wavefunction depends on
846
+
847
+ Examples
848
+ ========
849
+
850
+ >>> from sympy.physics.quantum.state import Wavefunction
851
+ >>> from sympy import symbols
852
+ >>> x,y = symbols('x,y')
853
+ >>> f = Wavefunction(x*y, x, y)
854
+ >>> f.variables
855
+ (x, y)
856
+ >>> g = Wavefunction(x*y, x)
857
+ >>> g.variables
858
+ (x,)
859
+
860
+ """
861
+ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
862
+ return tuple(var)
863
+
864
+ @property
865
+ def limits(self):
866
+ """
867
+ Return the limits of the coordinates which the w.f. depends on If no
868
+ limits are specified, defaults to ``(-oo, oo)``.
869
+
870
+ Examples
871
+ ========
872
+
873
+ >>> from sympy.physics.quantum.state import Wavefunction
874
+ >>> from sympy import symbols
875
+ >>> x, y = symbols('x, y')
876
+ >>> f = Wavefunction(x**2, (x, 0, 1))
877
+ >>> f.limits
878
+ {x: (0, 1)}
879
+ >>> f = Wavefunction(x**2, x)
880
+ >>> f.limits
881
+ {x: (-oo, oo)}
882
+ >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
883
+ >>> f.limits
884
+ {x: (-oo, oo), y: (-1, 2)}
885
+
886
+ """
887
+ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
888
+ for g in self._args[1:]]
889
+ return dict(zip(self.variables, tuple(limits)))
890
+
891
+ @property
892
+ def expr(self):
893
+ """
894
+ Return the expression which is the functional form of the Wavefunction
895
+
896
+ Examples
897
+ ========
898
+
899
+ >>> from sympy.physics.quantum.state import Wavefunction
900
+ >>> from sympy import symbols
901
+ >>> x, y = symbols('x, y')
902
+ >>> f = Wavefunction(x**2, x)
903
+ >>> f.expr
904
+ x**2
905
+
906
+ """
907
+ return self._args[0]
908
+
909
+ @property
910
+ def is_normalized(self):
911
+ """
912
+ Returns true if the Wavefunction is properly normalized
913
+
914
+ Examples
915
+ ========
916
+
917
+ >>> from sympy import symbols, pi
918
+ >>> from sympy.functions import sqrt, sin
919
+ >>> from sympy.physics.quantum.state import Wavefunction
920
+ >>> x, L = symbols('x,L', positive=True)
921
+ >>> n = symbols('n', integer=True, positive=True)
922
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
923
+ >>> f = Wavefunction(g, (x, 0, L))
924
+ >>> f.is_normalized
925
+ True
926
+
927
+ """
928
+
929
+ return equal_valued(self.norm, 1)
930
+
931
+ @property # type: ignore
932
+ @cacheit
933
+ def norm(self):
934
+ """
935
+ Return the normalization of the specified functional form.
936
+
937
+ This function integrates over the coordinates of the Wavefunction, with
938
+ the bounds specified.
939
+
940
+ Examples
941
+ ========
942
+
943
+ >>> from sympy import symbols, pi
944
+ >>> from sympy.functions import sqrt, sin
945
+ >>> from sympy.physics.quantum.state import Wavefunction
946
+ >>> x, L = symbols('x,L', positive=True)
947
+ >>> n = symbols('n', integer=True, positive=True)
948
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
949
+ >>> f = Wavefunction(g, (x, 0, L))
950
+ >>> f.norm
951
+ 1
952
+ >>> g = sin(n*pi*x/L)
953
+ >>> f = Wavefunction(g, (x, 0, L))
954
+ >>> f.norm
955
+ sqrt(2)*sqrt(L)/2
956
+
957
+ """
958
+
959
+ exp = self.expr*conjugate(self.expr)
960
+ var = self.variables
961
+ limits = self.limits
962
+
963
+ for v in var:
964
+ curr_limits = limits[v]
965
+ exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
966
+
967
+ return sqrt(exp)
968
+
969
+ def normalize(self):
970
+ """
971
+ Return a normalized version of the Wavefunction
972
+
973
+ Examples
974
+ ========
975
+
976
+ >>> from sympy import symbols, pi
977
+ >>> from sympy.functions import sin
978
+ >>> from sympy.physics.quantum.state import Wavefunction
979
+ >>> x = symbols('x', real=True)
980
+ >>> L = symbols('L', positive=True)
981
+ >>> n = symbols('n', integer=True, positive=True)
982
+ >>> g = sin(n*pi*x/L)
983
+ >>> f = Wavefunction(g, (x, 0, L))
984
+ >>> f.normalize()
985
+ Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
986
+
987
+ """
988
+ const = self.norm
989
+
990
+ if const is oo:
991
+ raise NotImplementedError("The function is not normalizable!")
992
+ else:
993
+ return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
994
+
995
+ def prob(self):
996
+ r"""
997
+ Return the absolute magnitude of the w.f., `|\psi(x)|^2`
998
+
999
+ Examples
1000
+ ========
1001
+
1002
+ >>> from sympy import symbols, pi
1003
+ >>> from sympy.functions import sin
1004
+ >>> from sympy.physics.quantum.state import Wavefunction
1005
+ >>> x, L = symbols('x,L', real=True)
1006
+ >>> n = symbols('n', integer=True)
1007
+ >>> g = sin(n*pi*x/L)
1008
+ >>> f = Wavefunction(g, (x, 0, L))
1009
+ >>> f.prob()
1010
+ Wavefunction(sin(pi*n*x/L)**2, x)
1011
+
1012
+ """
1013
+
1014
+ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
venv/lib/python3.10/site-packages/sympy/physics/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (187 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc ADDED
Binary file (7.86 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc ADDED
Binary file (2.27 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi, Rational)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.functions.special.spherical_harmonics import Ynm
8
+ from sympy.matrices.dense import Matrix
9
+ from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt,
10
+ real_gaunt, racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d)
11
+ from sympy.testing.pytest import raises
12
+
13
+ # for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients
14
+
15
+ def test_clebsch_gordan_docs():
16
+ assert clebsch_gordan(Rational(3, 2), S.Half, 2, Rational(3, 2), S.Half, 2) == 1
17
+ assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(3, 2), Rational(-1, 2), 1) == sqrt(3)/2
18
+ assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2
19
+
20
+
21
+ def test_clebsch_gordan():
22
+ # Argument order: (j_1, j_2, j, m_1, m_2, m)
23
+
24
+ h = S.One
25
+ k = S.Half
26
+ l = Rational(3, 2)
27
+ i = Rational(-1, 2)
28
+ n = Rational(7, 2)
29
+ p = Rational(5, 2)
30
+ assert clebsch_gordan(k, k, 1, k, k, 1) == 1
31
+ assert clebsch_gordan(k, k, 1, k, k, 0) == 0
32
+ assert clebsch_gordan(k, k, 1, i, i, -1) == 1
33
+ assert clebsch_gordan(k, k, 1, k, i, 0) == sqrt(2)/2
34
+ assert clebsch_gordan(k, k, 0, k, i, 0) == sqrt(2)/2
35
+ assert clebsch_gordan(k, k, 1, i, k, 0) == sqrt(2)/2
36
+ assert clebsch_gordan(k, k, 0, i, k, 0) == -sqrt(2)/2
37
+ assert clebsch_gordan(h, k, l, 1, k, l) == 1
38
+ assert clebsch_gordan(h, k, l, 1, i, k) == 1/sqrt(3)
39
+ assert clebsch_gordan(h, k, k, 1, i, k) == sqrt(2)/sqrt(3)
40
+ assert clebsch_gordan(h, k, k, 0, k, k) == -1/sqrt(3)
41
+ assert clebsch_gordan(h, k, l, 0, k, k) == sqrt(2)/sqrt(3)
42
+ assert clebsch_gordan(h, h, S(2), 1, 1, S(2)) == 1
43
+ assert clebsch_gordan(h, h, S(2), 1, 0, 1) == 1/sqrt(2)
44
+ assert clebsch_gordan(h, h, S(2), 0, 1, 1) == 1/sqrt(2)
45
+ assert clebsch_gordan(h, h, 1, 1, 0, 1) == 1/sqrt(2)
46
+ assert clebsch_gordan(h, h, 1, 0, 1, 1) == -1/sqrt(2)
47
+ assert clebsch_gordan(l, l, S(3), l, l, S(3)) == 1
48
+ assert clebsch_gordan(l, l, S(2), l, k, S(2)) == 1/sqrt(2)
49
+ assert clebsch_gordan(l, l, S(3), l, k, S(2)) == 1/sqrt(2)
50
+ assert clebsch_gordan(S(2), S(2), S(4), S(2), S(2), S(4)) == 1
51
+ assert clebsch_gordan(S(2), S(2), S(3), S(2), 1, S(3)) == 1/sqrt(2)
52
+ assert clebsch_gordan(S(2), S(2), S(3), 1, 1, S(2)) == 0
53
+ assert clebsch_gordan(p, h, n, p, 1, n) == 1
54
+ assert clebsch_gordan(p, h, p, p, 0, p) == sqrt(5)/sqrt(7)
55
+ assert clebsch_gordan(p, h, l, k, 1, l) == 1/sqrt(15)
56
+
57
+
58
+ def test_wigner():
59
+ def tn(a, b):
60
+ return (a - b).n(64) < S('1e-64')
61
+ assert tn(wigner_9j(1, 1, 1, 1, 1, 1, 1, 1, 0, prec=64), Rational(1, 18))
62
+ assert wigner_9j(3, 3, 2, 3, 3, 2, 3, 3, 2) == 3221*sqrt(
63
+ 70)/(246960*sqrt(105)) - 365/(3528*sqrt(70)*sqrt(105))
64
+ assert wigner_6j(5, 5, 5, 5, 5, 5) == Rational(1, 52)
65
+ assert tn(wigner_6j(8, 8, 8, 8, 8, 8, prec=64), Rational(-12219, 965770))
66
+ # regression test for #8747
67
+ half = S.Half
68
+ assert wigner_9j(0, 0, 0, 0, half, half, 0, half, half) == half
69
+ assert (wigner_9j(3, 5, 4,
70
+ 7 * half, 5 * half, 4,
71
+ 9 * half, 9 * half, 0)
72
+ == -sqrt(Rational(361, 205821000)))
73
+ assert (wigner_9j(1, 4, 3,
74
+ 5 * half, 4, 5 * half,
75
+ 5 * half, 2, 7 * half)
76
+ == -sqrt(Rational(3971, 373403520)))
77
+ assert (wigner_9j(4, 9 * half, 5 * half,
78
+ 2, 4, 4,
79
+ 5, 7 * half, 7 * half)
80
+ == -sqrt(Rational(3481, 5042614500)))
81
+
82
+
83
+ def test_gaunt():
84
+ def tn(a, b):
85
+ return (a - b).n(64) < S('1e-64')
86
+ assert gaunt(1, 0, 1, 1, 0, -1) == -1/(2*sqrt(pi))
87
+ assert isinstance(gaunt(1, 1, 0, -1, 1, 0).args[0], Rational)
88
+ assert isinstance(gaunt(0, 1, 1, 0, -1, 1).args[0], Rational)
89
+
90
+ assert tn(gaunt(
91
+ 10, 10, 12, 9, 3, -12, prec=64), (Rational(-98, 62031)) * sqrt(6279)/sqrt(pi))
92
+ def gaunt_ref(l1, l2, l3, m1, m2, m3):
93
+ return (
94
+ sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) / (4 * pi)) *
95
+ wigner_3j(l1, l2, l3, 0, 0, 0) *
96
+ wigner_3j(l1, l2, l3, m1, m2, m3)
97
+ )
98
+ threshold = 1e-10
99
+ l_max = 3
100
+ l3_max = 24
101
+ for l1 in range(l_max + 1):
102
+ for l2 in range(l_max + 1):
103
+ for l3 in range(l3_max + 1):
104
+ for m1 in range(-l1, l1 + 1):
105
+ for m2 in range(-l2, l2 + 1):
106
+ for m3 in range(-l3, l3 + 1):
107
+ args = l1, l2, l3, m1, m2, m3
108
+ g = gaunt(*args)
109
+ g0 = gaunt_ref(*args)
110
+ assert abs(g - g0) < threshold
111
+ if m1 + m2 + m3 != 0:
112
+ assert abs(g) < threshold
113
+ if (l1 + l2 + l3) % 2:
114
+ assert abs(g) < threshold
115
+ assert gaunt(1, 1, 0, 0, 2, -2) is S.Zero
116
+
117
+
118
+ def test_realgaunt():
119
+ # All non-zero values corresponding to l values from 0 to 2
120
+ for l in range(3):
121
+ for m in range(-l, l+1):
122
+ assert real_gaunt(0, l, l, 0, m, m) == 1/(2*sqrt(pi))
123
+ assert real_gaunt(1, 1, 2, 0, 0, 0) == sqrt(5)/(5*sqrt(pi))
124
+ assert real_gaunt(1, 1, 2, 1, 1, 0) == -sqrt(5)/(10*sqrt(pi))
125
+ assert real_gaunt(2, 2, 2, 0, 0, 0) == sqrt(5)/(7*sqrt(pi))
126
+ assert real_gaunt(2, 2, 2, 0, 2, 2) == -sqrt(5)/(7*sqrt(pi))
127
+ assert real_gaunt(2, 2, 2, -2, -2, 0) == -sqrt(5)/(7*sqrt(pi))
128
+ assert real_gaunt(1, 1, 2, -1, 0, -1) == sqrt(15)/(10*sqrt(pi))
129
+ assert real_gaunt(1, 1, 2, 0, 1, 1) == sqrt(15)/(10*sqrt(pi))
130
+ assert real_gaunt(1, 1, 2, 1, 1, 2) == sqrt(15)/(10*sqrt(pi))
131
+ assert real_gaunt(1, 1, 2, -1, 1, -2) == -sqrt(15)/(10*sqrt(pi))
132
+ assert real_gaunt(1, 1, 2, -1, -1, 2) == -sqrt(15)/(10*sqrt(pi))
133
+ assert real_gaunt(2, 2, 2, 0, 1, 1) == sqrt(5)/(14*sqrt(pi))
134
+ assert real_gaunt(2, 2, 2, 1, 1, 2) == sqrt(15)/(14*sqrt(pi))
135
+ assert real_gaunt(2, 2, 2, -1, -1, 2) == -sqrt(15)/(14*sqrt(pi))
136
+
137
+ assert real_gaunt(-2, -2, -2, -2, -2, 0) is S.Zero # m test
138
+ assert real_gaunt(-2, 1, 0, 1, 1, 1) is S.Zero # l test
139
+ assert real_gaunt(-2, -1, -2, -1, -1, 0) is S.Zero # m and l test
140
+ assert real_gaunt(-2, -2, -2, -2, -2, -2) is S.Zero # m and k test
141
+ assert real_gaunt(-2, -1, -2, -1, -1, -1) is S.Zero # m, l and k test
142
+
143
+ x = symbols('x', integer=True)
144
+ v = [0]*6
145
+ for i in range(len(v)):
146
+ v[i] = x # non literal ints fail
147
+ raises(ValueError, lambda: real_gaunt(*v))
148
+ v[i] = 0
149
+
150
+
151
+ def test_racah():
152
+ assert racah(3,3,3,3,3,3) == Rational(-1,14)
153
+ assert racah(2,2,2,2,2,2) == Rational(-3,70)
154
+ assert racah(7,8,7,1,7,7, prec=4).is_Float
155
+ assert racah(5.5,7.5,9.5,6.5,8,9) == -719*sqrt(598)/1158924
156
+ assert abs(racah(5.5,7.5,9.5,6.5,8,9, prec=4) - (-0.01517)) < S('1e-4')
157
+
158
+
159
+ def test_dot_rota_grad_SH():
160
+ theta, phi = symbols("theta phi")
161
+ assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0) != \
162
+ sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
163
+ assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0).doit() == \
164
+ sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
165
+ assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2) != \
166
+ 0
167
+ assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2).doit() == \
168
+ 0
169
+ assert dot_rot_grad_Ynm(3, 3, 3, 3, theta, phi).doit() == \
170
+ 15*sqrt(3003)*Ynm(6, 6, theta, phi)/(143*sqrt(pi))
171
+ assert dot_rot_grad_Ynm(3, 3, 1, 1, theta, phi).doit() == \
172
+ sqrt(3)*Ynm(4, 4, theta, phi)/sqrt(pi)
173
+ assert dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() == \
174
+ 3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
175
+ assert dot_rot_grad_Ynm(3, 2, 3, 2, theta, phi).doit().expand() == \
176
+ -sqrt(70)*Ynm(4, 4, theta, phi)/(11*sqrt(pi)) + \
177
+ 45*sqrt(182)*Ynm(6, 4, theta, phi)/(143*sqrt(pi))
178
+
179
+
180
+ def test_wigner_d():
181
+ half = S(1)/2
182
+ alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
183
+ d = wigner_d_small(half, beta).subs({beta: pi/2})
184
+ d_ = Matrix([[1, 1], [-1, 1]])/sqrt(2)
185
+ assert d == d_
186
+
187
+ D = wigner_d(half, alpha, beta, gamma)
188
+ assert D[0, 0] == exp(I*alpha/2)*exp(I*gamma/2)*cos(beta/2)
189
+ assert D[0, 1] == exp(I*alpha/2)*exp(-I*gamma/2)*sin(beta/2)
190
+ assert D[1, 0] == -exp(-I*alpha/2)*exp(I*gamma/2)*sin(beta/2)
191
+ assert D[1, 1] == exp(-I*alpha/2)*exp(-I*gamma/2)*cos(beta/2)
venv/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.integrals.integrals import integrate
8
+ from sympy.simplify.simplify import simplify
9
+ from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac, Psi_nlm
10
+ from sympy.testing.pytest import raises
11
+
12
+ n, r, Z = symbols('n r Z')
13
+
14
+
15
+ def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
16
+ a = float(a)
17
+ b = float(b)
18
+ # if the numbers are close enough (absolutely), then they are equal
19
+ if abs(a - b) < max_absolute_error:
20
+ return True
21
+ # if not, they can still be equal if their relative error is small
22
+ if abs(b) > abs(a):
23
+ relative_error = abs((a - b)/b)
24
+ else:
25
+ relative_error = abs((a - b)/a)
26
+ return relative_error <= max_relative_error
27
+
28
+
29
+ def test_wavefunction():
30
+ a = 1/Z
31
+ R = {
32
+ (1, 0): 2*sqrt(1/a**3) * exp(-r/a),
33
+ (2, 0): sqrt(1/(2*a**3)) * exp(-r/(2*a)) * (1 - r/(2*a)),
34
+ (2, 1): S.Half * sqrt(1/(6*a**3)) * exp(-r/(2*a)) * r/a,
35
+ (3, 0): Rational(2, 3) * sqrt(1/(3*a**3)) * exp(-r/(3*a)) *
36
+ (1 - 2*r/(3*a) + Rational(2, 27) * (r/a)**2),
37
+ (3, 1): Rational(4, 27) * sqrt(2/(3*a**3)) * exp(-r/(3*a)) *
38
+ (1 - r/(6*a)) * r/a,
39
+ (3, 2): Rational(2, 81) * sqrt(2/(15*a**3)) * exp(-r/(3*a)) * (r/a)**2,
40
+ (4, 0): Rational(1, 4) * sqrt(1/a**3) * exp(-r/(4*a)) *
41
+ (1 - 3*r/(4*a) + Rational(1, 8) * (r/a)**2 - Rational(1, 192) * (r/a)**3),
42
+ (4, 1): Rational(1, 16) * sqrt(5/(3*a**3)) * exp(-r/(4*a)) *
43
+ (1 - r/(4*a) + Rational(1, 80) * (r/a)**2) * (r/a),
44
+ (4, 2): Rational(1, 64) * sqrt(1/(5*a**3)) * exp(-r/(4*a)) *
45
+ (1 - r/(12*a)) * (r/a)**2,
46
+ (4, 3): Rational(1, 768) * sqrt(1/(35*a**3)) * exp(-r/(4*a)) * (r/a)**3,
47
+ }
48
+ for n, l in R:
49
+ assert simplify(R_nl(n, l, r, Z) - R[(n, l)]) == 0
50
+
51
+
52
+ def test_norm():
53
+ # Maximum "n" which is tested:
54
+ n_max = 2 # it works, but is slow, for n_max > 2
55
+ for n in range(n_max + 1):
56
+ for l in range(n):
57
+ assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1
58
+
59
+ def test_psi_nlm():
60
+ r=S('r')
61
+ phi=S('phi')
62
+ theta=S('theta')
63
+ assert (Psi_nlm(1, 0, 0, r, phi, theta) == exp(-r) / sqrt(pi))
64
+ assert (Psi_nlm(2, 1, -1, r, phi, theta)) == S.Half * exp(-r / (2)) * r \
65
+ * (sin(theta) * exp(-I * phi) / (4 * sqrt(pi)))
66
+ assert (Psi_nlm(3, 2, 1, r, phi, theta, 2) == -sqrt(2) * sin(theta) \
67
+ * exp(I * phi) * cos(theta) / (4 * sqrt(pi)) * S(2) / 81 \
68
+ * sqrt(2 * 2 ** 3) * exp(-2 * r / (3)) * (r * 2) ** 2)
69
+
70
+ def test_hydrogen_energies():
71
+ assert E_nl(n, Z) == -Z**2/(2*n**2)
72
+ assert E_nl(n) == -1/(2*n**2)
73
+
74
+ assert E_nl(1, 47) == -S(47)**2/(2*1**2)
75
+ assert E_nl(2, 47) == -S(47)**2/(2*2**2)
76
+
77
+ assert E_nl(1) == -S.One/(2*1**2)
78
+ assert E_nl(2) == -S.One/(2*2**2)
79
+ assert E_nl(3) == -S.One/(2*3**2)
80
+ assert E_nl(4) == -S.One/(2*4**2)
81
+ assert E_nl(100) == -S.One/(2*100**2)
82
+
83
+ raises(ValueError, lambda: E_nl(0))
84
+
85
+
86
+ def test_hydrogen_energies_relat():
87
+ # First test exact formulas for small "c" so that we get nice expressions:
88
+ assert E_nl_dirac(2, 0, Z=1, c=1) == 1/sqrt(2) - 1
89
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=2) - ( (8*sqrt(3) + 16)
90
+ / sqrt(16*sqrt(3) + 32) - 4)) == 0
91
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=3) - ( (54*sqrt(2) + 81)
92
+ / sqrt(108*sqrt(2) + 162) - 9)) == 0
93
+
94
+ # Now test for almost the correct speed of light, without floating point
95
+ # numbers:
96
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=137) - ( (352275361 + 10285412 *
97
+ sqrt(1173)) / sqrt(704550722 + 20570824 * sqrt(1173)) - 18769)) == 0
98
+ assert simplify(E_nl_dirac(2, 0, Z=82, c=137) - ( (352275361 + 2571353 *
99
+ sqrt(12045)) / sqrt(704550722 + 5142706*sqrt(12045)) - 18769)) == 0
100
+
101
+ # Test using exact speed of light, and compare against the nonrelativistic
102
+ # energies:
103
+ for n in range(1, 5):
104
+ for l in range(n):
105
+ assert feq(E_nl_dirac(n, l), E_nl(n), 1e-5, 1e-5)
106
+ if l > 0:
107
+ assert feq(E_nl_dirac(n, l, False), E_nl(n), 1e-5, 1e-5)
108
+
109
+ Z = 2
110
+ for n in range(1, 5):
111
+ for l in range(n):
112
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-4, 1e-4)
113
+ if l > 0:
114
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-4, 1e-4)
115
+
116
+ Z = 3
117
+ for n in range(1, 5):
118
+ for l in range(n):
119
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-3, 1e-3)
120
+ if l > 0:
121
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-3, 1e-3)
122
+
123
+ # Test the exceptions:
124
+ raises(ValueError, lambda: E_nl_dirac(0, 0))
125
+ raises(ValueError, lambda: E_nl_dirac(1, -1))
126
+ raises(ValueError, lambda: E_nl_dirac(1, 0, False))
venv/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I
2
+ from sympy.core.symbol import symbols
3
+ from sympy.physics.paulialgebra import Pauli
4
+ from sympy.testing.pytest import XFAIL
5
+ from sympy.physics.quantum import TensorProduct
6
+
7
+ sigma1 = Pauli(1)
8
+ sigma2 = Pauli(2)
9
+ sigma3 = Pauli(3)
10
+
11
+ tau1 = symbols("tau1", commutative = False)
12
+
13
+
14
+ def test_Pauli():
15
+
16
+ assert sigma1 == sigma1
17
+ assert sigma1 != sigma2
18
+
19
+ assert sigma1*sigma2 == I*sigma3
20
+ assert sigma3*sigma1 == I*sigma2
21
+ assert sigma2*sigma3 == I*sigma1
22
+
23
+ assert sigma1*sigma1 == 1
24
+ assert sigma2*sigma2 == 1
25
+ assert sigma3*sigma3 == 1
26
+
27
+ assert sigma1**0 == 1
28
+ assert sigma1**1 == sigma1
29
+ assert sigma1**2 == 1
30
+ assert sigma1**3 == sigma1
31
+ assert sigma1**4 == 1
32
+
33
+ assert sigma3**2 == 1
34
+
35
+ assert sigma1*2*sigma1 == 2
36
+
37
+
38
+ def test_evaluate_pauli_product():
39
+ from sympy.physics.paulialgebra import evaluate_pauli_product
40
+
41
+ assert evaluate_pauli_product(I*sigma2*sigma3) == -sigma1
42
+
43
+ # Check issue 6471
44
+ assert evaluate_pauli_product(-I*4*sigma1*sigma2) == 4*sigma3
45
+
46
+ assert evaluate_pauli_product(
47
+ 1 + I*sigma1*sigma2*sigma1*sigma2 + \
48
+ I*sigma1*sigma2*tau1*sigma1*sigma3 + \
49
+ ((tau1**2).subs(tau1, I*sigma1)) + \
50
+ sigma3*((tau1**2).subs(tau1, I*sigma1)) + \
51
+ TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1)
52
+ ) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1)
53
+
54
+
55
+ @XFAIL
56
+ def test_Pauli_should_work():
57
+ assert sigma1*sigma3*sigma1 == -sigma3
venv/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft
2
+ from sympy.core.numbers import (I, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.matrices.dense import (Matrix, eye, zeros)
6
+ from sympy.testing.pytest import warns_deprecated_sympy
7
+
8
+
9
+ def test_parallel_axis_theorem():
10
+ # This tests the parallel axis theorem matrix by comparing to test
11
+ # matrices.
12
+
13
+ # First case, 1 in all directions.
14
+ mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2)))
15
+ assert pat_matrix(1, 1, 1, 1) == mat1
16
+ assert pat_matrix(2, 1, 1, 1) == 2*mat1
17
+
18
+ # Second case, 1 in x, 0 in all others
19
+ mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1)))
20
+ assert pat_matrix(1, 1, 0, 0) == mat2
21
+ assert pat_matrix(2, 1, 0, 0) == 2*mat2
22
+
23
+ # Third case, 1 in y, 0 in all others
24
+ mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1)))
25
+ assert pat_matrix(1, 0, 1, 0) == mat3
26
+ assert pat_matrix(2, 0, 1, 0) == 2*mat3
27
+
28
+ # Fourth case, 1 in z, 0 in all others
29
+ mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0)))
30
+ assert pat_matrix(1, 0, 0, 1) == mat4
31
+ assert pat_matrix(2, 0, 0, 1) == 2*mat4
32
+
33
+
34
+ def test_Pauli():
35
+ #this and the following test are testing both Pauli and Dirac matrices
36
+ #and also that the general Matrix class works correctly in a real world
37
+ #situation
38
+ sigma1 = msigma(1)
39
+ sigma2 = msigma(2)
40
+ sigma3 = msigma(3)
41
+
42
+ assert sigma1 == sigma1
43
+ assert sigma1 != sigma2
44
+
45
+ # sigma*I -> I*sigma (see #354)
46
+ assert sigma1*sigma2 == sigma3*I
47
+ assert sigma3*sigma1 == sigma2*I
48
+ assert sigma2*sigma3 == sigma1*I
49
+
50
+ assert sigma1*sigma1 == eye(2)
51
+ assert sigma2*sigma2 == eye(2)
52
+ assert sigma3*sigma3 == eye(2)
53
+
54
+ assert sigma1*2*sigma1 == 2*eye(2)
55
+ assert sigma1*sigma3*sigma1 == -sigma3
56
+
57
+
58
+ def test_Dirac():
59
+ gamma0 = mgamma(0)
60
+ gamma1 = mgamma(1)
61
+ gamma2 = mgamma(2)
62
+ gamma3 = mgamma(3)
63
+ gamma5 = mgamma(5)
64
+
65
+ # gamma*I -> I*gamma (see #354)
66
+ assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I
67
+ assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4)
68
+ assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0]
69
+ assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0]
70
+ assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2]
71
+
72
+ assert mgamma(5, True) == \
73
+ mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
74
+
75
+ def test_mdft():
76
+ with warns_deprecated_sympy():
77
+ assert mdft(1) == Matrix([[1]])
78
+ with warns_deprecated_sympy():
79
+ assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
80
+ with warns_deprecated_sympy():
81
+ assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half],
82
+ [S.Half, -I/2, Rational(-1,2), I/2],
83
+ [S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
84
+ [S.Half, I/2, Rational(-1,2), -I/2]])