ZTWHHH commited on
Commit
2472b6d
·
verified ·
1 Parent(s): 55feaed

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. .gitattributes +4 -0
  2. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cartesian.cpython-310.pyc +0 -0
  3. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc +0 -0
  4. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc +0 -0
  5. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/pauli.cpython-310.pyc +0 -0
  6. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/represent.cpython-310.pyc +0 -0
  7. pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/state.cpython-310.pyc +0 -0
  8. pllava/lib/python3.10/site-packages/sympy/physics/quantum/boson.py +259 -0
  9. pllava/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
  10. pllava/lib/python3.10/site-packages/sympy/physics/quantum/constants.py +59 -0
  11. pllava/lib/python3.10/site-packages/sympy/physics/quantum/density.py +319 -0
  12. pllava/lib/python3.10/site-packages/sympy/physics/quantum/gate.py +1309 -0
  13. pllava/lib/python3.10/site-packages/sympy/physics/quantum/grover.py +345 -0
  14. pllava/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py +653 -0
  15. pllava/lib/python3.10/site-packages/sympy/physics/quantum/matrixcache.py +103 -0
  16. pllava/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py +272 -0
  17. pllava/lib/python3.10/site-packages/sympy/physics/quantum/operator.py +657 -0
  18. pllava/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py +290 -0
  19. pllava/lib/python3.10/site-packages/sympy/physics/quantum/pauli.py +675 -0
  20. pllava/lib/python3.10/site-packages/sympy/physics/quantum/piab.py +72 -0
  21. pllava/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py +212 -0
  22. pllava/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py +413 -0
  23. pllava/lib/python3.10/site-packages/sympy/physics/quantum/qubit.py +811 -0
  24. pllava/lib/python3.10/site-packages/sympy/physics/quantum/represent.py +574 -0
  25. pllava/lib/python3.10/site-packages/sympy/physics/quantum/sho1d.py +679 -0
  26. pllava/lib/python3.10/site-packages/sympy/physics/quantum/shor.py +173 -0
  27. pllava/lib/python3.10/site-packages/sympy/physics/quantum/spin.py +2150 -0
  28. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py +425 -0
  29. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc +0 -0
  30. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_boson.cpython-310.pyc +0 -0
  31. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc +0 -0
  32. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc +0 -0
  33. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_constants.cpython-310.pyc +0 -0
  34. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_dagger.cpython-310.pyc +0 -0
  35. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_density.cpython-310.pyc +0 -0
  36. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc +0 -0
  37. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_gate.cpython-310.pyc +0 -0
  38. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc +0 -0
  39. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_identitysearch.cpython-310.pyc +0 -0
  40. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc +0 -0
  41. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc +0 -0
  42. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc +0 -0
  43. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_piab.cpython-310.pyc +0 -0
  44. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc +0 -0
  45. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc +0 -0
  46. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_shor.cpython-310.pyc +0 -0
  47. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc +0 -0
  48. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py +56 -0
  49. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py +50 -0
  50. pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py +104 -0
.gitattributes CHANGED
@@ -291,3 +291,7 @@ pllava/lib/libncurses++.a filter=lfs diff=lfs merge=lfs -text
291
  pllava/bin/xz filter=lfs diff=lfs merge=lfs -text
292
  pllava/lib/libbz2.so.1.0.8 filter=lfs diff=lfs merge=lfs -text
293
  pllava/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
291
  pllava/bin/xz filter=lfs diff=lfs merge=lfs -text
292
  pllava/lib/libbz2.so.1.0.8 filter=lfs diff=lfs merge=lfs -text
293
  pllava/lib/python3.10/site-packages/torio/lib/libtorio_ffmpeg5.so filter=lfs diff=lfs merge=lfs -text
294
+ pllava/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
295
+ pllava/lib/python3.10/site-packages/transformers/__pycache__/modeling_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
296
+ pllava/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
297
+ pllava/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cartesian.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc ADDED
Binary file (3.72 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/pauli.cpython-310.pyc ADDED
Binary file (18.9 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/represent.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/state.cpython-310.pyc ADDED
Binary file (30.8 kB). View file
 
pllava/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
pllava/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])
pllava/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()
pllava/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()
pllava/lib/python3.10/site-packages/sympy/physics/quantum/gate.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.matrixbase 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
+ is_hermitian = True
629
+ gate_name = '1'
630
+ gate_name_latex = '1'
631
+
632
+ # Short cut version of gate._apply_operator_Qubit
633
+ def _apply_operator_Qubit(self, qubits, **options):
634
+ # Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
635
+ if qubits.nqubits < self.min_qubits:
636
+ raise QuantumError(
637
+ 'Gate needs a minimum of %r qubits to act on, got: %r' %
638
+ (self.min_qubits, qubits.nqubits)
639
+ )
640
+ return qubits # no computation required for IdentityGate
641
+
642
+ def get_target_matrix(self, format='sympy'):
643
+ return matrix_cache.get_matrix('eye2', format)
644
+
645
+ def _eval_commutator(self, other, **hints):
646
+ return _S.Zero
647
+
648
+ def _eval_anticommutator(self, other, **hints):
649
+ return Integer(2)*other
650
+
651
+
652
+ class HadamardGate(HermitianOperator, OneQubitGate):
653
+ """The single qubit Hadamard gate.
654
+
655
+ Parameters
656
+ ----------
657
+ target : int
658
+ The target qubit this gate will apply to.
659
+
660
+ Examples
661
+ ========
662
+
663
+ >>> from sympy import sqrt
664
+ >>> from sympy.physics.quantum.qubit import Qubit
665
+ >>> from sympy.physics.quantum.gate import HadamardGate
666
+ >>> from sympy.physics.quantum.qapply import qapply
667
+ >>> qapply(HadamardGate(0)*Qubit('1'))
668
+ sqrt(2)*|0>/2 - sqrt(2)*|1>/2
669
+ >>> # Hadamard on bell state, applied on 2 qubits.
670
+ >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
671
+ >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
672
+ sqrt(2)*|00>/2 + sqrt(2)*|11>/2
673
+
674
+ """
675
+ gate_name = 'H'
676
+ gate_name_latex = 'H'
677
+
678
+ def get_target_matrix(self, format='sympy'):
679
+ if _normalized:
680
+ return matrix_cache.get_matrix('H', format)
681
+ else:
682
+ return matrix_cache.get_matrix('Hsqrt2', format)
683
+
684
+ def _eval_commutator_XGate(self, other, **hints):
685
+ return I*sqrt(2)*YGate(self.targets[0])
686
+
687
+ def _eval_commutator_YGate(self, other, **hints):
688
+ return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
689
+
690
+ def _eval_commutator_ZGate(self, other, **hints):
691
+ return -I*sqrt(2)*YGate(self.targets[0])
692
+
693
+ def _eval_anticommutator_XGate(self, other, **hints):
694
+ return sqrt(2)*IdentityGate(self.targets[0])
695
+
696
+ def _eval_anticommutator_YGate(self, other, **hints):
697
+ return _S.Zero
698
+
699
+ def _eval_anticommutator_ZGate(self, other, **hints):
700
+ return sqrt(2)*IdentityGate(self.targets[0])
701
+
702
+
703
+ class XGate(HermitianOperator, OneQubitGate):
704
+ """The single qubit X, or NOT, gate.
705
+
706
+ Parameters
707
+ ----------
708
+ target : int
709
+ The target qubit this gate will apply to.
710
+
711
+ Examples
712
+ ========
713
+
714
+ """
715
+ gate_name = 'X'
716
+ gate_name_latex = 'X'
717
+
718
+ def get_target_matrix(self, format='sympy'):
719
+ return matrix_cache.get_matrix('X', format)
720
+
721
+ def plot_gate(self, circ_plot, gate_idx):
722
+ OneQubitGate.plot_gate(self,circ_plot,gate_idx)
723
+
724
+ def plot_gate_plus(self, circ_plot, gate_idx):
725
+ circ_plot.not_point(
726
+ gate_idx, int(self.label[0])
727
+ )
728
+
729
+ def _eval_commutator_YGate(self, other, **hints):
730
+ return Integer(2)*I*ZGate(self.targets[0])
731
+
732
+ def _eval_anticommutator_XGate(self, other, **hints):
733
+ return Integer(2)*IdentityGate(self.targets[0])
734
+
735
+ def _eval_anticommutator_YGate(self, other, **hints):
736
+ return _S.Zero
737
+
738
+ def _eval_anticommutator_ZGate(self, other, **hints):
739
+ return _S.Zero
740
+
741
+
742
+ class YGate(HermitianOperator, OneQubitGate):
743
+ """The single qubit Y gate.
744
+
745
+ Parameters
746
+ ----------
747
+ target : int
748
+ The target qubit this gate will apply to.
749
+
750
+ Examples
751
+ ========
752
+
753
+ """
754
+ gate_name = 'Y'
755
+ gate_name_latex = 'Y'
756
+
757
+ def get_target_matrix(self, format='sympy'):
758
+ return matrix_cache.get_matrix('Y', format)
759
+
760
+ def _eval_commutator_ZGate(self, other, **hints):
761
+ return Integer(2)*I*XGate(self.targets[0])
762
+
763
+ def _eval_anticommutator_YGate(self, other, **hints):
764
+ return Integer(2)*IdentityGate(self.targets[0])
765
+
766
+ def _eval_anticommutator_ZGate(self, other, **hints):
767
+ return _S.Zero
768
+
769
+
770
+ class ZGate(HermitianOperator, OneQubitGate):
771
+ """The single qubit Z gate.
772
+
773
+ Parameters
774
+ ----------
775
+ target : int
776
+ The target qubit this gate will apply to.
777
+
778
+ Examples
779
+ ========
780
+
781
+ """
782
+ gate_name = 'Z'
783
+ gate_name_latex = 'Z'
784
+
785
+ def get_target_matrix(self, format='sympy'):
786
+ return matrix_cache.get_matrix('Z', format)
787
+
788
+ def _eval_commutator_XGate(self, other, **hints):
789
+ return Integer(2)*I*YGate(self.targets[0])
790
+
791
+ def _eval_anticommutator_YGate(self, other, **hints):
792
+ return _S.Zero
793
+
794
+
795
+ class PhaseGate(OneQubitGate):
796
+ """The single qubit phase, or S, gate.
797
+
798
+ This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
799
+ does nothing if the state is ``|0>``.
800
+
801
+ Parameters
802
+ ----------
803
+ target : int
804
+ The target qubit this gate will apply to.
805
+
806
+ Examples
807
+ ========
808
+
809
+ """
810
+ is_hermitian = False
811
+ gate_name = 'S'
812
+ gate_name_latex = 'S'
813
+
814
+ def get_target_matrix(self, format='sympy'):
815
+ return matrix_cache.get_matrix('S', format)
816
+
817
+ def _eval_commutator_ZGate(self, other, **hints):
818
+ return _S.Zero
819
+
820
+ def _eval_commutator_TGate(self, other, **hints):
821
+ return _S.Zero
822
+
823
+
824
+ class TGate(OneQubitGate):
825
+ """The single qubit pi/8 gate.
826
+
827
+ This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
828
+ does nothing if the state is ``|0>``.
829
+
830
+ Parameters
831
+ ----------
832
+ target : int
833
+ The target qubit this gate will apply to.
834
+
835
+ Examples
836
+ ========
837
+
838
+ """
839
+ is_hermitian = False
840
+ gate_name = 'T'
841
+ gate_name_latex = 'T'
842
+
843
+ def get_target_matrix(self, format='sympy'):
844
+ return matrix_cache.get_matrix('T', format)
845
+
846
+ def _eval_commutator_ZGate(self, other, **hints):
847
+ return _S.Zero
848
+
849
+ def _eval_commutator_PhaseGate(self, other, **hints):
850
+ return _S.Zero
851
+
852
+
853
+ # Aliases for gate names.
854
+ H = HadamardGate
855
+ X = XGate
856
+ Y = YGate
857
+ Z = ZGate
858
+ T = TGate
859
+ Phase = S = PhaseGate
860
+
861
+
862
+ #-----------------------------------------------------------------------------
863
+ # 2 Qubit Gates
864
+ #-----------------------------------------------------------------------------
865
+
866
+
867
+ class CNotGate(HermitianOperator, CGate, TwoQubitGate):
868
+ """Two qubit controlled-NOT.
869
+
870
+ This gate performs the NOT or X gate on the target qubit if the control
871
+ qubits all have the value 1.
872
+
873
+ Parameters
874
+ ----------
875
+ label : tuple
876
+ A tuple of the form (control, target).
877
+
878
+ Examples
879
+ ========
880
+
881
+ >>> from sympy.physics.quantum.gate import CNOT
882
+ >>> from sympy.physics.quantum.qapply import qapply
883
+ >>> from sympy.physics.quantum.qubit import Qubit
884
+ >>> c = CNOT(1,0)
885
+ >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
886
+ |11>
887
+
888
+ """
889
+ gate_name = 'CNOT'
890
+ gate_name_latex = r'\text{CNOT}'
891
+ simplify_cgate = True
892
+
893
+ #-------------------------------------------------------------------------
894
+ # Initialization
895
+ #-------------------------------------------------------------------------
896
+
897
+ @classmethod
898
+ def _eval_args(cls, args):
899
+ args = Gate._eval_args(args)
900
+ return args
901
+
902
+ @classmethod
903
+ def _eval_hilbert_space(cls, args):
904
+ """This returns the smallest possible Hilbert space."""
905
+ return ComplexSpace(2)**(_max(args) + 1)
906
+
907
+ #-------------------------------------------------------------------------
908
+ # Properties
909
+ #-------------------------------------------------------------------------
910
+
911
+ @property
912
+ def min_qubits(self):
913
+ """The minimum number of qubits this gate needs to act on."""
914
+ return _max(self.label) + 1
915
+
916
+ @property
917
+ def targets(self):
918
+ """A tuple of target qubits."""
919
+ return (self.label[1],)
920
+
921
+ @property
922
+ def controls(self):
923
+ """A tuple of control qubits."""
924
+ return (self.label[0],)
925
+
926
+ @property
927
+ def gate(self):
928
+ """The non-controlled gate that will be applied to the targets."""
929
+ return XGate(self.label[1])
930
+
931
+ #-------------------------------------------------------------------------
932
+ # Properties
933
+ #-------------------------------------------------------------------------
934
+
935
+ # The default printing of Gate works better than those of CGate, so we
936
+ # go around the overridden methods in CGate.
937
+
938
+ def _print_label(self, printer, *args):
939
+ return Gate._print_label(self, printer, *args)
940
+
941
+ def _pretty(self, printer, *args):
942
+ return Gate._pretty(self, printer, *args)
943
+
944
+ def _latex(self, printer, *args):
945
+ return Gate._latex(self, printer, *args)
946
+
947
+ #-------------------------------------------------------------------------
948
+ # Commutator/AntiCommutator
949
+ #-------------------------------------------------------------------------
950
+
951
+ def _eval_commutator_ZGate(self, other, **hints):
952
+ """[CNOT(i, j), Z(i)] == 0."""
953
+ if self.controls[0] == other.targets[0]:
954
+ return _S.Zero
955
+ else:
956
+ raise NotImplementedError('Commutator not implemented: %r' % other)
957
+
958
+ def _eval_commutator_TGate(self, other, **hints):
959
+ """[CNOT(i, j), T(i)] == 0."""
960
+ return self._eval_commutator_ZGate(other, **hints)
961
+
962
+ def _eval_commutator_PhaseGate(self, other, **hints):
963
+ """[CNOT(i, j), S(i)] == 0."""
964
+ return self._eval_commutator_ZGate(other, **hints)
965
+
966
+ def _eval_commutator_XGate(self, other, **hints):
967
+ """[CNOT(i, j), X(j)] == 0."""
968
+ if self.targets[0] == other.targets[0]:
969
+ return _S.Zero
970
+ else:
971
+ raise NotImplementedError('Commutator not implemented: %r' % other)
972
+
973
+ def _eval_commutator_CNotGate(self, other, **hints):
974
+ """[CNOT(i, j), CNOT(i,k)] == 0."""
975
+ if self.controls[0] == other.controls[0]:
976
+ return _S.Zero
977
+ else:
978
+ raise NotImplementedError('Commutator not implemented: %r' % other)
979
+
980
+
981
+ class SwapGate(TwoQubitGate):
982
+ """Two qubit SWAP gate.
983
+
984
+ This gate swap the values of the two qubits.
985
+
986
+ Parameters
987
+ ----------
988
+ label : tuple
989
+ A tuple of the form (target1, target2).
990
+
991
+ Examples
992
+ ========
993
+
994
+ """
995
+ is_hermitian = True
996
+ gate_name = 'SWAP'
997
+ gate_name_latex = r'\text{SWAP}'
998
+
999
+ def get_target_matrix(self, format='sympy'):
1000
+ return matrix_cache.get_matrix('SWAP', format)
1001
+
1002
+ def decompose(self, **options):
1003
+ """Decompose the SWAP gate into CNOT gates."""
1004
+ i, j = self.targets[0], self.targets[1]
1005
+ g1 = CNotGate(i, j)
1006
+ g2 = CNotGate(j, i)
1007
+ return g1*g2*g1
1008
+
1009
+ def plot_gate(self, circ_plot, gate_idx):
1010
+ min_wire = int(_min(self.targets))
1011
+ max_wire = int(_max(self.targets))
1012
+ circ_plot.control_line(gate_idx, min_wire, max_wire)
1013
+ circ_plot.swap_point(gate_idx, min_wire)
1014
+ circ_plot.swap_point(gate_idx, max_wire)
1015
+
1016
+ def _represent_ZGate(self, basis, **options):
1017
+ """Represent the SWAP gate in the computational basis.
1018
+
1019
+ The following representation is used to compute this:
1020
+
1021
+ SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
1022
+ """
1023
+ format = options.get('format', 'sympy')
1024
+ targets = [int(t) for t in self.targets]
1025
+ min_target = _min(targets)
1026
+ max_target = _max(targets)
1027
+ nqubits = options.get('nqubits', self.min_qubits)
1028
+
1029
+ op01 = matrix_cache.get_matrix('op01', format)
1030
+ op10 = matrix_cache.get_matrix('op10', format)
1031
+ op11 = matrix_cache.get_matrix('op11', format)
1032
+ op00 = matrix_cache.get_matrix('op00', format)
1033
+ eye2 = matrix_cache.get_matrix('eye2', format)
1034
+
1035
+ result = None
1036
+ for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
1037
+ product = nqubits*[eye2]
1038
+ product[nqubits - min_target - 1] = i
1039
+ product[nqubits - max_target - 1] = j
1040
+ new_result = matrix_tensor_product(*product)
1041
+ if result is None:
1042
+ result = new_result
1043
+ else:
1044
+ result = result + new_result
1045
+
1046
+ return result
1047
+
1048
+
1049
+ # Aliases for gate names.
1050
+ CNOT = CNotGate
1051
+ SWAP = SwapGate
1052
+ def CPHASE(a,b): return CGateS((a,),Z(b))
1053
+
1054
+
1055
+ #-----------------------------------------------------------------------------
1056
+ # Represent
1057
+ #-----------------------------------------------------------------------------
1058
+
1059
+
1060
+ def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
1061
+ """Represent a gate with controls, targets and target_matrix.
1062
+
1063
+ This function does the low-level work of representing gates as matrices
1064
+ in the standard computational basis (ZGate). Currently, we support two
1065
+ main cases:
1066
+
1067
+ 1. One target qubit and no control qubits.
1068
+ 2. One target qubits and multiple control qubits.
1069
+
1070
+ For the base of multiple controls, we use the following expression [1]:
1071
+
1072
+ 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
1073
+
1074
+ Parameters
1075
+ ----------
1076
+ controls : list, tuple
1077
+ A sequence of control qubits.
1078
+ targets : list, tuple
1079
+ A sequence of target qubits.
1080
+ target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
1081
+ The matrix form of the transformation to be performed on the target
1082
+ qubits. The format of this matrix must match that passed into
1083
+ the `format` argument.
1084
+ nqubits : int
1085
+ The total number of qubits used for the representation.
1086
+ format : str
1087
+ The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
1088
+
1089
+ Examples
1090
+ ========
1091
+
1092
+ References
1093
+ ----------
1094
+ [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
1095
+ """
1096
+ controls = [int(x) for x in controls]
1097
+ targets = [int(x) for x in targets]
1098
+ nqubits = int(nqubits)
1099
+
1100
+ # This checks for the format as well.
1101
+ op11 = matrix_cache.get_matrix('op11', format)
1102
+ eye2 = matrix_cache.get_matrix('eye2', format)
1103
+
1104
+ # Plain single qubit case
1105
+ if len(controls) == 0 and len(targets) == 1:
1106
+ product = []
1107
+ bit = targets[0]
1108
+ # Fill product with [I1,Gate,I2] such that the unitaries,
1109
+ # I, cause the gate to be applied to the correct Qubit
1110
+ if bit != nqubits - 1:
1111
+ product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
1112
+ product.append(target_matrix)
1113
+ if bit != 0:
1114
+ product.append(matrix_eye(2**bit, format=format))
1115
+ return matrix_tensor_product(*product)
1116
+
1117
+ # Single target, multiple controls.
1118
+ elif len(targets) == 1 and len(controls) >= 1:
1119
+ target = targets[0]
1120
+
1121
+ # Build the non-trivial part.
1122
+ product2 = []
1123
+ for i in range(nqubits):
1124
+ product2.append(matrix_eye(2, format=format))
1125
+ for control in controls:
1126
+ product2[nqubits - 1 - control] = op11
1127
+ product2[nqubits - 1 - target] = target_matrix - eye2
1128
+
1129
+ return matrix_eye(2**nqubits, format=format) + \
1130
+ matrix_tensor_product(*product2)
1131
+
1132
+ # Multi-target, multi-control is not yet implemented.
1133
+ else:
1134
+ raise NotImplementedError(
1135
+ 'The representation of multi-target, multi-control gates '
1136
+ 'is not implemented.'
1137
+ )
1138
+
1139
+
1140
+ #-----------------------------------------------------------------------------
1141
+ # Gate manipulation functions.
1142
+ #-----------------------------------------------------------------------------
1143
+
1144
+
1145
+ def gate_simp(circuit):
1146
+ """Simplifies gates symbolically
1147
+
1148
+ It first sorts gates using gate_sort. It then applies basic
1149
+ simplification rules to the circuit, e.g., XGate**2 = Identity
1150
+ """
1151
+
1152
+ # Bubble sort out gates that commute.
1153
+ circuit = gate_sort(circuit)
1154
+
1155
+ # Do simplifications by subing a simplification into the first element
1156
+ # which can be simplified. We recursively call gate_simp with new circuit
1157
+ # as input more simplifications exist.
1158
+ if isinstance(circuit, Add):
1159
+ return sum(gate_simp(t) for t in circuit.args)
1160
+ elif isinstance(circuit, Mul):
1161
+ circuit_args = circuit.args
1162
+ elif isinstance(circuit, Pow):
1163
+ b, e = circuit.as_base_exp()
1164
+ circuit_args = (gate_simp(b)**e,)
1165
+ else:
1166
+ return circuit
1167
+
1168
+ # Iterate through each element in circuit, simplify if possible.
1169
+ for i in range(len(circuit_args)):
1170
+ # H,X,Y or Z squared is 1.
1171
+ # T**2 = S, S**2 = Z
1172
+ if isinstance(circuit_args[i], Pow):
1173
+ if isinstance(circuit_args[i].base,
1174
+ (HadamardGate, XGate, YGate, ZGate)) \
1175
+ and isinstance(circuit_args[i].exp, Number):
1176
+ # Build a new circuit taking replacing the
1177
+ # H,X,Y,Z squared with one.
1178
+ newargs = (circuit_args[:i] +
1179
+ (circuit_args[i].base**(circuit_args[i].exp % 2),) +
1180
+ circuit_args[i + 1:])
1181
+ # Recursively simplify the new circuit.
1182
+ circuit = gate_simp(Mul(*newargs))
1183
+ break
1184
+ elif isinstance(circuit_args[i].base, PhaseGate):
1185
+ # Build a new circuit taking old circuit but splicing
1186
+ # in simplification.
1187
+ newargs = circuit_args[:i]
1188
+ # Replace PhaseGate**2 with ZGate.
1189
+ newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
1190
+ (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
1191
+ (circuit_args[i].exp % 2))
1192
+ # Append the last elements.
1193
+ newargs = newargs + circuit_args[i + 1:]
1194
+ # Recursively simplify the new circuit.
1195
+ circuit = gate_simp(Mul(*newargs))
1196
+ break
1197
+ elif isinstance(circuit_args[i].base, TGate):
1198
+ # Build a new circuit taking all the old elements.
1199
+ newargs = circuit_args[:i]
1200
+
1201
+ # Put an Phasegate in place of any TGate**2.
1202
+ newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
1203
+ Integer(circuit_args[i].exp/2), circuit_args[i].base**
1204
+ (circuit_args[i].exp % 2))
1205
+
1206
+ # Append the last elements.
1207
+ newargs = newargs + circuit_args[i + 1:]
1208
+ # Recursively simplify the new circuit.
1209
+ circuit = gate_simp(Mul(*newargs))
1210
+ break
1211
+ return circuit
1212
+
1213
+
1214
+ def gate_sort(circuit):
1215
+ """Sorts the gates while keeping track of commutation relations
1216
+
1217
+ This function uses a bubble sort to rearrange the order of gate
1218
+ application. Keeps track of Quantum computations special commutation
1219
+ relations (e.g. things that apply to the same Qubit do not commute with
1220
+ each other)
1221
+
1222
+ circuit is the Mul of gates that are to be sorted.
1223
+ """
1224
+ # Make sure we have an Add or Mul.
1225
+ if isinstance(circuit, Add):
1226
+ return sum(gate_sort(t) for t in circuit.args)
1227
+ if isinstance(circuit, Pow):
1228
+ return gate_sort(circuit.base)**circuit.exp
1229
+ elif isinstance(circuit, Gate):
1230
+ return circuit
1231
+ if not isinstance(circuit, Mul):
1232
+ return circuit
1233
+
1234
+ changes = True
1235
+ while changes:
1236
+ changes = False
1237
+ circ_array = circuit.args
1238
+ for i in range(len(circ_array) - 1):
1239
+ # Go through each element and switch ones that are in wrong order
1240
+ if isinstance(circ_array[i], (Gate, Pow)) and \
1241
+ isinstance(circ_array[i + 1], (Gate, Pow)):
1242
+ # If we have a Pow object, look at only the base
1243
+ first_base, first_exp = circ_array[i].as_base_exp()
1244
+ second_base, second_exp = circ_array[i + 1].as_base_exp()
1245
+
1246
+ # Use SymPy's hash based sorting. This is not mathematical
1247
+ # sorting, but is rather based on comparing hashes of objects.
1248
+ # See Basic.compare for details.
1249
+ if first_base.compare(second_base) > 0:
1250
+ if Commutator(first_base, second_base).doit() == 0:
1251
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1252
+ (circuit.args[i],) + circuit.args[i + 2:])
1253
+ circuit = Mul(*new_args)
1254
+ changes = True
1255
+ break
1256
+ if AntiCommutator(first_base, second_base).doit() == 0:
1257
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1258
+ (circuit.args[i],) + circuit.args[i + 2:])
1259
+ sign = _S.NegativeOne**(first_exp*second_exp)
1260
+ circuit = sign*Mul(*new_args)
1261
+ changes = True
1262
+ break
1263
+ return circuit
1264
+
1265
+
1266
+ #-----------------------------------------------------------------------------
1267
+ # Utility functions
1268
+ #-----------------------------------------------------------------------------
1269
+
1270
+
1271
+ def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
1272
+ """Return a random circuit of ngates and nqubits.
1273
+
1274
+ This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
1275
+ gates.
1276
+
1277
+ Parameters
1278
+ ----------
1279
+ ngates : int
1280
+ The number of gates in the circuit.
1281
+ nqubits : int
1282
+ The number of qubits in the circuit.
1283
+ gate_space : tuple
1284
+ A tuple of the gate classes that will be used in the circuit.
1285
+ Repeating gate classes multiple times in this tuple will increase
1286
+ the frequency they appear in the random circuit.
1287
+ """
1288
+ qubit_space = range(nqubits)
1289
+ result = []
1290
+ for i in range(ngates):
1291
+ g = random.choice(gate_space)
1292
+ if g == CNotGate or g == SwapGate:
1293
+ qubits = random.sample(qubit_space, 2)
1294
+ g = g(*qubits)
1295
+ else:
1296
+ qubit = random.choice(qubit_space)
1297
+ g = g(qubit)
1298
+ result.append(g)
1299
+ return Mul(*result)
1300
+
1301
+
1302
+ def zx_basis_transform(self, format='sympy'):
1303
+ """Transformation matrix from Z to X basis."""
1304
+ return matrix_cache.get_matrix('ZX', format)
1305
+
1306
+
1307
+ def zy_basis_transform(self, format='sympy'):
1308
+ """Transformation matrix from Z to Y basis."""
1309
+ return matrix_cache.get_matrix('ZY', format)
pllava/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
pllava/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hilbert spaces for quantum mechanics.
2
+
3
+ Authors:
4
+ * Brian Granger
5
+ * Matt Curry
6
+ """
7
+
8
+ from functools import reduce
9
+
10
+ from sympy.core.basic import Basic
11
+ from sympy.core.singleton import S
12
+ from sympy.core.sympify import sympify
13
+ from sympy.sets.sets import Interval
14
+ from sympy.printing.pretty.stringpict import prettyForm
15
+ from sympy.physics.quantum.qexpr import QuantumError
16
+
17
+
18
+ __all__ = [
19
+ 'HilbertSpaceError',
20
+ 'HilbertSpace',
21
+ 'TensorProductHilbertSpace',
22
+ 'TensorPowerHilbertSpace',
23
+ 'DirectSumHilbertSpace',
24
+ 'ComplexSpace',
25
+ 'L2',
26
+ 'FockSpace'
27
+ ]
28
+
29
+ #-----------------------------------------------------------------------------
30
+ # Main objects
31
+ #-----------------------------------------------------------------------------
32
+
33
+
34
+ class HilbertSpaceError(QuantumError):
35
+ pass
36
+
37
+ #-----------------------------------------------------------------------------
38
+ # Main objects
39
+ #-----------------------------------------------------------------------------
40
+
41
+
42
+ class HilbertSpace(Basic):
43
+ """An abstract Hilbert space for quantum mechanics.
44
+
45
+ In short, a Hilbert space is an abstract vector space that is complete
46
+ with inner products defined [1]_.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.physics.quantum.hilbert import HilbertSpace
52
+ >>> hs = HilbertSpace()
53
+ >>> hs
54
+ H
55
+
56
+ References
57
+ ==========
58
+
59
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space
60
+ """
61
+
62
+ def __new__(cls):
63
+ obj = Basic.__new__(cls)
64
+ return obj
65
+
66
+ @property
67
+ def dimension(self):
68
+ """Return the Hilbert dimension of the space."""
69
+ raise NotImplementedError('This Hilbert space has no dimension.')
70
+
71
+ def __add__(self, other):
72
+ return DirectSumHilbertSpace(self, other)
73
+
74
+ def __radd__(self, other):
75
+ return DirectSumHilbertSpace(other, self)
76
+
77
+ def __mul__(self, other):
78
+ return TensorProductHilbertSpace(self, other)
79
+
80
+ def __rmul__(self, other):
81
+ return TensorProductHilbertSpace(other, self)
82
+
83
+ def __pow__(self, other, mod=None):
84
+ if mod is not None:
85
+ raise ValueError('The third argument to __pow__ is not supported \
86
+ for Hilbert spaces.')
87
+ return TensorPowerHilbertSpace(self, other)
88
+
89
+ def __contains__(self, other):
90
+ """Is the operator or state in this Hilbert space.
91
+
92
+ This is checked by comparing the classes of the Hilbert spaces, not
93
+ the instances. This is to allow Hilbert Spaces with symbolic
94
+ dimensions.
95
+ """
96
+ if other.hilbert_space.__class__ == self.__class__:
97
+ return True
98
+ else:
99
+ return False
100
+
101
+ def _sympystr(self, printer, *args):
102
+ return 'H'
103
+
104
+ def _pretty(self, printer, *args):
105
+ ustr = '\N{LATIN CAPITAL LETTER H}'
106
+ return prettyForm(ustr)
107
+
108
+ def _latex(self, printer, *args):
109
+ return r'\mathcal{H}'
110
+
111
+
112
+ class ComplexSpace(HilbertSpace):
113
+ """Finite dimensional Hilbert space of complex vectors.
114
+
115
+ The elements of this Hilbert space are n-dimensional complex valued
116
+ vectors with the usual inner product that takes the complex conjugate
117
+ of the vector on the right.
118
+
119
+ A classic example of this type of Hilbert space is spin-1/2, which is
120
+ ``ComplexSpace(2)``. Generalizing to spin-s, the space is
121
+ ``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
122
+ direct product space ``ComplexSpace(2)**N``.
123
+
124
+ Examples
125
+ ========
126
+
127
+ >>> from sympy import symbols
128
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace
129
+ >>> c1 = ComplexSpace(2)
130
+ >>> c1
131
+ C(2)
132
+ >>> c1.dimension
133
+ 2
134
+
135
+ >>> n = symbols('n')
136
+ >>> c2 = ComplexSpace(n)
137
+ >>> c2
138
+ C(n)
139
+ >>> c2.dimension
140
+ n
141
+
142
+ """
143
+
144
+ def __new__(cls, dimension):
145
+ dimension = sympify(dimension)
146
+ r = cls.eval(dimension)
147
+ if isinstance(r, Basic):
148
+ return r
149
+ obj = Basic.__new__(cls, dimension)
150
+ return obj
151
+
152
+ @classmethod
153
+ def eval(cls, dimension):
154
+ if len(dimension.atoms()) == 1:
155
+ if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
156
+ or dimension.is_Symbol):
157
+ raise TypeError('The dimension of a ComplexSpace can only'
158
+ 'be a positive integer, oo, or a Symbol: %r'
159
+ % dimension)
160
+ else:
161
+ for dim in dimension.atoms():
162
+ if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
163
+ raise TypeError('The dimension of a ComplexSpace can only'
164
+ ' contain integers, oo, or a Symbol: %r'
165
+ % dim)
166
+
167
+ @property
168
+ def dimension(self):
169
+ return self.args[0]
170
+
171
+ def _sympyrepr(self, printer, *args):
172
+ return "%s(%s)" % (self.__class__.__name__,
173
+ printer._print(self.dimension, *args))
174
+
175
+ def _sympystr(self, printer, *args):
176
+ return "C(%s)" % printer._print(self.dimension, *args)
177
+
178
+ def _pretty(self, printer, *args):
179
+ ustr = '\N{LATIN CAPITAL LETTER C}'
180
+ pform_exp = printer._print(self.dimension, *args)
181
+ pform_base = prettyForm(ustr)
182
+ return pform_base**pform_exp
183
+
184
+ def _latex(self, printer, *args):
185
+ return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
186
+
187
+
188
+ class L2(HilbertSpace):
189
+ """The Hilbert space of square integrable functions on an interval.
190
+
191
+ An L2 object takes in a single SymPy Interval argument which represents
192
+ the interval its functions (vectors) are defined on.
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy import Interval, oo
198
+ >>> from sympy.physics.quantum.hilbert import L2
199
+ >>> hs = L2(Interval(0,oo))
200
+ >>> hs
201
+ L2(Interval(0, oo))
202
+ >>> hs.dimension
203
+ oo
204
+ >>> hs.interval
205
+ Interval(0, oo)
206
+
207
+ """
208
+
209
+ def __new__(cls, interval):
210
+ if not isinstance(interval, Interval):
211
+ raise TypeError('L2 interval must be an Interval instance: %r'
212
+ % interval)
213
+ obj = Basic.__new__(cls, interval)
214
+ return obj
215
+
216
+ @property
217
+ def dimension(self):
218
+ return S.Infinity
219
+
220
+ @property
221
+ def interval(self):
222
+ return self.args[0]
223
+
224
+ def _sympyrepr(self, printer, *args):
225
+ return "L2(%s)" % printer._print(self.interval, *args)
226
+
227
+ def _sympystr(self, printer, *args):
228
+ return "L2(%s)" % printer._print(self.interval, *args)
229
+
230
+ def _pretty(self, printer, *args):
231
+ pform_exp = prettyForm('2')
232
+ pform_base = prettyForm('L')
233
+ return pform_base**pform_exp
234
+
235
+ def _latex(self, printer, *args):
236
+ interval = printer._print(self.interval, *args)
237
+ return r'{\mathcal{L}^2}\left( %s \right)' % interval
238
+
239
+
240
+ class FockSpace(HilbertSpace):
241
+ """The Hilbert space for second quantization.
242
+
243
+ Technically, this Hilbert space is a infinite direct sum of direct
244
+ products of single particle Hilbert spaces [1]_. This is a mess, so we have
245
+ a class to represent it directly.
246
+
247
+ Examples
248
+ ========
249
+
250
+ >>> from sympy.physics.quantum.hilbert import FockSpace
251
+ >>> hs = FockSpace()
252
+ >>> hs
253
+ F
254
+ >>> hs.dimension
255
+ oo
256
+
257
+ References
258
+ ==========
259
+
260
+ .. [1] https://en.wikipedia.org/wiki/Fock_space
261
+ """
262
+
263
+ def __new__(cls):
264
+ obj = Basic.__new__(cls)
265
+ return obj
266
+
267
+ @property
268
+ def dimension(self):
269
+ return S.Infinity
270
+
271
+ def _sympyrepr(self, printer, *args):
272
+ return "FockSpace()"
273
+
274
+ def _sympystr(self, printer, *args):
275
+ return "F"
276
+
277
+ def _pretty(self, printer, *args):
278
+ ustr = '\N{LATIN CAPITAL LETTER F}'
279
+ return prettyForm(ustr)
280
+
281
+ def _latex(self, printer, *args):
282
+ return r'\mathcal{F}'
283
+
284
+
285
+ class TensorProductHilbertSpace(HilbertSpace):
286
+ """A tensor product of Hilbert spaces [1]_.
287
+
288
+ The tensor product between Hilbert spaces is represented by the
289
+ operator ``*`` Products of the same Hilbert space will be combined into
290
+ tensor powers.
291
+
292
+ A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
293
+ ``HilbertSpace`` objects as its arguments. In addition, multiplication of
294
+ ``HilbertSpace`` objects will automatically return this tensor product
295
+ object.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
301
+ >>> from sympy import symbols
302
+
303
+ >>> c = ComplexSpace(2)
304
+ >>> f = FockSpace()
305
+ >>> hs = c*f
306
+ >>> hs
307
+ C(2)*F
308
+ >>> hs.dimension
309
+ oo
310
+ >>> hs.spaces
311
+ (C(2), F)
312
+
313
+ >>> c1 = ComplexSpace(2)
314
+ >>> n = symbols('n')
315
+ >>> c2 = ComplexSpace(n)
316
+ >>> hs = c1*c2
317
+ >>> hs
318
+ C(2)*C(n)
319
+ >>> hs.dimension
320
+ 2*n
321
+
322
+ References
323
+ ==========
324
+
325
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
326
+ """
327
+
328
+ def __new__(cls, *args):
329
+ r = cls.eval(args)
330
+ if isinstance(r, Basic):
331
+ return r
332
+ obj = Basic.__new__(cls, *args)
333
+ return obj
334
+
335
+ @classmethod
336
+ def eval(cls, args):
337
+ """Evaluates the direct product."""
338
+ new_args = []
339
+ recall = False
340
+ #flatten arguments
341
+ for arg in args:
342
+ if isinstance(arg, TensorProductHilbertSpace):
343
+ new_args.extend(arg.args)
344
+ recall = True
345
+ elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
346
+ new_args.append(arg)
347
+ else:
348
+ raise TypeError('Hilbert spaces can only be multiplied by \
349
+ other Hilbert spaces: %r' % arg)
350
+ #combine like arguments into direct powers
351
+ comb_args = []
352
+ prev_arg = None
353
+ for new_arg in new_args:
354
+ if prev_arg is not None:
355
+ if isinstance(new_arg, TensorPowerHilbertSpace) and \
356
+ isinstance(prev_arg, TensorPowerHilbertSpace) and \
357
+ new_arg.base == prev_arg.base:
358
+ prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
359
+ elif isinstance(new_arg, TensorPowerHilbertSpace) and \
360
+ new_arg.base == prev_arg:
361
+ prev_arg = prev_arg**(new_arg.exp + 1)
362
+ elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
363
+ new_arg == prev_arg.base:
364
+ prev_arg = new_arg**(prev_arg.exp + 1)
365
+ elif new_arg == prev_arg:
366
+ prev_arg = new_arg**2
367
+ else:
368
+ comb_args.append(prev_arg)
369
+ prev_arg = new_arg
370
+ elif prev_arg is None:
371
+ prev_arg = new_arg
372
+ comb_args.append(prev_arg)
373
+ if recall:
374
+ return TensorProductHilbertSpace(*comb_args)
375
+ elif len(comb_args) == 1:
376
+ return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
377
+ else:
378
+ return None
379
+
380
+ @property
381
+ def dimension(self):
382
+ arg_list = [arg.dimension for arg in self.args]
383
+ if S.Infinity in arg_list:
384
+ return S.Infinity
385
+ else:
386
+ return reduce(lambda x, y: x*y, arg_list)
387
+
388
+ @property
389
+ def spaces(self):
390
+ """A tuple of the Hilbert spaces in this tensor product."""
391
+ return self.args
392
+
393
+ def _spaces_printer(self, printer, *args):
394
+ spaces_strs = []
395
+ for arg in self.args:
396
+ s = printer._print(arg, *args)
397
+ if isinstance(arg, DirectSumHilbertSpace):
398
+ s = '(%s)' % s
399
+ spaces_strs.append(s)
400
+ return spaces_strs
401
+
402
+ def _sympyrepr(self, printer, *args):
403
+ spaces_reprs = self._spaces_printer(printer, *args)
404
+ return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
405
+
406
+ def _sympystr(self, printer, *args):
407
+ spaces_strs = self._spaces_printer(printer, *args)
408
+ return '*'.join(spaces_strs)
409
+
410
+ def _pretty(self, printer, *args):
411
+ length = len(self.args)
412
+ pform = printer._print('', *args)
413
+ for i in range(length):
414
+ next_pform = printer._print(self.args[i], *args)
415
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
416
+ TensorProductHilbertSpace)):
417
+ next_pform = prettyForm(
418
+ *next_pform.parens(left='(', right=')')
419
+ )
420
+ pform = prettyForm(*pform.right(next_pform))
421
+ if i != length - 1:
422
+ if printer._use_unicode:
423
+ pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
424
+ else:
425
+ pform = prettyForm(*pform.right(' x '))
426
+ return pform
427
+
428
+ def _latex(self, printer, *args):
429
+ length = len(self.args)
430
+ s = ''
431
+ for i in range(length):
432
+ arg_s = printer._print(self.args[i], *args)
433
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
434
+ TensorProductHilbertSpace)):
435
+ arg_s = r'\left(%s\right)' % arg_s
436
+ s = s + arg_s
437
+ if i != length - 1:
438
+ s = s + r'\otimes '
439
+ return s
440
+
441
+
442
+ class DirectSumHilbertSpace(HilbertSpace):
443
+ """A direct sum of Hilbert spaces [1]_.
444
+
445
+ This class uses the ``+`` operator to represent direct sums between
446
+ different Hilbert spaces.
447
+
448
+ A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
449
+ ``HilbertSpace`` objects as its arguments. Also, addition of
450
+ ``HilbertSpace`` objects will automatically return a direct sum object.
451
+
452
+ Examples
453
+ ========
454
+
455
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
456
+
457
+ >>> c = ComplexSpace(2)
458
+ >>> f = FockSpace()
459
+ >>> hs = c+f
460
+ >>> hs
461
+ C(2)+F
462
+ >>> hs.dimension
463
+ oo
464
+ >>> list(hs.spaces)
465
+ [C(2), F]
466
+
467
+ References
468
+ ==========
469
+
470
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
471
+ """
472
+ def __new__(cls, *args):
473
+ r = cls.eval(args)
474
+ if isinstance(r, Basic):
475
+ return r
476
+ obj = Basic.__new__(cls, *args)
477
+ return obj
478
+
479
+ @classmethod
480
+ def eval(cls, args):
481
+ """Evaluates the direct product."""
482
+ new_args = []
483
+ recall = False
484
+ #flatten arguments
485
+ for arg in args:
486
+ if isinstance(arg, DirectSumHilbertSpace):
487
+ new_args.extend(arg.args)
488
+ recall = True
489
+ elif isinstance(arg, HilbertSpace):
490
+ new_args.append(arg)
491
+ else:
492
+ raise TypeError('Hilbert spaces can only be summed with other \
493
+ Hilbert spaces: %r' % arg)
494
+ if recall:
495
+ return DirectSumHilbertSpace(*new_args)
496
+ else:
497
+ return None
498
+
499
+ @property
500
+ def dimension(self):
501
+ arg_list = [arg.dimension for arg in self.args]
502
+ if S.Infinity in arg_list:
503
+ return S.Infinity
504
+ else:
505
+ return reduce(lambda x, y: x + y, arg_list)
506
+
507
+ @property
508
+ def spaces(self):
509
+ """A tuple of the Hilbert spaces in this direct sum."""
510
+ return self.args
511
+
512
+ def _sympyrepr(self, printer, *args):
513
+ spaces_reprs = [printer._print(arg, *args) for arg in self.args]
514
+ return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
515
+
516
+ def _sympystr(self, printer, *args):
517
+ spaces_strs = [printer._print(arg, *args) for arg in self.args]
518
+ return '+'.join(spaces_strs)
519
+
520
+ def _pretty(self, printer, *args):
521
+ length = len(self.args)
522
+ pform = printer._print('', *args)
523
+ for i in range(length):
524
+ next_pform = printer._print(self.args[i], *args)
525
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
526
+ TensorProductHilbertSpace)):
527
+ next_pform = prettyForm(
528
+ *next_pform.parens(left='(', right=')')
529
+ )
530
+ pform = prettyForm(*pform.right(next_pform))
531
+ if i != length - 1:
532
+ if printer._use_unicode:
533
+ pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
534
+ else:
535
+ pform = prettyForm(*pform.right(' + '))
536
+ return pform
537
+
538
+ def _latex(self, printer, *args):
539
+ length = len(self.args)
540
+ s = ''
541
+ for i in range(length):
542
+ arg_s = printer._print(self.args[i], *args)
543
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
544
+ TensorProductHilbertSpace)):
545
+ arg_s = r'\left(%s\right)' % arg_s
546
+ s = s + arg_s
547
+ if i != length - 1:
548
+ s = s + r'\oplus '
549
+ return s
550
+
551
+
552
+ class TensorPowerHilbertSpace(HilbertSpace):
553
+ """An exponentiated Hilbert space [1]_.
554
+
555
+ Tensor powers (repeated tensor products) are represented by the
556
+ operator ``**`` Identical Hilbert spaces that are multiplied together
557
+ will be automatically combined into a single tensor power object.
558
+
559
+ Any Hilbert space, product, or sum may be raised to a tensor power. The
560
+ ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
561
+ tensor power (number).
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
567
+ >>> from sympy import symbols
568
+
569
+ >>> n = symbols('n')
570
+ >>> c = ComplexSpace(2)
571
+ >>> hs = c**n
572
+ >>> hs
573
+ C(2)**n
574
+ >>> hs.dimension
575
+ 2**n
576
+
577
+ >>> c = ComplexSpace(2)
578
+ >>> c*c
579
+ C(2)**2
580
+ >>> f = FockSpace()
581
+ >>> c*f*f
582
+ C(2)*F**2
583
+
584
+ References
585
+ ==========
586
+
587
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
588
+ """
589
+
590
+ def __new__(cls, *args):
591
+ r = cls.eval(args)
592
+ if isinstance(r, Basic):
593
+ return r
594
+ return Basic.__new__(cls, *r)
595
+
596
+ @classmethod
597
+ def eval(cls, args):
598
+ new_args = args[0], sympify(args[1])
599
+ exp = new_args[1]
600
+ #simplify hs**1 -> hs
601
+ if exp is S.One:
602
+ return args[0]
603
+ #simplify hs**0 -> 1
604
+ if exp is S.Zero:
605
+ return S.One
606
+ #check (and allow) for hs**(x+42+y...) case
607
+ if len(exp.atoms()) == 1:
608
+ if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
609
+ raise ValueError('Hilbert spaces can only be raised to \
610
+ positive integers or Symbols: %r' % exp)
611
+ else:
612
+ for power in exp.atoms():
613
+ if not (power.is_Integer or power.is_Symbol):
614
+ raise ValueError('Tensor powers can only contain integers \
615
+ or Symbols: %r' % power)
616
+ return new_args
617
+
618
+ @property
619
+ def base(self):
620
+ return self.args[0]
621
+
622
+ @property
623
+ def exp(self):
624
+ return self.args[1]
625
+
626
+ @property
627
+ def dimension(self):
628
+ if self.base.dimension is S.Infinity:
629
+ return S.Infinity
630
+ else:
631
+ return self.base.dimension**self.exp
632
+
633
+ def _sympyrepr(self, printer, *args):
634
+ return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
635
+ *args), printer._print(self.exp, *args))
636
+
637
+ def _sympystr(self, printer, *args):
638
+ return "%s**%s" % (printer._print(self.base, *args),
639
+ printer._print(self.exp, *args))
640
+
641
+ def _pretty(self, printer, *args):
642
+ pform_exp = printer._print(self.exp, *args)
643
+ if printer._use_unicode:
644
+ pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
645
+ else:
646
+ pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
647
+ pform_base = printer._print(self.base, *args)
648
+ return pform_base**pform_exp
649
+
650
+ def _latex(self, printer, *args):
651
+ base = printer._print(self.base, *args)
652
+ exp = printer._print(self.exp, *args)
653
+ return r'{%s}^{\otimes %s}' % (base, exp)
pllava/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]]))
pllava/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.matrixbase 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
pllava/lib/python3.10/site-packages/sympy/physics/quantum/operator.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Optional
12
+
13
+ from sympy.core.add import Add
14
+ from sympy.core.expr import Expr
15
+ from sympy.core.function import (Derivative, expand)
16
+ from sympy.core.mul import Mul
17
+ from sympy.core.numbers import oo
18
+ from sympy.core.singleton import S
19
+ from sympy.printing.pretty.stringpict import prettyForm
20
+ from sympy.physics.quantum.dagger import Dagger
21
+ from sympy.physics.quantum.qexpr import QExpr, dispatch_method
22
+ from sympy.matrices import eye
23
+
24
+ __all__ = [
25
+ 'Operator',
26
+ 'HermitianOperator',
27
+ 'UnitaryOperator',
28
+ 'IdentityOperator',
29
+ 'OuterProduct',
30
+ 'DifferentialOperator'
31
+ ]
32
+
33
+ #-----------------------------------------------------------------------------
34
+ # Operators and outer products
35
+ #-----------------------------------------------------------------------------
36
+
37
+
38
+ class Operator(QExpr):
39
+ """Base class for non-commuting quantum operators.
40
+
41
+ An operator maps between quantum states [1]_. In quantum mechanics,
42
+ observables (including, but not limited to, measured physical values) are
43
+ represented as Hermitian operators [2]_.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ args : tuple
49
+ The list of numbers or parameters that uniquely specify the
50
+ operator. For time-dependent operators, this will include the time.
51
+
52
+ Examples
53
+ ========
54
+
55
+ Create an operator and examine its attributes::
56
+
57
+ >>> from sympy.physics.quantum import Operator
58
+ >>> from sympy import I
59
+ >>> A = Operator('A')
60
+ >>> A
61
+ A
62
+ >>> A.hilbert_space
63
+ H
64
+ >>> A.label
65
+ (A,)
66
+ >>> A.is_commutative
67
+ False
68
+
69
+ Create another operator and do some arithmetic operations::
70
+
71
+ >>> B = Operator('B')
72
+ >>> C = 2*A*A + I*B
73
+ >>> C
74
+ 2*A**2 + I*B
75
+
76
+ Operators do not commute::
77
+
78
+ >>> A.is_commutative
79
+ False
80
+ >>> B.is_commutative
81
+ False
82
+ >>> A*B == B*A
83
+ False
84
+
85
+ Polymonials of operators respect the commutation properties::
86
+
87
+ >>> e = (A+B)**3
88
+ >>> e.expand()
89
+ A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3
90
+
91
+ Operator inverses are handle symbolically::
92
+
93
+ >>> A.inv()
94
+ A**(-1)
95
+ >>> A*A.inv()
96
+ 1
97
+
98
+ References
99
+ ==========
100
+
101
+ .. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29
102
+ .. [2] https://en.wikipedia.org/wiki/Observable
103
+ """
104
+ is_hermitian: Optional[bool] = None
105
+ is_unitary: Optional[bool] = None
106
+ @classmethod
107
+ def default_args(self):
108
+ return ("O",)
109
+
110
+ #-------------------------------------------------------------------------
111
+ # Printing
112
+ #-------------------------------------------------------------------------
113
+
114
+ _label_separator = ','
115
+
116
+ def _print_operator_name(self, printer, *args):
117
+ return self.__class__.__name__
118
+
119
+ _print_operator_name_latex = _print_operator_name
120
+
121
+ def _print_operator_name_pretty(self, printer, *args):
122
+ return prettyForm(self.__class__.__name__)
123
+
124
+ def _print_contents(self, printer, *args):
125
+ if len(self.label) == 1:
126
+ return self._print_label(printer, *args)
127
+ else:
128
+ return '%s(%s)' % (
129
+ self._print_operator_name(printer, *args),
130
+ self._print_label(printer, *args)
131
+ )
132
+
133
+ def _print_contents_pretty(self, printer, *args):
134
+ if len(self.label) == 1:
135
+ return self._print_label_pretty(printer, *args)
136
+ else:
137
+ pform = self._print_operator_name_pretty(printer, *args)
138
+ label_pform = self._print_label_pretty(printer, *args)
139
+ label_pform = prettyForm(
140
+ *label_pform.parens(left='(', right=')')
141
+ )
142
+ pform = prettyForm(*pform.right(label_pform))
143
+ return pform
144
+
145
+ def _print_contents_latex(self, printer, *args):
146
+ if len(self.label) == 1:
147
+ return self._print_label_latex(printer, *args)
148
+ else:
149
+ return r'%s\left(%s\right)' % (
150
+ self._print_operator_name_latex(printer, *args),
151
+ self._print_label_latex(printer, *args)
152
+ )
153
+
154
+ #-------------------------------------------------------------------------
155
+ # _eval_* methods
156
+ #-------------------------------------------------------------------------
157
+
158
+ def _eval_commutator(self, other, **options):
159
+ """Evaluate [self, other] if known, return None if not known."""
160
+ return dispatch_method(self, '_eval_commutator', other, **options)
161
+
162
+ def _eval_anticommutator(self, other, **options):
163
+ """Evaluate [self, other] if known."""
164
+ return dispatch_method(self, '_eval_anticommutator', other, **options)
165
+
166
+ #-------------------------------------------------------------------------
167
+ # Operator application
168
+ #-------------------------------------------------------------------------
169
+
170
+ def _apply_operator(self, ket, **options):
171
+ return dispatch_method(self, '_apply_operator', ket, **options)
172
+
173
+ def _apply_from_right_to(self, bra, **options):
174
+ return None
175
+
176
+ def matrix_element(self, *args):
177
+ raise NotImplementedError('matrix_elements is not defined')
178
+
179
+ def inverse(self):
180
+ return self._eval_inverse()
181
+
182
+ inv = inverse
183
+
184
+ def _eval_inverse(self):
185
+ return self**(-1)
186
+
187
+ def __mul__(self, other):
188
+
189
+ if isinstance(other, IdentityOperator):
190
+ return self
191
+
192
+ return Mul(self, other)
193
+
194
+
195
+ class HermitianOperator(Operator):
196
+ """A Hermitian operator that satisfies H == Dagger(H).
197
+
198
+ Parameters
199
+ ==========
200
+
201
+ args : tuple
202
+ The list of numbers or parameters that uniquely specify the
203
+ operator. For time-dependent operators, this will include the time.
204
+
205
+ Examples
206
+ ========
207
+
208
+ >>> from sympy.physics.quantum import Dagger, HermitianOperator
209
+ >>> H = HermitianOperator('H')
210
+ >>> Dagger(H)
211
+ H
212
+ """
213
+
214
+ is_hermitian = True
215
+
216
+ def _eval_inverse(self):
217
+ if isinstance(self, UnitaryOperator):
218
+ return self
219
+ else:
220
+ return Operator._eval_inverse(self)
221
+
222
+ def _eval_power(self, exp):
223
+ if isinstance(self, UnitaryOperator):
224
+ # so all eigenvalues of self are 1 or -1
225
+ if exp.is_even:
226
+ from sympy.core.singleton import S
227
+ return S.One # is identity, see Issue 24153.
228
+ elif exp.is_odd:
229
+ return self
230
+ # No simplification in all other cases
231
+ return Operator._eval_power(self, exp)
232
+
233
+
234
+ class UnitaryOperator(Operator):
235
+ """A unitary operator that satisfies U*Dagger(U) == 1.
236
+
237
+ Parameters
238
+ ==========
239
+
240
+ args : tuple
241
+ The list of numbers or parameters that uniquely specify the
242
+ operator. For time-dependent operators, this will include the time.
243
+
244
+ Examples
245
+ ========
246
+
247
+ >>> from sympy.physics.quantum import Dagger, UnitaryOperator
248
+ >>> U = UnitaryOperator('U')
249
+ >>> U*Dagger(U)
250
+ 1
251
+ """
252
+ is_unitary = True
253
+ def _eval_adjoint(self):
254
+ return self._eval_inverse()
255
+
256
+
257
+ class IdentityOperator(Operator):
258
+ """An identity operator I that satisfies op * I == I * op == op for any
259
+ operator op.
260
+
261
+ Parameters
262
+ ==========
263
+
264
+ N : Integer
265
+ Optional parameter that specifies the dimension of the Hilbert space
266
+ of operator. This is used when generating a matrix representation.
267
+
268
+ Examples
269
+ ========
270
+
271
+ >>> from sympy.physics.quantum import IdentityOperator
272
+ >>> IdentityOperator()
273
+ I
274
+ """
275
+ is_hermitian = True
276
+ is_unitary = True
277
+ @property
278
+ def dimension(self):
279
+ return self.N
280
+
281
+ @classmethod
282
+ def default_args(self):
283
+ return (oo,)
284
+
285
+ def __init__(self, *args, **hints):
286
+ if not len(args) in (0, 1):
287
+ raise ValueError('0 or 1 parameters expected, got %s' % args)
288
+
289
+ self.N = args[0] if (len(args) == 1 and args[0]) else oo
290
+
291
+ def _eval_commutator(self, other, **hints):
292
+ return S.Zero
293
+
294
+ def _eval_anticommutator(self, other, **hints):
295
+ return 2 * other
296
+
297
+ def _eval_inverse(self):
298
+ return self
299
+
300
+ def _eval_adjoint(self):
301
+ return self
302
+
303
+ def _apply_operator(self, ket, **options):
304
+ return ket
305
+
306
+ def _apply_from_right_to(self, bra, **options):
307
+ return bra
308
+
309
+ def _eval_power(self, exp):
310
+ return self
311
+
312
+ def _print_contents(self, printer, *args):
313
+ return 'I'
314
+
315
+ def _print_contents_pretty(self, printer, *args):
316
+ return prettyForm('I')
317
+
318
+ def _print_contents_latex(self, printer, *args):
319
+ return r'{\mathcal{I}}'
320
+
321
+ def __mul__(self, other):
322
+
323
+ if isinstance(other, (Operator, Dagger)):
324
+ return other
325
+
326
+ return Mul(self, other)
327
+
328
+ def _represent_default_basis(self, **options):
329
+ if not self.N or self.N == oo:
330
+ raise NotImplementedError('Cannot represent infinite dimensional' +
331
+ ' identity operator as a matrix')
332
+
333
+ format = options.get('format', 'sympy')
334
+ if format != 'sympy':
335
+ raise NotImplementedError('Representation in format ' +
336
+ '%s not implemented.' % format)
337
+
338
+ return eye(self.N)
339
+
340
+
341
+ class OuterProduct(Operator):
342
+ """An unevaluated outer product between a ket and bra.
343
+
344
+ This constructs an outer product between any subclass of ``KetBase`` and
345
+ ``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as
346
+ operators in quantum expressions. For reference see [1]_.
347
+
348
+ Parameters
349
+ ==========
350
+
351
+ ket : KetBase
352
+ The ket on the left side of the outer product.
353
+ bar : BraBase
354
+ The bra on the right side of the outer product.
355
+
356
+ Examples
357
+ ========
358
+
359
+ Create a simple outer product by hand and take its dagger::
360
+
361
+ >>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger
362
+ >>> from sympy.physics.quantum import Operator
363
+
364
+ >>> k = Ket('k')
365
+ >>> b = Bra('b')
366
+ >>> op = OuterProduct(k, b)
367
+ >>> op
368
+ |k><b|
369
+ >>> op.hilbert_space
370
+ H
371
+ >>> op.ket
372
+ |k>
373
+ >>> op.bra
374
+ <b|
375
+ >>> Dagger(op)
376
+ |b><k|
377
+
378
+ In simple products of kets and bras outer products will be automatically
379
+ identified and created::
380
+
381
+ >>> k*b
382
+ |k><b|
383
+
384
+ But in more complex expressions, outer products are not automatically
385
+ created::
386
+
387
+ >>> A = Operator('A')
388
+ >>> A*k*b
389
+ A*|k>*<b|
390
+
391
+ A user can force the creation of an outer product in a complex expression
392
+ by using parentheses to group the ket and bra::
393
+
394
+ >>> A*(k*b)
395
+ A*|k><b|
396
+
397
+ References
398
+ ==========
399
+
400
+ .. [1] https://en.wikipedia.org/wiki/Outer_product
401
+ """
402
+ is_commutative = False
403
+
404
+ def __new__(cls, *args, **old_assumptions):
405
+ from sympy.physics.quantum.state import KetBase, BraBase
406
+
407
+ if len(args) != 2:
408
+ raise ValueError('2 parameters expected, got %d' % len(args))
409
+
410
+ ket_expr = expand(args[0])
411
+ bra_expr = expand(args[1])
412
+
413
+ if (isinstance(ket_expr, (KetBase, Mul)) and
414
+ isinstance(bra_expr, (BraBase, Mul))):
415
+ ket_c, kets = ket_expr.args_cnc()
416
+ bra_c, bras = bra_expr.args_cnc()
417
+
418
+ if len(kets) != 1 or not isinstance(kets[0], KetBase):
419
+ raise TypeError('KetBase subclass expected'
420
+ ', got: %r' % Mul(*kets))
421
+
422
+ if len(bras) != 1 or not isinstance(bras[0], BraBase):
423
+ raise TypeError('BraBase subclass expected'
424
+ ', got: %r' % Mul(*bras))
425
+
426
+ if not kets[0].dual_class() == bras[0].__class__:
427
+ raise TypeError(
428
+ 'ket and bra are not dual classes: %r, %r' %
429
+ (kets[0].__class__, bras[0].__class__)
430
+ )
431
+
432
+ # TODO: make sure the hilbert spaces of the bra and ket are
433
+ # compatible
434
+ obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions)
435
+ obj.hilbert_space = kets[0].hilbert_space
436
+ return Mul(*(ket_c + bra_c)) * obj
437
+
438
+ op_terms = []
439
+ if isinstance(ket_expr, Add) and isinstance(bra_expr, Add):
440
+ for ket_term in ket_expr.args:
441
+ for bra_term in bra_expr.args:
442
+ op_terms.append(OuterProduct(ket_term, bra_term,
443
+ **old_assumptions))
444
+ elif isinstance(ket_expr, Add):
445
+ for ket_term in ket_expr.args:
446
+ op_terms.append(OuterProduct(ket_term, bra_expr,
447
+ **old_assumptions))
448
+ elif isinstance(bra_expr, Add):
449
+ for bra_term in bra_expr.args:
450
+ op_terms.append(OuterProduct(ket_expr, bra_term,
451
+ **old_assumptions))
452
+ else:
453
+ raise TypeError(
454
+ 'Expected ket and bra expression, got: %r, %r' %
455
+ (ket_expr, bra_expr)
456
+ )
457
+
458
+ return Add(*op_terms)
459
+
460
+ @property
461
+ def ket(self):
462
+ """Return the ket on the left side of the outer product."""
463
+ return self.args[0]
464
+
465
+ @property
466
+ def bra(self):
467
+ """Return the bra on the right side of the outer product."""
468
+ return self.args[1]
469
+
470
+ def _eval_adjoint(self):
471
+ return OuterProduct(Dagger(self.bra), Dagger(self.ket))
472
+
473
+ def _sympystr(self, printer, *args):
474
+ return printer._print(self.ket) + printer._print(self.bra)
475
+
476
+ def _sympyrepr(self, printer, *args):
477
+ return '%s(%s,%s)' % (self.__class__.__name__,
478
+ printer._print(self.ket, *args), printer._print(self.bra, *args))
479
+
480
+ def _pretty(self, printer, *args):
481
+ pform = self.ket._pretty(printer, *args)
482
+ return prettyForm(*pform.right(self.bra._pretty(printer, *args)))
483
+
484
+ def _latex(self, printer, *args):
485
+ k = printer._print(self.ket, *args)
486
+ b = printer._print(self.bra, *args)
487
+ return k + b
488
+
489
+ def _represent(self, **options):
490
+ k = self.ket._represent(**options)
491
+ b = self.bra._represent(**options)
492
+ return k*b
493
+
494
+ def _eval_trace(self, **kwargs):
495
+ # TODO if operands are tensorproducts this may be will be handled
496
+ # differently.
497
+
498
+ return self.ket._eval_trace(self.bra, **kwargs)
499
+
500
+
501
+ class DifferentialOperator(Operator):
502
+ """An operator for representing the differential operator, i.e. d/dx
503
+
504
+ It is initialized by passing two arguments. The first is an arbitrary
505
+ expression that involves a function, such as ``Derivative(f(x), x)``. The
506
+ second is the function (e.g. ``f(x)``) which we are to replace with the
507
+ ``Wavefunction`` that this ``DifferentialOperator`` is applied to.
508
+
509
+ Parameters
510
+ ==========
511
+
512
+ expr : Expr
513
+ The arbitrary expression which the appropriate Wavefunction is to be
514
+ substituted into
515
+
516
+ func : Expr
517
+ A function (e.g. f(x)) which is to be replaced with the appropriate
518
+ Wavefunction when this DifferentialOperator is applied
519
+
520
+ Examples
521
+ ========
522
+
523
+ You can define a completely arbitrary expression and specify where the
524
+ Wavefunction is to be substituted
525
+
526
+ >>> from sympy import Derivative, Function, Symbol
527
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
528
+ >>> from sympy.physics.quantum.state import Wavefunction
529
+ >>> from sympy.physics.quantum.qapply import qapply
530
+ >>> f = Function('f')
531
+ >>> x = Symbol('x')
532
+ >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
533
+ >>> w = Wavefunction(x**2, x)
534
+ >>> d.function
535
+ f(x)
536
+ >>> d.variables
537
+ (x,)
538
+ >>> qapply(d*w)
539
+ Wavefunction(2, x)
540
+
541
+ """
542
+
543
+ @property
544
+ def variables(self):
545
+ """
546
+ Returns the variables with which the function in the specified
547
+ arbitrary expression is evaluated
548
+
549
+ Examples
550
+ ========
551
+
552
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
553
+ >>> from sympy import Symbol, Function, Derivative
554
+ >>> x = Symbol('x')
555
+ >>> f = Function('f')
556
+ >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x))
557
+ >>> d.variables
558
+ (x,)
559
+ >>> y = Symbol('y')
560
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
561
+ ... Derivative(f(x, y), y), f(x, y))
562
+ >>> d.variables
563
+ (x, y)
564
+ """
565
+
566
+ return self.args[-1].args
567
+
568
+ @property
569
+ def function(self):
570
+ """
571
+ Returns the function which is to be replaced with the Wavefunction
572
+
573
+ Examples
574
+ ========
575
+
576
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
577
+ >>> from sympy import Function, Symbol, Derivative
578
+ >>> x = Symbol('x')
579
+ >>> f = Function('f')
580
+ >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
581
+ >>> d.function
582
+ f(x)
583
+ >>> y = Symbol('y')
584
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
585
+ ... Derivative(f(x, y), y), f(x, y))
586
+ >>> d.function
587
+ f(x, y)
588
+ """
589
+
590
+ return self.args[-1]
591
+
592
+ @property
593
+ def expr(self):
594
+ """
595
+ Returns the arbitrary expression which is to have the Wavefunction
596
+ substituted into it
597
+
598
+ Examples
599
+ ========
600
+
601
+ >>> from sympy.physics.quantum.operator import DifferentialOperator
602
+ >>> from sympy import Function, Symbol, Derivative
603
+ >>> x = Symbol('x')
604
+ >>> f = Function('f')
605
+ >>> d = DifferentialOperator(Derivative(f(x), x), f(x))
606
+ >>> d.expr
607
+ Derivative(f(x), x)
608
+ >>> y = Symbol('y')
609
+ >>> d = DifferentialOperator(Derivative(f(x, y), x) +
610
+ ... Derivative(f(x, y), y), f(x, y))
611
+ >>> d.expr
612
+ Derivative(f(x, y), x) + Derivative(f(x, y), y)
613
+ """
614
+
615
+ return self.args[0]
616
+
617
+ @property
618
+ def free_symbols(self):
619
+ """
620
+ Return the free symbols of the expression.
621
+ """
622
+
623
+ return self.expr.free_symbols
624
+
625
+ def _apply_operator_Wavefunction(self, func, **options):
626
+ from sympy.physics.quantum.state import Wavefunction
627
+ var = self.variables
628
+ wf_vars = func.args[1:]
629
+
630
+ f = self.function
631
+ new_expr = self.expr.subs(f, func(*var))
632
+ new_expr = new_expr.doit()
633
+
634
+ return Wavefunction(new_expr, *wf_vars)
635
+
636
+ def _eval_derivative(self, symbol):
637
+ new_expr = Derivative(self.expr, symbol)
638
+ return DifferentialOperator(new_expr, self.args[-1])
639
+
640
+ #-------------------------------------------------------------------------
641
+ # Printing
642
+ #-------------------------------------------------------------------------
643
+
644
+ def _print(self, printer, *args):
645
+ return '%s(%s)' % (
646
+ self._print_operator_name(printer, *args),
647
+ self._print_label(printer, *args)
648
+ )
649
+
650
+ def _print_pretty(self, printer, *args):
651
+ pform = self._print_operator_name_pretty(printer, *args)
652
+ label_pform = self._print_label_pretty(printer, *args)
653
+ label_pform = prettyForm(
654
+ *label_pform.parens(left='(', right=')')
655
+ )
656
+ pform = prettyForm(*pform.right(label_pform))
657
+ return pform
pllava/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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
+ def _normal_ordered_form_factor(product, independent=False, recursive_limit=10,
39
+ _recursive_depth=0):
40
+ """
41
+ Helper function for normal_ordered_form_factor: Write multiplication
42
+ expression with bosonic or fermionic operators on normally ordered form,
43
+ using the bosonic and fermionic commutation relations. The resulting
44
+ operator expression is equivalent to the argument, but will in general be
45
+ a sum of operator products instead of a simple product.
46
+ """
47
+
48
+ factors = _expand_powers(product)
49
+
50
+ new_factors = []
51
+ n = 0
52
+ while n < len(factors) - 1:
53
+ current, next = factors[n], factors[n + 1]
54
+ if any(not isinstance(f, (FermionOp, BosonOp)) for f in (current, next)):
55
+ new_factors.append(current)
56
+ n += 1
57
+ continue
58
+
59
+ key_1 = (current.is_annihilation, str(current.name))
60
+ key_2 = (next.is_annihilation, str(next.name))
61
+
62
+ if key_1 <= key_2:
63
+ new_factors.append(current)
64
+ n += 1
65
+ continue
66
+
67
+ n += 2
68
+ if current.is_annihilation and not next.is_annihilation:
69
+ if isinstance(current, BosonOp) and isinstance(next, BosonOp):
70
+ if current.args[0] != next.args[0]:
71
+ if independent:
72
+ c = 0
73
+ else:
74
+ c = Commutator(current, next)
75
+ new_factors.append(next * current + c)
76
+ else:
77
+ new_factors.append(next * current + 1)
78
+ elif isinstance(current, FermionOp) and isinstance(next, FermionOp):
79
+ if current.args[0] != next.args[0]:
80
+ if independent:
81
+ c = 0
82
+ else:
83
+ c = AntiCommutator(current, next)
84
+ new_factors.append(-next * current + c)
85
+ else:
86
+ new_factors.append(-next * current + 1)
87
+ elif (current.is_annihilation == next.is_annihilation and
88
+ isinstance(current, FermionOp) and isinstance(next, FermionOp)):
89
+ new_factors.append(-next * current)
90
+ else:
91
+ new_factors.append(next * current)
92
+
93
+ if n == len(factors) - 1:
94
+ new_factors.append(factors[-1])
95
+
96
+ if new_factors == factors:
97
+ return product
98
+ else:
99
+ expr = Mul(*new_factors).expand()
100
+ return normal_ordered_form(expr,
101
+ recursive_limit=recursive_limit,
102
+ _recursive_depth=_recursive_depth + 1,
103
+ independent=independent)
104
+
105
+
106
+ def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10,
107
+ _recursive_depth=0):
108
+ """
109
+ Helper function for normal_ordered_form: loop through each term in an
110
+ addition expression and call _normal_ordered_form_factor to perform the
111
+ factor to an normally ordered expression.
112
+ """
113
+
114
+ new_terms = []
115
+ for term in expr.args:
116
+ if isinstance(term, Mul):
117
+ new_term = _normal_ordered_form_factor(
118
+ term, recursive_limit=recursive_limit,
119
+ _recursive_depth=_recursive_depth, independent=independent)
120
+ new_terms.append(new_term)
121
+ else:
122
+ new_terms.append(term)
123
+
124
+ return Add(*new_terms)
125
+
126
+
127
+ def normal_ordered_form(expr, independent=False, recursive_limit=10,
128
+ _recursive_depth=0):
129
+ """Write an expression with bosonic or fermionic operators on normal
130
+ ordered form, where each term is normally ordered. Note that this
131
+ normal ordered form is equivalent to the original expression.
132
+
133
+ Parameters
134
+ ==========
135
+
136
+ expr : expression
137
+ The expression write on normal ordered form.
138
+ independent : bool (default False)
139
+ Whether to consider operator with different names as operating in
140
+ different Hilbert spaces. If False, the (anti-)commutation is left
141
+ explicit.
142
+ recursive_limit : int (default 10)
143
+ The number of allowed recursive applications of the function.
144
+
145
+ Examples
146
+ ========
147
+
148
+ >>> from sympy.physics.quantum import Dagger
149
+ >>> from sympy.physics.quantum.boson import BosonOp
150
+ >>> from sympy.physics.quantum.operatorordering import normal_ordered_form
151
+ >>> a = BosonOp("a")
152
+ >>> normal_ordered_form(a * Dagger(a))
153
+ 1 + Dagger(a)*a
154
+ """
155
+
156
+ if _recursive_depth > recursive_limit:
157
+ warnings.warn("Too many recursions, aborting")
158
+ return expr
159
+
160
+ if isinstance(expr, Add):
161
+ return _normal_ordered_form_terms(expr,
162
+ recursive_limit=recursive_limit,
163
+ _recursive_depth=_recursive_depth,
164
+ independent=independent)
165
+ elif isinstance(expr, Mul):
166
+ return _normal_ordered_form_factor(expr,
167
+ recursive_limit=recursive_limit,
168
+ _recursive_depth=_recursive_depth,
169
+ independent=independent)
170
+ else:
171
+ return expr
172
+
173
+
174
+ def _normal_order_factor(product, recursive_limit=10, _recursive_depth=0):
175
+ """
176
+ Helper function for normal_order: Normal order a multiplication expression
177
+ with bosonic or fermionic operators. In general the resulting operator
178
+ expression will not be equivalent to original product.
179
+ """
180
+
181
+ factors = _expand_powers(product)
182
+
183
+ n = 0
184
+ new_factors = []
185
+ while n < len(factors) - 1:
186
+
187
+ if (isinstance(factors[n], BosonOp) and
188
+ factors[n].is_annihilation):
189
+ # boson
190
+ if not isinstance(factors[n + 1], BosonOp):
191
+ new_factors.append(factors[n])
192
+ else:
193
+ if factors[n + 1].is_annihilation:
194
+ new_factors.append(factors[n])
195
+ else:
196
+ if factors[n].args[0] != factors[n + 1].args[0]:
197
+ new_factors.append(factors[n + 1] * factors[n])
198
+ else:
199
+ new_factors.append(factors[n + 1] * factors[n])
200
+ n += 1
201
+
202
+ elif (isinstance(factors[n], FermionOp) and
203
+ factors[n].is_annihilation):
204
+ # fermion
205
+ if not isinstance(factors[n + 1], FermionOp):
206
+ new_factors.append(factors[n])
207
+ else:
208
+ if factors[n + 1].is_annihilation:
209
+ new_factors.append(factors[n])
210
+ else:
211
+ if factors[n].args[0] != factors[n + 1].args[0]:
212
+ new_factors.append(-factors[n + 1] * factors[n])
213
+ else:
214
+ new_factors.append(-factors[n + 1] * factors[n])
215
+ n += 1
216
+
217
+ else:
218
+ new_factors.append(factors[n])
219
+
220
+ n += 1
221
+
222
+ if n == len(factors) - 1:
223
+ new_factors.append(factors[-1])
224
+
225
+ if new_factors == factors:
226
+ return product
227
+ else:
228
+ expr = Mul(*new_factors).expand()
229
+ return normal_order(expr,
230
+ recursive_limit=recursive_limit,
231
+ _recursive_depth=_recursive_depth + 1)
232
+
233
+
234
+ def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0):
235
+ """
236
+ Helper function for normal_order: look through each term in an addition
237
+ expression and call _normal_order_factor to perform the normal ordering
238
+ on the factors.
239
+ """
240
+
241
+ new_terms = []
242
+ for term in expr.args:
243
+ if isinstance(term, Mul):
244
+ new_term = _normal_order_factor(term,
245
+ recursive_limit=recursive_limit,
246
+ _recursive_depth=_recursive_depth)
247
+ new_terms.append(new_term)
248
+ else:
249
+ new_terms.append(term)
250
+
251
+ return Add(*new_terms)
252
+
253
+
254
+ def normal_order(expr, recursive_limit=10, _recursive_depth=0):
255
+ """Normal order an expression with bosonic or fermionic operators. Note
256
+ that this normal order is not equivalent to the original expression, but
257
+ the creation and annihilation operators in each term in expr is reordered
258
+ so that the expression becomes normal ordered.
259
+
260
+ Parameters
261
+ ==========
262
+
263
+ expr : expression
264
+ The expression to normal order.
265
+
266
+ recursive_limit : int (default 10)
267
+ The number of allowed recursive applications of the function.
268
+
269
+ Examples
270
+ ========
271
+
272
+ >>> from sympy.physics.quantum import Dagger
273
+ >>> from sympy.physics.quantum.boson import BosonOp
274
+ >>> from sympy.physics.quantum.operatorordering import normal_order
275
+ >>> a = BosonOp("a")
276
+ >>> normal_order(a * Dagger(a))
277
+ Dagger(a)*a
278
+ """
279
+ if _recursive_depth > recursive_limit:
280
+ warnings.warn("Too many recursions, aborting")
281
+ return expr
282
+
283
+ if isinstance(expr, Add):
284
+ return _normal_order_terms(expr, recursive_limit=recursive_limit,
285
+ _recursive_depth=_recursive_depth)
286
+ elif isinstance(expr, Mul):
287
+ return _normal_order_factor(expr, recursive_limit=recursive_limit,
288
+ _recursive_depth=_recursive_depth)
289
+ else:
290
+ return expr
pllava/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
pllava/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
pllava/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
184
+ result = None
185
+
186
+ if result is None:
187
+ _apply_right = getattr(rhs, '_apply_from_right_to', None)
188
+ if _apply_right is not None:
189
+ try:
190
+ result = _apply_right(lhs, **options)
191
+ except NotImplementedError:
192
+ result = None
193
+
194
+ if result is None:
195
+ if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
196
+ result = InnerProduct(lhs, rhs)
197
+ if ip_doit:
198
+ result = result.doit()
199
+
200
+ # TODO: I may need to expand before returning the final result.
201
+ if result == 0:
202
+ return S.Zero
203
+ elif result is None:
204
+ if len(args) == 0:
205
+ # We had two args to begin with so args=[].
206
+ return e
207
+ else:
208
+ return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs
209
+ elif isinstance(result, InnerProduct):
210
+ return result*qapply_Mul(e.func(*args), **options)
211
+ else: # result is a scalar times a Mul, Add or TensorProduct
212
+ return qapply(e.func(*args)*result, **options)
pllava/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
+ )
pllava/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.log2(size) + .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.log2(max(m.shape)) + .1)))
808
+ else:
809
+ raise NotImplementedError(
810
+ "This function cannot handle non-SymPy matrix formats yet"
811
+ )
pllava/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
pllava/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')
pllava/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.intfunc 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
pllava/lib/python3.10/site-packages/sympy/physics/quantum/spin.py ADDED
@@ -0,0 +1,2150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.numbers import int_valued
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.numbers import (I, Integer, Rational, pi)
10
+ from sympy.core.singleton import S
11
+ from sympy.core.symbol import (Dummy, symbols)
12
+ from sympy.core.sympify import sympify
13
+ from sympy.functions.combinatorial.factorials import (binomial, factorial)
14
+ from sympy.functions.elementary.exponential import exp
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.functions.elementary.trigonometric import (cos, sin)
17
+ from sympy.simplify.simplify import simplify
18
+ from sympy.matrices import zeros
19
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
20
+ from sympy.printing.pretty.pretty_symbology import pretty_symbol
21
+
22
+ from sympy.physics.quantum.qexpr import QExpr
23
+ from sympy.physics.quantum.operator import (HermitianOperator, Operator,
24
+ UnitaryOperator)
25
+ from sympy.physics.quantum.state import Bra, Ket, State
26
+ from sympy.functions.special.tensor_functions import KroneckerDelta
27
+ from sympy.physics.quantum.constants import hbar
28
+ from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
29
+ from sympy.physics.quantum.tensorproduct import TensorProduct
30
+ from sympy.physics.quantum.cg import CG
31
+ from sympy.physics.quantum.qapply import qapply
32
+
33
+
34
+ __all__ = [
35
+ 'm_values',
36
+ 'Jplus',
37
+ 'Jminus',
38
+ 'Jx',
39
+ 'Jy',
40
+ 'Jz',
41
+ 'J2',
42
+ 'Rotation',
43
+ 'WignerD',
44
+ 'JxKet',
45
+ 'JxBra',
46
+ 'JyKet',
47
+ 'JyBra',
48
+ 'JzKet',
49
+ 'JzBra',
50
+ 'JzOp',
51
+ 'J2Op',
52
+ 'JxKetCoupled',
53
+ 'JxBraCoupled',
54
+ 'JyKetCoupled',
55
+ 'JyBraCoupled',
56
+ 'JzKetCoupled',
57
+ 'JzBraCoupled',
58
+ 'couple',
59
+ 'uncouple'
60
+ ]
61
+
62
+
63
+ def m_values(j):
64
+ j = sympify(j)
65
+ size = 2*j + 1
66
+ if not size.is_Integer or not size > 0:
67
+ raise ValueError(
68
+ 'Only integer or half-integer values allowed for j, got: : %r' % j
69
+ )
70
+ return size, [j - i for i in range(int(2*j + 1))]
71
+
72
+
73
+ #-----------------------------------------------------------------------------
74
+ # Spin Operators
75
+ #-----------------------------------------------------------------------------
76
+
77
+
78
+ class SpinOpBase:
79
+ """Base class for spin operators."""
80
+
81
+ @classmethod
82
+ def _eval_hilbert_space(cls, label):
83
+ # We consider all j values so our space is infinite.
84
+ return ComplexSpace(S.Infinity)
85
+
86
+ @property
87
+ def name(self):
88
+ return self.args[0]
89
+
90
+ def _print_contents(self, printer, *args):
91
+ return '%s%s' % (self.name, self._coord)
92
+
93
+ def _print_contents_pretty(self, printer, *args):
94
+ a = stringPict(str(self.name))
95
+ b = stringPict(self._coord)
96
+ return self._print_subscript_pretty(a, b)
97
+
98
+ def _print_contents_latex(self, printer, *args):
99
+ return r'%s_%s' % ((self.name, self._coord))
100
+
101
+ def _represent_base(self, basis, **options):
102
+ j = options.get('j', S.Half)
103
+ size, mvals = m_values(j)
104
+ result = zeros(size, size)
105
+ for p in range(size):
106
+ for q in range(size):
107
+ me = self.matrix_element(j, mvals[p], j, mvals[q])
108
+ result[p, q] = me
109
+ return result
110
+
111
+ def _apply_op(self, ket, orig_basis, **options):
112
+ state = ket.rewrite(self.basis)
113
+ # If the state has only one term
114
+ if isinstance(state, State):
115
+ ret = (hbar*state.m)*state
116
+ # state is a linear combination of states
117
+ elif isinstance(state, Sum):
118
+ ret = self._apply_operator_Sum(state, **options)
119
+ else:
120
+ ret = qapply(self*state)
121
+ if ret == self*state:
122
+ raise NotImplementedError
123
+ return ret.rewrite(orig_basis)
124
+
125
+ def _apply_operator_JxKet(self, ket, **options):
126
+ return self._apply_op(ket, 'Jx', **options)
127
+
128
+ def _apply_operator_JxKetCoupled(self, ket, **options):
129
+ return self._apply_op(ket, 'Jx', **options)
130
+
131
+ def _apply_operator_JyKet(self, ket, **options):
132
+ return self._apply_op(ket, 'Jy', **options)
133
+
134
+ def _apply_operator_JyKetCoupled(self, ket, **options):
135
+ return self._apply_op(ket, 'Jy', **options)
136
+
137
+ def _apply_operator_JzKet(self, ket, **options):
138
+ return self._apply_op(ket, 'Jz', **options)
139
+
140
+ def _apply_operator_JzKetCoupled(self, ket, **options):
141
+ return self._apply_op(ket, 'Jz', **options)
142
+
143
+ def _apply_operator_TensorProduct(self, tp, **options):
144
+ # Uncoupling operator is only easily found for coordinate basis spin operators
145
+ # TODO: add methods for uncoupling operators
146
+ if not isinstance(self, (JxOp, JyOp, JzOp)):
147
+ raise NotImplementedError
148
+ result = []
149
+ for n in range(len(tp.args)):
150
+ arg = []
151
+ arg.extend(tp.args[:n])
152
+ arg.append(self._apply_operator(tp.args[n]))
153
+ arg.extend(tp.args[n + 1:])
154
+ result.append(tp.__class__(*arg))
155
+ return Add(*result).expand()
156
+
157
+ # TODO: move this to qapply_Mul
158
+ def _apply_operator_Sum(self, s, **options):
159
+ new_func = qapply(self*s.function)
160
+ if new_func == self*s.function:
161
+ raise NotImplementedError
162
+ return Sum(new_func, *s.limits)
163
+
164
+ def _eval_trace(self, **options):
165
+ #TODO: use options to use different j values
166
+ #For now eval at default basis
167
+
168
+ # is it efficient to represent each time
169
+ # to do a trace?
170
+ return self._represent_default_basis().trace()
171
+
172
+
173
+ class JplusOp(SpinOpBase, Operator):
174
+ """The J+ operator."""
175
+
176
+ _coord = '+'
177
+
178
+ basis = 'Jz'
179
+
180
+ def _eval_commutator_JminusOp(self, other):
181
+ return 2*hbar*JzOp(self.name)
182
+
183
+ def _apply_operator_JzKet(self, ket, **options):
184
+ j = ket.j
185
+ m = ket.m
186
+ if m.is_Number and j.is_Number:
187
+ if m >= j:
188
+ return S.Zero
189
+ return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
190
+
191
+ def _apply_operator_JzKetCoupled(self, ket, **options):
192
+ j = ket.j
193
+ m = ket.m
194
+ jn = ket.jn
195
+ coupling = ket.coupling
196
+ if m.is_Number and j.is_Number:
197
+ if m >= j:
198
+ return S.Zero
199
+ return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
200
+
201
+ def matrix_element(self, j, m, jp, mp):
202
+ result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
203
+ result *= KroneckerDelta(m, mp + 1)
204
+ result *= KroneckerDelta(j, jp)
205
+ return result
206
+
207
+ def _represent_default_basis(self, **options):
208
+ return self._represent_JzOp(None, **options)
209
+
210
+ def _represent_JzOp(self, basis, **options):
211
+ return self._represent_base(basis, **options)
212
+
213
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
214
+ return JxOp(args[0]) + I*JyOp(args[0])
215
+
216
+
217
+ class JminusOp(SpinOpBase, Operator):
218
+ """The J- operator."""
219
+
220
+ _coord = '-'
221
+
222
+ basis = 'Jz'
223
+
224
+ def _apply_operator_JzKet(self, ket, **options):
225
+ j = ket.j
226
+ m = ket.m
227
+ if m.is_Number and j.is_Number:
228
+ if m <= -j:
229
+ return S.Zero
230
+ return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
231
+
232
+ def _apply_operator_JzKetCoupled(self, ket, **options):
233
+ j = ket.j
234
+ m = ket.m
235
+ jn = ket.jn
236
+ coupling = ket.coupling
237
+ if m.is_Number and j.is_Number:
238
+ if m <= -j:
239
+ return S.Zero
240
+ return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
241
+
242
+ def matrix_element(self, j, m, jp, mp):
243
+ result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
244
+ result *= KroneckerDelta(m, mp - 1)
245
+ result *= KroneckerDelta(j, jp)
246
+ return result
247
+
248
+ def _represent_default_basis(self, **options):
249
+ return self._represent_JzOp(None, **options)
250
+
251
+ def _represent_JzOp(self, basis, **options):
252
+ return self._represent_base(basis, **options)
253
+
254
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
255
+ return JxOp(args[0]) - I*JyOp(args[0])
256
+
257
+
258
+ class JxOp(SpinOpBase, HermitianOperator):
259
+ """The Jx operator."""
260
+
261
+ _coord = 'x'
262
+
263
+ basis = 'Jx'
264
+
265
+ def _eval_commutator_JyOp(self, other):
266
+ return I*hbar*JzOp(self.name)
267
+
268
+ def _eval_commutator_JzOp(self, other):
269
+ return -I*hbar*JyOp(self.name)
270
+
271
+ def _apply_operator_JzKet(self, ket, **options):
272
+ jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
273
+ jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
274
+ return (jp + jm)/Integer(2)
275
+
276
+ def _apply_operator_JzKetCoupled(self, ket, **options):
277
+ jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
278
+ jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
279
+ return (jp + jm)/Integer(2)
280
+
281
+ def _represent_default_basis(self, **options):
282
+ return self._represent_JzOp(None, **options)
283
+
284
+ def _represent_JzOp(self, basis, **options):
285
+ jp = JplusOp(self.name)._represent_JzOp(basis, **options)
286
+ jm = JminusOp(self.name)._represent_JzOp(basis, **options)
287
+ return (jp + jm)/Integer(2)
288
+
289
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
290
+ return (JplusOp(args[0]) + JminusOp(args[0]))/2
291
+
292
+
293
+ class JyOp(SpinOpBase, HermitianOperator):
294
+ """The Jy operator."""
295
+
296
+ _coord = 'y'
297
+
298
+ basis = 'Jy'
299
+
300
+ def _eval_commutator_JzOp(self, other):
301
+ return I*hbar*JxOp(self.name)
302
+
303
+ def _eval_commutator_JxOp(self, other):
304
+ return -I*hbar*J2Op(self.name)
305
+
306
+ def _apply_operator_JzKet(self, ket, **options):
307
+ jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
308
+ jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
309
+ return (jp - jm)/(Integer(2)*I)
310
+
311
+ def _apply_operator_JzKetCoupled(self, ket, **options):
312
+ jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
313
+ jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
314
+ return (jp - jm)/(Integer(2)*I)
315
+
316
+ def _represent_default_basis(self, **options):
317
+ return self._represent_JzOp(None, **options)
318
+
319
+ def _represent_JzOp(self, basis, **options):
320
+ jp = JplusOp(self.name)._represent_JzOp(basis, **options)
321
+ jm = JminusOp(self.name)._represent_JzOp(basis, **options)
322
+ return (jp - jm)/(Integer(2)*I)
323
+
324
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
325
+ return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
326
+
327
+
328
+ class JzOp(SpinOpBase, HermitianOperator):
329
+ """The Jz operator."""
330
+
331
+ _coord = 'z'
332
+
333
+ basis = 'Jz'
334
+
335
+ def _eval_commutator_JxOp(self, other):
336
+ return I*hbar*JyOp(self.name)
337
+
338
+ def _eval_commutator_JyOp(self, other):
339
+ return -I*hbar*JxOp(self.name)
340
+
341
+ def _eval_commutator_JplusOp(self, other):
342
+ return hbar*JplusOp(self.name)
343
+
344
+ def _eval_commutator_JminusOp(self, other):
345
+ return -hbar*JminusOp(self.name)
346
+
347
+ def matrix_element(self, j, m, jp, mp):
348
+ result = hbar*mp
349
+ result *= KroneckerDelta(m, mp)
350
+ result *= KroneckerDelta(j, jp)
351
+ return result
352
+
353
+ def _represent_default_basis(self, **options):
354
+ return self._represent_JzOp(None, **options)
355
+
356
+ def _represent_JzOp(self, basis, **options):
357
+ return self._represent_base(basis, **options)
358
+
359
+
360
+ class J2Op(SpinOpBase, HermitianOperator):
361
+ """The J^2 operator."""
362
+
363
+ _coord = '2'
364
+
365
+ def _eval_commutator_JxOp(self, other):
366
+ return S.Zero
367
+
368
+ def _eval_commutator_JyOp(self, other):
369
+ return S.Zero
370
+
371
+ def _eval_commutator_JzOp(self, other):
372
+ return S.Zero
373
+
374
+ def _eval_commutator_JplusOp(self, other):
375
+ return S.Zero
376
+
377
+ def _eval_commutator_JminusOp(self, other):
378
+ return S.Zero
379
+
380
+ def _apply_operator_JxKet(self, ket, **options):
381
+ j = ket.j
382
+ return hbar**2*j*(j + 1)*ket
383
+
384
+ def _apply_operator_JxKetCoupled(self, ket, **options):
385
+ j = ket.j
386
+ return hbar**2*j*(j + 1)*ket
387
+
388
+ def _apply_operator_JyKet(self, ket, **options):
389
+ j = ket.j
390
+ return hbar**2*j*(j + 1)*ket
391
+
392
+ def _apply_operator_JyKetCoupled(self, ket, **options):
393
+ j = ket.j
394
+ return hbar**2*j*(j + 1)*ket
395
+
396
+ def _apply_operator_JzKet(self, ket, **options):
397
+ j = ket.j
398
+ return hbar**2*j*(j + 1)*ket
399
+
400
+ def _apply_operator_JzKetCoupled(self, ket, **options):
401
+ j = ket.j
402
+ return hbar**2*j*(j + 1)*ket
403
+
404
+ def matrix_element(self, j, m, jp, mp):
405
+ result = (hbar**2)*j*(j + 1)
406
+ result *= KroneckerDelta(m, mp)
407
+ result *= KroneckerDelta(j, jp)
408
+ return result
409
+
410
+ def _represent_default_basis(self, **options):
411
+ return self._represent_JzOp(None, **options)
412
+
413
+ def _represent_JzOp(self, basis, **options):
414
+ return self._represent_base(basis, **options)
415
+
416
+ def _print_contents_pretty(self, printer, *args):
417
+ a = prettyForm(str(self.name))
418
+ b = prettyForm('2')
419
+ return a**b
420
+
421
+ def _print_contents_latex(self, printer, *args):
422
+ return r'%s^2' % str(self.name)
423
+
424
+ def _eval_rewrite_as_xyz(self, *args, **kwargs):
425
+ return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
426
+
427
+ def _eval_rewrite_as_plusminus(self, *args, **kwargs):
428
+ a = args[0]
429
+ return JzOp(a)**2 + \
430
+ S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
431
+
432
+
433
+ class Rotation(UnitaryOperator):
434
+ """Wigner D operator in terms of Euler angles.
435
+
436
+ Defines the rotation operator in terms of the Euler angles defined by
437
+ the z-y-z convention for a passive transformation. That is the coordinate
438
+ axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
439
+ this new coordinate system is rotated about the new y'-axis, giving new
440
+ x''-y''-z'' axes. Then this new coordinate system is rotated about the
441
+ z''-axis. Conventions follow those laid out in [1]_.
442
+
443
+ Parameters
444
+ ==========
445
+
446
+ alpha : Number, Symbol
447
+ First Euler Angle
448
+ beta : Number, Symbol
449
+ Second Euler angle
450
+ gamma : Number, Symbol
451
+ Third Euler angle
452
+
453
+ Examples
454
+ ========
455
+
456
+ A simple example rotation operator:
457
+
458
+ >>> from sympy import pi
459
+ >>> from sympy.physics.quantum.spin import Rotation
460
+ >>> Rotation(pi, 0, pi/2)
461
+ R(pi,0,pi/2)
462
+
463
+ With symbolic Euler angles and calculating the inverse rotation operator:
464
+
465
+ >>> from sympy import symbols
466
+ >>> a, b, c = symbols('a b c')
467
+ >>> Rotation(a, b, c)
468
+ R(a,b,c)
469
+ >>> Rotation(a, b, c).inverse()
470
+ R(-c,-b,-a)
471
+
472
+ See Also
473
+ ========
474
+
475
+ WignerD: Symbolic Wigner-D function
476
+ D: Wigner-D function
477
+ d: Wigner small-d function
478
+
479
+ References
480
+ ==========
481
+
482
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
483
+ """
484
+
485
+ @classmethod
486
+ def _eval_args(cls, args):
487
+ args = QExpr._eval_args(args)
488
+ if len(args) != 3:
489
+ raise ValueError('3 Euler angles required, got: %r' % args)
490
+ return args
491
+
492
+ @classmethod
493
+ def _eval_hilbert_space(cls, label):
494
+ # We consider all j values so our space is infinite.
495
+ return ComplexSpace(S.Infinity)
496
+
497
+ @property
498
+ def alpha(self):
499
+ return self.label[0]
500
+
501
+ @property
502
+ def beta(self):
503
+ return self.label[1]
504
+
505
+ @property
506
+ def gamma(self):
507
+ return self.label[2]
508
+
509
+ def _print_operator_name(self, printer, *args):
510
+ return 'R'
511
+
512
+ def _print_operator_name_pretty(self, printer, *args):
513
+ if printer._use_unicode:
514
+ return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
515
+ else:
516
+ return prettyForm("R ")
517
+
518
+ def _print_operator_name_latex(self, printer, *args):
519
+ return r'\mathcal{R}'
520
+
521
+ def _eval_inverse(self):
522
+ return Rotation(-self.gamma, -self.beta, -self.alpha)
523
+
524
+ @classmethod
525
+ def D(cls, j, m, mp, alpha, beta, gamma):
526
+ """Wigner D-function.
527
+
528
+ Returns an instance of the WignerD class corresponding to the Wigner-D
529
+ function specified by the parameters.
530
+
531
+ Parameters
532
+ ===========
533
+
534
+ j : Number
535
+ Total angular momentum
536
+ m : Number
537
+ Eigenvalue of angular momentum along axis after rotation
538
+ mp : Number
539
+ Eigenvalue of angular momentum along rotated axis
540
+ alpha : Number, Symbol
541
+ First Euler angle of rotation
542
+ beta : Number, Symbol
543
+ Second Euler angle of rotation
544
+ gamma : Number, Symbol
545
+ Third Euler angle of rotation
546
+
547
+ Examples
548
+ ========
549
+
550
+ Return the Wigner-D matrix element for a defined rotation, both
551
+ numerical and symbolic:
552
+
553
+ >>> from sympy.physics.quantum.spin import Rotation
554
+ >>> from sympy import pi, symbols
555
+ >>> alpha, beta, gamma = symbols('alpha beta gamma')
556
+ >>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
557
+ WignerD(1, 1, 0, pi, pi/2, -pi)
558
+
559
+ See Also
560
+ ========
561
+
562
+ WignerD: Symbolic Wigner-D function
563
+
564
+ """
565
+ return WignerD(j, m, mp, alpha, beta, gamma)
566
+
567
+ @classmethod
568
+ def d(cls, j, m, mp, beta):
569
+ """Wigner small-d function.
570
+
571
+ Returns an instance of the WignerD class corresponding to the Wigner-D
572
+ function specified by the parameters with the alpha and gamma angles
573
+ given as 0.
574
+
575
+ Parameters
576
+ ===========
577
+
578
+ j : Number
579
+ Total angular momentum
580
+ m : Number
581
+ Eigenvalue of angular momentum along axis after rotation
582
+ mp : Number
583
+ Eigenvalue of angular momentum along rotated axis
584
+ beta : Number, Symbol
585
+ Second Euler angle of rotation
586
+
587
+ Examples
588
+ ========
589
+
590
+ Return the Wigner-D matrix element for a defined rotation, both
591
+ numerical and symbolic:
592
+
593
+ >>> from sympy.physics.quantum.spin import Rotation
594
+ >>> from sympy import pi, symbols
595
+ >>> beta = symbols('beta')
596
+ >>> Rotation.d(1, 1, 0, pi/2)
597
+ WignerD(1, 1, 0, 0, pi/2, 0)
598
+
599
+ See Also
600
+ ========
601
+
602
+ WignerD: Symbolic Wigner-D function
603
+
604
+ """
605
+ return WignerD(j, m, mp, 0, beta, 0)
606
+
607
+ def matrix_element(self, j, m, jp, mp):
608
+ result = self.__class__.D(
609
+ jp, m, mp, self.alpha, self.beta, self.gamma
610
+ )
611
+ result *= KroneckerDelta(j, jp)
612
+ return result
613
+
614
+ def _represent_base(self, basis, **options):
615
+ j = sympify(options.get('j', S.Half))
616
+ # TODO: move evaluation up to represent function/implement elsewhere
617
+ evaluate = sympify(options.get('doit'))
618
+ size, mvals = m_values(j)
619
+ result = zeros(size, size)
620
+ for p in range(size):
621
+ for q in range(size):
622
+ me = self.matrix_element(j, mvals[p], j, mvals[q])
623
+ if evaluate:
624
+ result[p, q] = me.doit()
625
+ else:
626
+ result[p, q] = me
627
+ return result
628
+
629
+ def _represent_default_basis(self, **options):
630
+ return self._represent_JzOp(None, **options)
631
+
632
+ def _represent_JzOp(self, basis, **options):
633
+ return self._represent_base(basis, **options)
634
+
635
+ def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
636
+ a = self.alpha
637
+ b = self.beta
638
+ g = self.gamma
639
+ j = ket.j
640
+ m = ket.m
641
+ if j.is_number:
642
+ s = []
643
+ size = m_values(j)
644
+ sz = size[1]
645
+ for mp in sz:
646
+ r = Rotation.D(j, m, mp, a, b, g)
647
+ z = r.doit()
648
+ s.append(z*state(j, mp))
649
+ return Add(*s)
650
+ else:
651
+ if dummy:
652
+ mp = Dummy('mp')
653
+ else:
654
+ mp = symbols('mp')
655
+ return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
656
+
657
+ def _apply_operator_JxKet(self, ket, **options):
658
+ return self._apply_operator_uncoupled(JxKet, ket, **options)
659
+
660
+ def _apply_operator_JyKet(self, ket, **options):
661
+ return self._apply_operator_uncoupled(JyKet, ket, **options)
662
+
663
+ def _apply_operator_JzKet(self, ket, **options):
664
+ return self._apply_operator_uncoupled(JzKet, ket, **options)
665
+
666
+ def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
667
+ a = self.alpha
668
+ b = self.beta
669
+ g = self.gamma
670
+ j = ket.j
671
+ m = ket.m
672
+ jn = ket.jn
673
+ coupling = ket.coupling
674
+ if j.is_number:
675
+ s = []
676
+ size = m_values(j)
677
+ sz = size[1]
678
+ for mp in sz:
679
+ r = Rotation.D(j, m, mp, a, b, g)
680
+ z = r.doit()
681
+ s.append(z*state(j, mp, jn, coupling))
682
+ return Add(*s)
683
+ else:
684
+ if dummy:
685
+ mp = Dummy('mp')
686
+ else:
687
+ mp = symbols('mp')
688
+ return Sum(Rotation.D(j, m, mp, a, b, g)*state(
689
+ j, mp, jn, coupling), (mp, -j, j))
690
+
691
+ def _apply_operator_JxKetCoupled(self, ket, **options):
692
+ return self._apply_operator_coupled(JxKetCoupled, ket, **options)
693
+
694
+ def _apply_operator_JyKetCoupled(self, ket, **options):
695
+ return self._apply_operator_coupled(JyKetCoupled, ket, **options)
696
+
697
+ def _apply_operator_JzKetCoupled(self, ket, **options):
698
+ return self._apply_operator_coupled(JzKetCoupled, ket, **options)
699
+
700
+ class WignerD(Expr):
701
+ r"""Wigner-D function
702
+
703
+ The Wigner D-function gives the matrix elements of the rotation
704
+ operator in the jm-representation. For the Euler angles `\alpha`,
705
+ `\beta`, `\gamma`, the D-function is defined such that:
706
+
707
+ .. math ::
708
+ <j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
709
+
710
+ Where the rotation operator is as defined by the Rotation class [1]_.
711
+
712
+ The Wigner D-function defined in this way gives:
713
+
714
+ .. math ::
715
+ D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
716
+
717
+ Where d is the Wigner small-d function, which is given by Rotation.d.
718
+
719
+ The Wigner small-d function gives the component of the Wigner
720
+ D-function that is determined by the second Euler angle. That is the
721
+ Wigner D-function is:
722
+
723
+ .. math ::
724
+ D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
725
+
726
+ Where d is the small-d function. The Wigner D-function is given by
727
+ Rotation.D.
728
+
729
+ Note that to evaluate the D-function, the j, m and mp parameters must
730
+ be integer or half integer numbers.
731
+
732
+ Parameters
733
+ ==========
734
+
735
+ j : Number
736
+ Total angular momentum
737
+ m : Number
738
+ Eigenvalue of angular momentum along axis after rotation
739
+ mp : Number
740
+ Eigenvalue of angular momentum along rotated axis
741
+ alpha : Number, Symbol
742
+ First Euler angle of rotation
743
+ beta : Number, Symbol
744
+ Second Euler angle of rotation
745
+ gamma : Number, Symbol
746
+ Third Euler angle of rotation
747
+
748
+ Examples
749
+ ========
750
+
751
+ Evaluate the Wigner-D matrix elements of a simple rotation:
752
+
753
+ >>> from sympy.physics.quantum.spin import Rotation
754
+ >>> from sympy import pi
755
+ >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
756
+ >>> rot
757
+ WignerD(1, 1, 0, pi, pi/2, 0)
758
+ >>> rot.doit()
759
+ sqrt(2)/2
760
+
761
+ Evaluate the Wigner-d matrix elements of a simple rotation
762
+
763
+ >>> rot = Rotation.d(1, 1, 0, pi/2)
764
+ >>> rot
765
+ WignerD(1, 1, 0, 0, pi/2, 0)
766
+ >>> rot.doit()
767
+ -sqrt(2)/2
768
+
769
+ See Also
770
+ ========
771
+
772
+ Rotation: Rotation operator
773
+
774
+ References
775
+ ==========
776
+
777
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
778
+ """
779
+
780
+ is_commutative = True
781
+
782
+ def __new__(cls, *args, **hints):
783
+ if not len(args) == 6:
784
+ raise ValueError('6 parameters expected, got %s' % args)
785
+ args = sympify(args)
786
+ evaluate = hints.get('evaluate', False)
787
+ if evaluate:
788
+ return Expr.__new__(cls, *args)._eval_wignerd()
789
+ return Expr.__new__(cls, *args)
790
+
791
+ @property
792
+ def j(self):
793
+ return self.args[0]
794
+
795
+ @property
796
+ def m(self):
797
+ return self.args[1]
798
+
799
+ @property
800
+ def mp(self):
801
+ return self.args[2]
802
+
803
+ @property
804
+ def alpha(self):
805
+ return self.args[3]
806
+
807
+ @property
808
+ def beta(self):
809
+ return self.args[4]
810
+
811
+ @property
812
+ def gamma(self):
813
+ return self.args[5]
814
+
815
+ def _latex(self, printer, *args):
816
+ if self.alpha == 0 and self.gamma == 0:
817
+ return r'd^{%s}_{%s,%s}\left(%s\right)' % \
818
+ (
819
+ printer._print(self.j), printer._print(
820
+ self.m), printer._print(self.mp),
821
+ printer._print(self.beta) )
822
+ return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
823
+ (
824
+ printer._print(
825
+ self.j), printer._print(self.m), printer._print(self.mp),
826
+ printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
827
+
828
+ def _pretty(self, printer, *args):
829
+ top = printer._print(self.j)
830
+
831
+ bot = printer._print(self.m)
832
+ bot = prettyForm(*bot.right(','))
833
+ bot = prettyForm(*bot.right(printer._print(self.mp)))
834
+
835
+ pad = max(top.width(), bot.width())
836
+ top = prettyForm(*top.left(' '))
837
+ bot = prettyForm(*bot.left(' '))
838
+ if pad > top.width():
839
+ top = prettyForm(*top.right(' '*(pad - top.width())))
840
+ if pad > bot.width():
841
+ bot = prettyForm(*bot.right(' '*(pad - bot.width())))
842
+ if self.alpha == 0 and self.gamma == 0:
843
+ args = printer._print(self.beta)
844
+ s = stringPict('d' + ' '*pad)
845
+ else:
846
+ args = printer._print(self.alpha)
847
+ args = prettyForm(*args.right(','))
848
+ args = prettyForm(*args.right(printer._print(self.beta)))
849
+ args = prettyForm(*args.right(','))
850
+ args = prettyForm(*args.right(printer._print(self.gamma)))
851
+
852
+ s = stringPict('D' + ' '*pad)
853
+
854
+ args = prettyForm(*args.parens())
855
+ s = prettyForm(*s.above(top))
856
+ s = prettyForm(*s.below(bot))
857
+ s = prettyForm(*s.right(args))
858
+ return s
859
+
860
+ def doit(self, **hints):
861
+ hints['evaluate'] = True
862
+ return WignerD(*self.args, **hints)
863
+
864
+ def _eval_wignerd(self):
865
+ j = self.j
866
+ m = self.m
867
+ mp = self.mp
868
+ alpha = self.alpha
869
+ beta = self.beta
870
+ gamma = self.gamma
871
+ if alpha == 0 and beta == 0 and gamma == 0:
872
+ return KroneckerDelta(m, mp)
873
+ if not j.is_number:
874
+ raise ValueError(
875
+ 'j parameter must be numerical to evaluate, got %s' % j)
876
+ r = 0
877
+ if beta == pi/2:
878
+ # Varshalovich Equation (5), Section 4.16, page 113, setting
879
+ # alpha=gamma=0.
880
+ for k in range(2*j + 1):
881
+ if k > j + mp or k > j - m or k < mp - m:
882
+ continue
883
+ r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
884
+ r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
885
+ factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
886
+ else:
887
+ # Varshalovich Equation(5), Section 4.7.2, page 87, where we set
888
+ # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
889
+ # then we use the Eq. (1), Section 4.4. page 79, to simplify:
890
+ # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
891
+ # This happens to be almost the same as in Eq.(10), Section 4.16,
892
+ # except that we need to substitute -mp for mp.
893
+ size, mvals = m_values(j)
894
+ for mpp in mvals:
895
+ r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
896
+ Rotation.d(j, mpp, -mp, pi/2).doit()
897
+ # Empirical normalization factor so results match Varshalovich
898
+ # Tables 4.3-4.12
899
+ # Note that this exact normalization does not follow from the
900
+ # above equations
901
+ r = r*I**(2*j - m - mp)*(-1)**(2*m)
902
+ # Finally, simplify the whole expression
903
+ r = simplify(r)
904
+ r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
905
+ return r
906
+
907
+
908
+ Jx = JxOp('J')
909
+ Jy = JyOp('J')
910
+ Jz = JzOp('J')
911
+ J2 = J2Op('J')
912
+ Jplus = JplusOp('J')
913
+ Jminus = JminusOp('J')
914
+
915
+
916
+ #-----------------------------------------------------------------------------
917
+ # Spin States
918
+ #-----------------------------------------------------------------------------
919
+
920
+
921
+ class SpinState(State):
922
+ """Base class for angular momentum states."""
923
+
924
+ _label_separator = ','
925
+
926
+ def __new__(cls, j, m):
927
+ j = sympify(j)
928
+ m = sympify(m)
929
+ if j.is_number:
930
+ if 2*j != int(2*j):
931
+ raise ValueError(
932
+ 'j must be integer or half-integer, got: %s' % j)
933
+ if j < 0:
934
+ raise ValueError('j must be >= 0, got: %s' % j)
935
+ if m.is_number:
936
+ if 2*m != int(2*m):
937
+ raise ValueError(
938
+ 'm must be integer or half-integer, got: %s' % m)
939
+ if j.is_number and m.is_number:
940
+ if abs(m) > j:
941
+ raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
942
+ if int(j - m) != j - m:
943
+ raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
944
+ return State.__new__(cls, j, m)
945
+
946
+ @property
947
+ def j(self):
948
+ return self.label[0]
949
+
950
+ @property
951
+ def m(self):
952
+ return self.label[1]
953
+
954
+ @classmethod
955
+ def _eval_hilbert_space(cls, label):
956
+ return ComplexSpace(2*label[0] + 1)
957
+
958
+ def _represent_base(self, **options):
959
+ j = self.j
960
+ m = self.m
961
+ alpha = sympify(options.get('alpha', 0))
962
+ beta = sympify(options.get('beta', 0))
963
+ gamma = sympify(options.get('gamma', 0))
964
+ size, mvals = m_values(j)
965
+ result = zeros(size, 1)
966
+ # breaks finding angles on L930
967
+ for p, mval in enumerate(mvals):
968
+ if m.is_number:
969
+ result[p, 0] = Rotation.D(
970
+ self.j, mval, self.m, alpha, beta, gamma).doit()
971
+ else:
972
+ result[p, 0] = Rotation.D(self.j, mval,
973
+ self.m, alpha, beta, gamma)
974
+ return result
975
+
976
+ def _eval_rewrite_as_Jx(self, *args, **options):
977
+ if isinstance(self, Bra):
978
+ return self._rewrite_basis(Jx, JxBra, **options)
979
+ return self._rewrite_basis(Jx, JxKet, **options)
980
+
981
+ def _eval_rewrite_as_Jy(self, *args, **options):
982
+ if isinstance(self, Bra):
983
+ return self._rewrite_basis(Jy, JyBra, **options)
984
+ return self._rewrite_basis(Jy, JyKet, **options)
985
+
986
+ def _eval_rewrite_as_Jz(self, *args, **options):
987
+ if isinstance(self, Bra):
988
+ return self._rewrite_basis(Jz, JzBra, **options)
989
+ return self._rewrite_basis(Jz, JzKet, **options)
990
+
991
+ def _rewrite_basis(self, basis, evect, **options):
992
+ from sympy.physics.quantum.represent import represent
993
+ j = self.j
994
+ args = self.args[2:]
995
+ if j.is_number:
996
+ if isinstance(self, CoupledSpinState):
997
+ if j == int(j):
998
+ start = j**2
999
+ else:
1000
+ start = (2*j - 1)*(2*j + 1)/4
1001
+ else:
1002
+ start = 0
1003
+ vect = represent(self, basis=basis, **options)
1004
+ result = Add(
1005
+ *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
1006
+ if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
1007
+ return uncouple(result)
1008
+ return result
1009
+ else:
1010
+ i = 0
1011
+ mi = symbols('mi')
1012
+ # make sure not to introduce a symbol already in the state
1013
+ while self.subs(mi, 0) != self:
1014
+ i += 1
1015
+ mi = symbols('mi%d' % i)
1016
+ break
1017
+ # TODO: better way to get angles of rotation
1018
+ if isinstance(self, CoupledSpinState):
1019
+ test_args = (0, mi, (0, 0))
1020
+ else:
1021
+ test_args = (0, mi)
1022
+ if isinstance(self, Ket):
1023
+ angles = represent(
1024
+ self.__class__(*test_args), basis=basis)[0].args[3:6]
1025
+ else:
1026
+ angles = represent(self.__class__(
1027
+ *test_args), basis=basis)[0].args[0].args[3:6]
1028
+ if angles == (0, 0, 0):
1029
+ return self
1030
+ else:
1031
+ state = evect(j, mi, *args)
1032
+ lt = Rotation.D(j, mi, self.m, *angles)
1033
+ return Sum(lt*state, (mi, -j, j))
1034
+
1035
+ def _eval_innerproduct_JxBra(self, bra, **hints):
1036
+ result = KroneckerDelta(self.j, bra.j)
1037
+ if bra.dual_class() is not self.__class__:
1038
+ result *= self._represent_JxOp(None)[bra.j - bra.m]
1039
+ else:
1040
+ result *= KroneckerDelta(
1041
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1042
+ return result
1043
+
1044
+ def _eval_innerproduct_JyBra(self, bra, **hints):
1045
+ result = KroneckerDelta(self.j, bra.j)
1046
+ if bra.dual_class() is not self.__class__:
1047
+ result *= self._represent_JyOp(None)[bra.j - bra.m]
1048
+ else:
1049
+ result *= KroneckerDelta(
1050
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1051
+ return result
1052
+
1053
+ def _eval_innerproduct_JzBra(self, bra, **hints):
1054
+ result = KroneckerDelta(self.j, bra.j)
1055
+ if bra.dual_class() is not self.__class__:
1056
+ result *= self._represent_JzOp(None)[bra.j - bra.m]
1057
+ else:
1058
+ result *= KroneckerDelta(
1059
+ self.j, bra.j)*KroneckerDelta(self.m, bra.m)
1060
+ return result
1061
+
1062
+ def _eval_trace(self, bra, **hints):
1063
+
1064
+ # One way to implement this method is to assume the basis set k is
1065
+ # passed.
1066
+ # Then we can apply the discrete form of Trace formula here
1067
+ # Tr(|i><j| ) = \Sum_k <k|i><j|k>
1068
+ #then we do qapply() on each each inner product and sum over them.
1069
+
1070
+ # OR
1071
+
1072
+ # Inner product of |i><j| = Trace(Outer Product).
1073
+ # we could just use this unless there are cases when this is not true
1074
+
1075
+ return (bra*self).doit()
1076
+
1077
+
1078
+ class JxKet(SpinState, Ket):
1079
+ """Eigenket of Jx.
1080
+
1081
+ See JzKet for the usage of spin eigenstates.
1082
+
1083
+ See Also
1084
+ ========
1085
+
1086
+ JzKet: Usage of spin states
1087
+
1088
+ """
1089
+
1090
+ @classmethod
1091
+ def dual_class(self):
1092
+ return JxBra
1093
+
1094
+ @classmethod
1095
+ def coupled_class(self):
1096
+ return JxKetCoupled
1097
+
1098
+ def _represent_default_basis(self, **options):
1099
+ return self._represent_JxOp(None, **options)
1100
+
1101
+ def _represent_JxOp(self, basis, **options):
1102
+ return self._represent_base(**options)
1103
+
1104
+ def _represent_JyOp(self, basis, **options):
1105
+ return self._represent_base(alpha=pi*Rational(3, 2), **options)
1106
+
1107
+ def _represent_JzOp(self, basis, **options):
1108
+ return self._represent_base(beta=pi/2, **options)
1109
+
1110
+
1111
+ class JxBra(SpinState, Bra):
1112
+ """Eigenbra of Jx.
1113
+
1114
+ See JzKet for the usage of spin eigenstates.
1115
+
1116
+ See Also
1117
+ ========
1118
+
1119
+ JzKet: Usage of spin states
1120
+
1121
+ """
1122
+
1123
+ @classmethod
1124
+ def dual_class(self):
1125
+ return JxKet
1126
+
1127
+ @classmethod
1128
+ def coupled_class(self):
1129
+ return JxBraCoupled
1130
+
1131
+
1132
+ class JyKet(SpinState, Ket):
1133
+ """Eigenket of Jy.
1134
+
1135
+ See JzKet for the usage of spin eigenstates.
1136
+
1137
+ See Also
1138
+ ========
1139
+
1140
+ JzKet: Usage of spin states
1141
+
1142
+ """
1143
+
1144
+ @classmethod
1145
+ def dual_class(self):
1146
+ return JyBra
1147
+
1148
+ @classmethod
1149
+ def coupled_class(self):
1150
+ return JyKetCoupled
1151
+
1152
+ def _represent_default_basis(self, **options):
1153
+ return self._represent_JyOp(None, **options)
1154
+
1155
+ def _represent_JxOp(self, basis, **options):
1156
+ return self._represent_base(gamma=pi/2, **options)
1157
+
1158
+ def _represent_JyOp(self, basis, **options):
1159
+ return self._represent_base(**options)
1160
+
1161
+ def _represent_JzOp(self, basis, **options):
1162
+ return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
1163
+
1164
+
1165
+ class JyBra(SpinState, Bra):
1166
+ """Eigenbra of Jy.
1167
+
1168
+ See JzKet for the usage of spin eigenstates.
1169
+
1170
+ See Also
1171
+ ========
1172
+
1173
+ JzKet: Usage of spin states
1174
+
1175
+ """
1176
+
1177
+ @classmethod
1178
+ def dual_class(self):
1179
+ return JyKet
1180
+
1181
+ @classmethod
1182
+ def coupled_class(self):
1183
+ return JyBraCoupled
1184
+
1185
+
1186
+ class JzKet(SpinState, Ket):
1187
+ """Eigenket of Jz.
1188
+
1189
+ Spin state which is an eigenstate of the Jz operator. Uncoupled states,
1190
+ that is states representing the interaction of multiple separate spin
1191
+ states, are defined as a tensor product of states.
1192
+
1193
+ Parameters
1194
+ ==========
1195
+
1196
+ j : Number, Symbol
1197
+ Total spin angular momentum
1198
+ m : Number, Symbol
1199
+ Eigenvalue of the Jz spin operator
1200
+
1201
+ Examples
1202
+ ========
1203
+
1204
+ *Normal States:*
1205
+
1206
+ Defining simple spin states, both numerical and symbolic:
1207
+
1208
+ >>> from sympy.physics.quantum.spin import JzKet, JxKet
1209
+ >>> from sympy import symbols
1210
+ >>> JzKet(1, 0)
1211
+ |1,0>
1212
+ >>> j, m = symbols('j m')
1213
+ >>> JzKet(j, m)
1214
+ |j,m>
1215
+
1216
+ Rewriting the JzKet in terms of eigenkets of the Jx operator:
1217
+ Note: that the resulting eigenstates are JxKet's
1218
+
1219
+ >>> JzKet(1,1).rewrite("Jx")
1220
+ |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
1221
+
1222
+ Get the vector representation of a state in terms of the basis elements
1223
+ of the Jx operator:
1224
+
1225
+ >>> from sympy.physics.quantum.represent import represent
1226
+ >>> from sympy.physics.quantum.spin import Jx, Jz
1227
+ >>> represent(JzKet(1,-1), basis=Jx)
1228
+ Matrix([
1229
+ [ 1/2],
1230
+ [sqrt(2)/2],
1231
+ [ 1/2]])
1232
+
1233
+ Apply innerproducts between states:
1234
+
1235
+ >>> from sympy.physics.quantum.innerproduct import InnerProduct
1236
+ >>> from sympy.physics.quantum.spin import JxBra
1237
+ >>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
1238
+ >>> i
1239
+ <1,1|1,1>
1240
+ >>> i.doit()
1241
+ 1/2
1242
+
1243
+ *Uncoupled States:*
1244
+
1245
+ Define an uncoupled state as a TensorProduct between two Jz eigenkets:
1246
+
1247
+ >>> from sympy.physics.quantum.tensorproduct import TensorProduct
1248
+ >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
1249
+ >>> TensorProduct(JzKet(1,0), JzKet(1,1))
1250
+ |1,0>x|1,1>
1251
+ >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
1252
+ |j1,m1>x|j2,m2>
1253
+
1254
+ A TensorProduct can be rewritten, in which case the eigenstates that make
1255
+ up the tensor product is rewritten to the new basis:
1256
+
1257
+ >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
1258
+ |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
1259
+
1260
+ The represent method for TensorProduct's gives the vector representation of
1261
+ the state. Note that the state in the product basis is the equivalent of the
1262
+ tensor product of the vector representation of the component eigenstates:
1263
+
1264
+ >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
1265
+ Matrix([
1266
+ [0],
1267
+ [0],
1268
+ [0],
1269
+ [1],
1270
+ [0],
1271
+ [0],
1272
+ [0],
1273
+ [0],
1274
+ [0]])
1275
+ >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
1276
+ Matrix([
1277
+ [ 1/2],
1278
+ [sqrt(2)/2],
1279
+ [ 1/2],
1280
+ [ 0],
1281
+ [ 0],
1282
+ [ 0],
1283
+ [ 0],
1284
+ [ 0],
1285
+ [ 0]])
1286
+
1287
+ See Also
1288
+ ========
1289
+
1290
+ JzKetCoupled: Coupled eigenstates
1291
+ sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
1292
+ uncouple: Uncouples states given coupling parameters
1293
+ couple: Couples uncoupled states
1294
+
1295
+ """
1296
+
1297
+ @classmethod
1298
+ def dual_class(self):
1299
+ return JzBra
1300
+
1301
+ @classmethod
1302
+ def coupled_class(self):
1303
+ return JzKetCoupled
1304
+
1305
+ def _represent_default_basis(self, **options):
1306
+ return self._represent_JzOp(None, **options)
1307
+
1308
+ def _represent_JxOp(self, basis, **options):
1309
+ return self._represent_base(beta=pi*Rational(3, 2), **options)
1310
+
1311
+ def _represent_JyOp(self, basis, **options):
1312
+ return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
1313
+
1314
+ def _represent_JzOp(self, basis, **options):
1315
+ return self._represent_base(**options)
1316
+
1317
+
1318
+ class JzBra(SpinState, Bra):
1319
+ """Eigenbra of Jz.
1320
+
1321
+ See the JzKet for the usage of spin eigenstates.
1322
+
1323
+ See Also
1324
+ ========
1325
+
1326
+ JzKet: Usage of spin states
1327
+
1328
+ """
1329
+
1330
+ @classmethod
1331
+ def dual_class(self):
1332
+ return JzKet
1333
+
1334
+ @classmethod
1335
+ def coupled_class(self):
1336
+ return JzBraCoupled
1337
+
1338
+
1339
+ # Method used primarily to create coupled_n and coupled_jn by __new__ in
1340
+ # CoupledSpinState
1341
+ # This same method is also used by the uncouple method, and is separated from
1342
+ # the CoupledSpinState class to maintain consistency in defining coupling
1343
+ def _build_coupled(jcoupling, length):
1344
+ n_list = [ [n + 1] for n in range(length) ]
1345
+ coupled_jn = []
1346
+ coupled_n = []
1347
+ for n1, n2, j_new in jcoupling:
1348
+ coupled_jn.append(j_new)
1349
+ coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
1350
+ n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
1351
+ n_list[n_sort[0] - 1] = n_sort
1352
+ return coupled_n, coupled_jn
1353
+
1354
+
1355
+ class CoupledSpinState(SpinState):
1356
+ """Base class for coupled angular momentum states."""
1357
+
1358
+ def __new__(cls, j, m, jn, *jcoupling):
1359
+ # Check j and m values using SpinState
1360
+ SpinState(j, m)
1361
+ # Build and check coupling scheme from arguments
1362
+ if len(jcoupling) == 0:
1363
+ # Use default coupling scheme
1364
+ jcoupling = []
1365
+ for n in range(2, len(jn)):
1366
+ jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
1367
+ jcoupling.append( (1, len(jn), j) )
1368
+ elif len(jcoupling) == 1:
1369
+ # Use specified coupling scheme
1370
+ jcoupling = jcoupling[0]
1371
+ else:
1372
+ raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
1373
+ # Check arguments have correct form
1374
+ if not isinstance(jn, (list, tuple, Tuple)):
1375
+ raise TypeError('jn must be Tuple, list or tuple, got %s' %
1376
+ jn.__class__.__name__)
1377
+ if not isinstance(jcoupling, (list, tuple, Tuple)):
1378
+ raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
1379
+ jcoupling.__class__.__name__)
1380
+ if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
1381
+ raise TypeError(
1382
+ 'All elements of jcoupling must be list, tuple or Tuple')
1383
+ if not len(jn) - 1 == len(jcoupling):
1384
+ raise ValueError('jcoupling must have length of %d, got %d' %
1385
+ (len(jn) - 1, len(jcoupling)))
1386
+ if not all(len(x) == 3 for x in jcoupling):
1387
+ raise ValueError('All elements of jcoupling must have length 3')
1388
+ # Build sympified args
1389
+ j = sympify(j)
1390
+ m = sympify(m)
1391
+ jn = Tuple( *[sympify(ji) for ji in jn] )
1392
+ jcoupling = Tuple( *[Tuple(sympify(
1393
+ n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
1394
+ # Check values in coupling scheme give physical state
1395
+ if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
1396
+ raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
1397
+ if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
1398
+ raise ValueError('Indices in jcoupling must be integers')
1399
+ if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
1400
+ raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
1401
+ if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
1402
+ raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
1403
+ coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
1404
+ jvals = list(jn)
1405
+ for n, (n1, n2) in enumerate(coupled_n):
1406
+ j1 = jvals[min(n1) - 1]
1407
+ j2 = jvals[min(n2) - 1]
1408
+ j3 = coupled_jn[n]
1409
+ if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
1410
+ if j1 + j2 < j3:
1411
+ raise ValueError('All couplings must have j1+j2 >= j3, '
1412
+ 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
1413
+ if abs(j1 - j2) > j3:
1414
+ raise ValueError("All couplings must have |j1+j2| <= j3, "
1415
+ "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
1416
+ if int_valued(j1 + j2):
1417
+ pass
1418
+ jvals[min(n1 + n2) - 1] = j3
1419
+ if len(jcoupling) > 0 and jcoupling[-1][2] != j:
1420
+ raise ValueError('Last j value coupled together must be the final j of the state')
1421
+ # Return state
1422
+ return State.__new__(cls, j, m, jn, jcoupling)
1423
+
1424
+ def _print_label(self, printer, *args):
1425
+ label = [printer._print(self.j), printer._print(self.m)]
1426
+ for i, ji in enumerate(self.jn, start=1):
1427
+ label.append('j%d=%s' % (
1428
+ i, printer._print(ji)
1429
+ ))
1430
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1431
+ label.append('j(%s)=%s' % (
1432
+ ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
1433
+ ))
1434
+ return ','.join(label)
1435
+
1436
+ def _print_label_pretty(self, printer, *args):
1437
+ label = [self.j, self.m]
1438
+ for i, ji in enumerate(self.jn, start=1):
1439
+ symb = 'j%d' % i
1440
+ symb = pretty_symbol(symb)
1441
+ symb = prettyForm(symb + '=')
1442
+ item = prettyForm(*symb.right(printer._print(ji)))
1443
+ label.append(item)
1444
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1445
+ n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
1446
+ symb = prettyForm('j' + n + '=')
1447
+ item = prettyForm(*symb.right(printer._print(jn)))
1448
+ label.append(item)
1449
+ return self._print_sequence_pretty(
1450
+ label, self._label_separator, printer, *args
1451
+ )
1452
+
1453
+ def _print_label_latex(self, printer, *args):
1454
+ label = [
1455
+ printer._print(self.j, *args),
1456
+ printer._print(self.m, *args)
1457
+ ]
1458
+ for i, ji in enumerate(self.jn, start=1):
1459
+ label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
1460
+ for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
1461
+ n = ','.join(str(i) for i in sorted(n1 + n2))
1462
+ label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
1463
+ return self._label_separator.join(label)
1464
+
1465
+ @property
1466
+ def jn(self):
1467
+ return self.label[2]
1468
+
1469
+ @property
1470
+ def coupling(self):
1471
+ return self.label[3]
1472
+
1473
+ @property
1474
+ def coupled_jn(self):
1475
+ return _build_coupled(self.label[3], len(self.label[2]))[1]
1476
+
1477
+ @property
1478
+ def coupled_n(self):
1479
+ return _build_coupled(self.label[3], len(self.label[2]))[0]
1480
+
1481
+ @classmethod
1482
+ def _eval_hilbert_space(cls, label):
1483
+ j = Add(*label[2])
1484
+ if j.is_number:
1485
+ return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
1486
+ else:
1487
+ # TODO: Need hilbert space fix, see issue 5732
1488
+ # Desired behavior:
1489
+ #ji = symbols('ji')
1490
+ #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
1491
+ # Temporary fix:
1492
+ return ComplexSpace(2*j + 1)
1493
+
1494
+ def _represent_coupled_base(self, **options):
1495
+ evect = self.uncoupled_class()
1496
+ if not self.j.is_number:
1497
+ raise ValueError(
1498
+ 'State must not have symbolic j value to represent')
1499
+ if not self.hilbert_space.dimension.is_number:
1500
+ raise ValueError(
1501
+ 'State must not have symbolic j values to represent')
1502
+ result = zeros(self.hilbert_space.dimension, 1)
1503
+ if self.j == int(self.j):
1504
+ start = self.j**2
1505
+ else:
1506
+ start = (2*self.j - 1)*(1 + 2*self.j)/4
1507
+ result[start:start + 2*self.j + 1, 0] = evect(
1508
+ self.j, self.m)._represent_base(**options)
1509
+ return result
1510
+
1511
+ def _eval_rewrite_as_Jx(self, *args, **options):
1512
+ if isinstance(self, Bra):
1513
+ return self._rewrite_basis(Jx, JxBraCoupled, **options)
1514
+ return self._rewrite_basis(Jx, JxKetCoupled, **options)
1515
+
1516
+ def _eval_rewrite_as_Jy(self, *args, **options):
1517
+ if isinstance(self, Bra):
1518
+ return self._rewrite_basis(Jy, JyBraCoupled, **options)
1519
+ return self._rewrite_basis(Jy, JyKetCoupled, **options)
1520
+
1521
+ def _eval_rewrite_as_Jz(self, *args, **options):
1522
+ if isinstance(self, Bra):
1523
+ return self._rewrite_basis(Jz, JzBraCoupled, **options)
1524
+ return self._rewrite_basis(Jz, JzKetCoupled, **options)
1525
+
1526
+
1527
+ class JxKetCoupled(CoupledSpinState, Ket):
1528
+ """Coupled eigenket of Jx.
1529
+
1530
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1531
+
1532
+ See Also
1533
+ ========
1534
+
1535
+ JzKetCoupled: Usage of coupled spin states
1536
+
1537
+ """
1538
+
1539
+ @classmethod
1540
+ def dual_class(self):
1541
+ return JxBraCoupled
1542
+
1543
+ @classmethod
1544
+ def uncoupled_class(self):
1545
+ return JxKet
1546
+
1547
+ def _represent_default_basis(self, **options):
1548
+ return self._represent_JzOp(None, **options)
1549
+
1550
+ def _represent_JxOp(self, basis, **options):
1551
+ return self._represent_coupled_base(**options)
1552
+
1553
+ def _represent_JyOp(self, basis, **options):
1554
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
1555
+
1556
+ def _represent_JzOp(self, basis, **options):
1557
+ return self._represent_coupled_base(beta=pi/2, **options)
1558
+
1559
+
1560
+ class JxBraCoupled(CoupledSpinState, Bra):
1561
+ """Coupled eigenbra of Jx.
1562
+
1563
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1564
+
1565
+ See Also
1566
+ ========
1567
+
1568
+ JzKetCoupled: Usage of coupled spin states
1569
+
1570
+ """
1571
+
1572
+ @classmethod
1573
+ def dual_class(self):
1574
+ return JxKetCoupled
1575
+
1576
+ @classmethod
1577
+ def uncoupled_class(self):
1578
+ return JxBra
1579
+
1580
+
1581
+ class JyKetCoupled(CoupledSpinState, Ket):
1582
+ """Coupled eigenket of Jy.
1583
+
1584
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1585
+
1586
+ See Also
1587
+ ========
1588
+
1589
+ JzKetCoupled: Usage of coupled spin states
1590
+
1591
+ """
1592
+
1593
+ @classmethod
1594
+ def dual_class(self):
1595
+ return JyBraCoupled
1596
+
1597
+ @classmethod
1598
+ def uncoupled_class(self):
1599
+ return JyKet
1600
+
1601
+ def _represent_default_basis(self, **options):
1602
+ return self._represent_JzOp(None, **options)
1603
+
1604
+ def _represent_JxOp(self, basis, **options):
1605
+ return self._represent_coupled_base(gamma=pi/2, **options)
1606
+
1607
+ def _represent_JyOp(self, basis, **options):
1608
+ return self._represent_coupled_base(**options)
1609
+
1610
+ def _represent_JzOp(self, basis, **options):
1611
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
1612
+
1613
+
1614
+ class JyBraCoupled(CoupledSpinState, Bra):
1615
+ """Coupled eigenbra of Jy.
1616
+
1617
+ See JzKetCoupled for the usage of coupled spin eigenstates.
1618
+
1619
+ See Also
1620
+ ========
1621
+
1622
+ JzKetCoupled: Usage of coupled spin states
1623
+
1624
+ """
1625
+
1626
+ @classmethod
1627
+ def dual_class(self):
1628
+ return JyKetCoupled
1629
+
1630
+ @classmethod
1631
+ def uncoupled_class(self):
1632
+ return JyBra
1633
+
1634
+
1635
+ class JzKetCoupled(CoupledSpinState, Ket):
1636
+ r"""Coupled eigenket of Jz
1637
+
1638
+ Spin state that is an eigenket of Jz which represents the coupling of
1639
+ separate spin spaces.
1640
+
1641
+ The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
1642
+ ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
1643
+ are the total angular momentum quantum numbers, as used for normal states
1644
+ (e.g. JzKet).
1645
+
1646
+ The other required parameter in ``jn``, which is a tuple defining the `j_n`
1647
+ angular momentum quantum numbers of the product spaces. So for example, if
1648
+ a state represented the coupling of the product basis state
1649
+ `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
1650
+ for this state would be ``(j1,j2)``.
1651
+
1652
+ The final option is ``jcoupling``, which is used to define how the spaces
1653
+ specified by ``jn`` are coupled, which includes both the order these spaces
1654
+ are coupled together and the quantum numbers that arise from these
1655
+ couplings. The ``jcoupling`` parameter itself is a list of lists, such that
1656
+ each of the sublists defines a single coupling between the spin spaces. If
1657
+ there are N coupled angular momentum spaces, that is ``jn`` has N elements,
1658
+ then there must be N-1 sublists. Each of these sublists making up the
1659
+ ``jcoupling`` parameter have length 3. The first two elements are the
1660
+ indices of the product spaces that are considered to be coupled together.
1661
+ For example, if we want to couple `j_1` and `j_4`, the indices would be 1
1662
+ and 4. If a state has already been coupled, it is referenced by the
1663
+ smallest index that is coupled, so if `j_2` and `j_4` has already been
1664
+ coupled to some `j_{24}`, then this value can be coupled by referencing it
1665
+ with index 2. The final element of the sublist is the quantum number of the
1666
+ coupled state. So putting everything together, into a valid sublist for
1667
+ ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
1668
+ with quantum number `j_{12}` with the value ``j12``, the sublist would be
1669
+ ``(1,2,j12)``, N-1 of these sublists are used in the list for
1670
+ ``jcoupling``.
1671
+
1672
+ Note the ``jcoupling`` parameter is optional, if it is not specified, the
1673
+ default coupling is taken. This default value is to coupled the spaces in
1674
+ order and take the quantum number of the coupling to be the maximum value.
1675
+ For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
1676
+ default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
1677
+ `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
1678
+ `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
1679
+ correspond to this is:
1680
+
1681
+ ``((1,2,j1+j2),(1,3,j1+j2+j3))``
1682
+
1683
+ Parameters
1684
+ ==========
1685
+
1686
+ args : tuple
1687
+ The arguments that must be passed are ``j``, ``m``, ``jn``, and
1688
+ ``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
1689
+ value is the eigenvalue of the Jz spin operator. The ``jn`` list are
1690
+ the j values of argular momentum spaces coupled together. The
1691
+ ``jcoupling`` parameter is an optional parameter defining how the spaces
1692
+ are coupled together. See the above description for how these coupling
1693
+ parameters are defined.
1694
+
1695
+ Examples
1696
+ ========
1697
+
1698
+ Defining simple spin states, both numerical and symbolic:
1699
+
1700
+ >>> from sympy.physics.quantum.spin import JzKetCoupled
1701
+ >>> from sympy import symbols
1702
+ >>> JzKetCoupled(1, 0, (1, 1))
1703
+ |1,0,j1=1,j2=1>
1704
+ >>> j, m, j1, j2 = symbols('j m j1 j2')
1705
+ >>> JzKetCoupled(j, m, (j1, j2))
1706
+ |j,m,j1=j1,j2=j2>
1707
+
1708
+ Defining coupled spin states for more than 2 coupled spaces with various
1709
+ coupling parameters:
1710
+
1711
+ >>> JzKetCoupled(2, 1, (1, 1, 1))
1712
+ |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
1713
+ >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
1714
+ |2,1,j1=1,j2=1,j3=1,j(1,2)=2>
1715
+ >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
1716
+ |2,1,j1=1,j2=1,j3=1,j(2,3)=1>
1717
+
1718
+ Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
1719
+ Note: that the resulting eigenstates are JxKetCoupled
1720
+
1721
+ >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
1722
+ |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
1723
+
1724
+ The rewrite method can be used to convert a coupled state to an uncoupled
1725
+ state. This is done by passing coupled=False to the rewrite function:
1726
+
1727
+ >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
1728
+ -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
1729
+
1730
+ Get the vector representation of a state in terms of the basis elements
1731
+ of the Jx operator:
1732
+
1733
+ >>> from sympy.physics.quantum.represent import represent
1734
+ >>> from sympy.physics.quantum.spin import Jx
1735
+ >>> from sympy import S
1736
+ >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
1737
+ Matrix([
1738
+ [ 0],
1739
+ [ 1/2],
1740
+ [sqrt(2)/2],
1741
+ [ 1/2]])
1742
+
1743
+ See Also
1744
+ ========
1745
+
1746
+ JzKet: Normal spin eigenstates
1747
+ uncouple: Uncoupling of coupling spin states
1748
+ couple: Coupling of uncoupled spin states
1749
+
1750
+ """
1751
+
1752
+ @classmethod
1753
+ def dual_class(self):
1754
+ return JzBraCoupled
1755
+
1756
+ @classmethod
1757
+ def uncoupled_class(self):
1758
+ return JzKet
1759
+
1760
+ def _represent_default_basis(self, **options):
1761
+ return self._represent_JzOp(None, **options)
1762
+
1763
+ def _represent_JxOp(self, basis, **options):
1764
+ return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
1765
+
1766
+ def _represent_JyOp(self, basis, **options):
1767
+ return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
1768
+
1769
+ def _represent_JzOp(self, basis, **options):
1770
+ return self._represent_coupled_base(**options)
1771
+
1772
+
1773
+ class JzBraCoupled(CoupledSpinState, Bra):
1774
+ """Coupled eigenbra of Jz.
1775
+
1776
+ See the JzKetCoupled for the usage of coupled spin eigenstates.
1777
+
1778
+ See Also
1779
+ ========
1780
+
1781
+ JzKetCoupled: Usage of coupled spin states
1782
+
1783
+ """
1784
+
1785
+ @classmethod
1786
+ def dual_class(self):
1787
+ return JzKetCoupled
1788
+
1789
+ @classmethod
1790
+ def uncoupled_class(self):
1791
+ return JzBra
1792
+
1793
+ #-----------------------------------------------------------------------------
1794
+ # Coupling/uncoupling
1795
+ #-----------------------------------------------------------------------------
1796
+
1797
+
1798
+ def couple(expr, jcoupling_list=None):
1799
+ """ Couple a tensor product of spin states
1800
+
1801
+ This function can be used to couple an uncoupled tensor product of spin
1802
+ states. All of the eigenstates to be coupled must be of the same class. It
1803
+ will return a linear combination of eigenstates that are subclasses of
1804
+ CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
1805
+ coefficients.
1806
+
1807
+ Parameters
1808
+ ==========
1809
+
1810
+ expr : Expr
1811
+ An expression involving TensorProducts of spin states to be coupled.
1812
+ Each state must be a subclass of SpinState and they all must be the
1813
+ same class.
1814
+
1815
+ jcoupling_list : list or tuple
1816
+ Elements of this list are sub-lists of length 2 specifying the order of
1817
+ the coupling of the spin spaces. The length of this must be N-1, where N
1818
+ is the number of states in the tensor product to be coupled. The
1819
+ elements of this sublist are the same as the first two elements of each
1820
+ sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
1821
+ parameter is not specified, the default value is taken, which couples
1822
+ the first and second product basis spaces, then couples this new coupled
1823
+ space to the third product space, etc
1824
+
1825
+ Examples
1826
+ ========
1827
+
1828
+ Couple a tensor product of numerical states for two spaces:
1829
+
1830
+ >>> from sympy.physics.quantum.spin import JzKet, couple
1831
+ >>> from sympy.physics.quantum.tensorproduct import TensorProduct
1832
+ >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
1833
+ -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
1834
+
1835
+
1836
+ Numerical coupling of three spaces using the default coupling method, i.e.
1837
+ first and second spaces couple, then this couples to the third space:
1838
+
1839
+ >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
1840
+ 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
1841
+
1842
+ Perform this same coupling, but we define the coupling to first couple
1843
+ the first and third spaces:
1844
+
1845
+ >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
1846
+ 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
1847
+
1848
+ Couple a tensor product of symbolic states:
1849
+
1850
+ >>> from sympy import symbols
1851
+ >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
1852
+ >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
1853
+ Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
1854
+
1855
+ """
1856
+ a = expr.atoms(TensorProduct)
1857
+ for tp in a:
1858
+ # Allow other tensor products to be in expression
1859
+ if not all(isinstance(state, SpinState) for state in tp.args):
1860
+ continue
1861
+ # If tensor product has all spin states, raise error for invalid tensor product state
1862
+ if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
1863
+ raise TypeError('All states must be the same basis')
1864
+ expr = expr.subs(tp, _couple(tp, jcoupling_list))
1865
+ return expr
1866
+
1867
+
1868
+ def _couple(tp, jcoupling_list):
1869
+ states = tp.args
1870
+ coupled_evect = states[0].coupled_class()
1871
+
1872
+ # Define default coupling if none is specified
1873
+ if jcoupling_list is None:
1874
+ jcoupling_list = []
1875
+ for n in range(1, len(states)):
1876
+ jcoupling_list.append( (1, n + 1) )
1877
+
1878
+ # Check jcoupling_list valid
1879
+ if not len(jcoupling_list) == len(states) - 1:
1880
+ raise TypeError('jcoupling_list must be length %d, got %d' %
1881
+ (len(states) - 1, len(jcoupling_list)))
1882
+ if not all( len(coupling) == 2 for coupling in jcoupling_list):
1883
+ raise ValueError('Each coupling must define 2 spaces')
1884
+ if any(n1 == n2 for n1, n2 in jcoupling_list):
1885
+ raise ValueError('Spin spaces cannot couple to themselves')
1886
+ if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
1887
+ j_test = [0]*len(states)
1888
+ for n1, n2 in jcoupling_list:
1889
+ if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
1890
+ raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
1891
+ j_test[max(n1, n2) - 1] = -1
1892
+
1893
+ # j values of states to be coupled together
1894
+ jn = [state.j for state in states]
1895
+ mn = [state.m for state in states]
1896
+
1897
+ # Create coupling_list, which defines all the couplings between all
1898
+ # the spaces from jcoupling_list
1899
+ coupling_list = []
1900
+ n_list = [ [i + 1] for i in range(len(states)) ]
1901
+ for j_coupling in jcoupling_list:
1902
+ # Least n for all j_n which is coupled as first and second spaces
1903
+ n1, n2 = j_coupling
1904
+ # List of all n's coupled in first and second spaces
1905
+ j1_n = list(n_list[n1 - 1])
1906
+ j2_n = list(n_list[n2 - 1])
1907
+ coupling_list.append( (j1_n, j2_n) )
1908
+ # Set new j_n to be coupling of all j_n in both first and second spaces
1909
+ n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
1910
+
1911
+ if all(state.j.is_number and state.m.is_number for state in states):
1912
+ # Numerical coupling
1913
+ # Iterate over difference between maximum possible j value of each coupling and the actual value
1914
+ diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
1915
+ coupling[1] ] ) for coupling in coupling_list ]
1916
+ result = []
1917
+ for diff in range(diff_max[-1] + 1):
1918
+ # Determine available configurations
1919
+ n = len(coupling_list)
1920
+ tot = binomial(diff + n - 1, diff)
1921
+
1922
+ for config_num in range(tot):
1923
+ diff_list = _confignum_to_difflist(config_num, diff, n)
1924
+
1925
+ # Skip the configuration if non-physical
1926
+ # This is a lazy check for physical states given the loose restrictions of diff_max
1927
+ if any(d > m for d, m in zip(diff_list, diff_max)):
1928
+ continue
1929
+
1930
+ # Determine term
1931
+ cg_terms = []
1932
+ coupled_j = list(jn)
1933
+ jcoupling = []
1934
+ for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
1935
+ j1 = coupled_j[ min(j1_n) - 1 ]
1936
+ j2 = coupled_j[ min(j2_n) - 1 ]
1937
+ j3 = j1 + j2 - coupling_diff
1938
+ coupled_j[ min(j1_n + j2_n) - 1 ] = j3
1939
+ m1 = Add( *[ mn[x - 1] for x in j1_n] )
1940
+ m2 = Add( *[ mn[x - 1] for x in j2_n] )
1941
+ m3 = m1 + m2
1942
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
1943
+ jcoupling.append( (min(j1_n), min(j2_n), j3) )
1944
+ # Better checks that state is physical
1945
+ if any(abs(term[5]) > term[4] for term in cg_terms):
1946
+ continue
1947
+ if any(term[0] + term[2] < term[4] for term in cg_terms):
1948
+ continue
1949
+ if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
1950
+ continue
1951
+ coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
1952
+ state = coupled_evect(j3, m3, jn, jcoupling)
1953
+ result.append(coeff*state)
1954
+ return Add(*result)
1955
+ else:
1956
+ # Symbolic coupling
1957
+ cg_terms = []
1958
+ jcoupling = []
1959
+ sum_terms = []
1960
+ coupled_j = list(jn)
1961
+ for j1_n, j2_n in coupling_list:
1962
+ j1 = coupled_j[ min(j1_n) - 1 ]
1963
+ j2 = coupled_j[ min(j2_n) - 1 ]
1964
+ if len(j1_n + j2_n) == len(states):
1965
+ j3 = symbols('j')
1966
+ else:
1967
+ j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
1968
+ j3 = symbols(j3_name)
1969
+ coupled_j[ min(j1_n + j2_n) - 1 ] = j3
1970
+ m1 = Add( *[ mn[x - 1] for x in j1_n] )
1971
+ m2 = Add( *[ mn[x - 1] for x in j2_n] )
1972
+ m3 = m1 + m2
1973
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
1974
+ jcoupling.append( (min(j1_n), min(j2_n), j3) )
1975
+ sum_terms.append((j3, m3, j1 + j2))
1976
+ coeff = Mul( *[ CG(*term) for term in cg_terms] )
1977
+ state = coupled_evect(j3, m3, jn, jcoupling)
1978
+ return Sum(coeff*state, *sum_terms)
1979
+
1980
+
1981
+ def uncouple(expr, jn=None, jcoupling_list=None):
1982
+ """ Uncouple a coupled spin state
1983
+
1984
+ Gives the uncoupled representation of a coupled spin state. Arguments must
1985
+ be either a spin state that is a subclass of CoupledSpinState or a spin
1986
+ state that is a subclass of SpinState and an array giving the j values
1987
+ of the spaces that are to be coupled
1988
+
1989
+ Parameters
1990
+ ==========
1991
+
1992
+ expr : Expr
1993
+ The expression containing states that are to be coupled. If the states
1994
+ are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
1995
+ must be defined. If the states are a subclass of CoupledSpinState,
1996
+ ``jn`` and ``jcoupling`` will be taken from the state.
1997
+
1998
+ jn : list or tuple
1999
+ The list of the j-values that are coupled. If state is a
2000
+ CoupledSpinState, this parameter is ignored. This must be defined if
2001
+ state is not a subclass of CoupledSpinState. The syntax of this
2002
+ parameter is the same as the ``jn`` parameter of JzKetCoupled.
2003
+
2004
+ jcoupling_list : list or tuple
2005
+ The list defining how the j-values are coupled together. If state is a
2006
+ CoupledSpinState, this parameter is ignored. This must be defined if
2007
+ state is not a subclass of CoupledSpinState. The syntax of this
2008
+ parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
2009
+
2010
+ Examples
2011
+ ========
2012
+
2013
+ Uncouple a numerical state using a CoupledSpinState state:
2014
+
2015
+ >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
2016
+ >>> from sympy import S
2017
+ >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
2018
+ sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
2019
+
2020
+ Perform the same calculation using a SpinState state:
2021
+
2022
+ >>> from sympy.physics.quantum.spin import JzKet
2023
+ >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
2024
+ sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
2025
+
2026
+ Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
2027
+
2028
+ >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
2029
+ |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
2030
+
2031
+ Perform the same calculation using a SpinState state:
2032
+
2033
+ >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
2034
+ |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
2035
+
2036
+ Uncouple a symbolic state using a CoupledSpinState state:
2037
+
2038
+ >>> from sympy import symbols
2039
+ >>> j,m,j1,j2 = symbols('j m j1 j2')
2040
+ >>> uncouple(JzKetCoupled(j, m, (j1, j2)))
2041
+ Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
2042
+
2043
+ Perform the same calculation using a SpinState state
2044
+
2045
+ >>> uncouple(JzKet(j, m), (j1, j2))
2046
+ Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
2047
+
2048
+ """
2049
+ a = expr.atoms(SpinState)
2050
+ for state in a:
2051
+ expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
2052
+ return expr
2053
+
2054
+
2055
+ def _uncouple(state, jn, jcoupling_list):
2056
+ if isinstance(state, CoupledSpinState):
2057
+ jn = state.jn
2058
+ coupled_n = state.coupled_n
2059
+ coupled_jn = state.coupled_jn
2060
+ evect = state.uncoupled_class()
2061
+ elif isinstance(state, SpinState):
2062
+ if jn is None:
2063
+ raise ValueError("Must specify j-values for coupled state")
2064
+ if not isinstance(jn, (list, tuple)):
2065
+ raise TypeError("jn must be list or tuple")
2066
+ if jcoupling_list is None:
2067
+ # Use default
2068
+ jcoupling_list = []
2069
+ for i in range(1, len(jn)):
2070
+ jcoupling_list.append(
2071
+ (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
2072
+ if not isinstance(jcoupling_list, (list, tuple)):
2073
+ raise TypeError("jcoupling must be a list or tuple")
2074
+ if not len(jcoupling_list) == len(jn) - 1:
2075
+ raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
2076
+ coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
2077
+ evect = state.__class__
2078
+ else:
2079
+ raise TypeError("state must be a spin state")
2080
+ j = state.j
2081
+ m = state.m
2082
+ coupling_list = []
2083
+ j_list = list(jn)
2084
+
2085
+ # Create coupling, which defines all the couplings between all the spaces
2086
+ for j3, (n1, n2) in zip(coupled_jn, coupled_n):
2087
+ # j's which are coupled as first and second spaces
2088
+ j1 = j_list[n1[0] - 1]
2089
+ j2 = j_list[n2[0] - 1]
2090
+ # Build coupling list
2091
+ coupling_list.append( (n1, n2, j1, j2, j3) )
2092
+ # Set new value in j_list
2093
+ j_list[min(n1 + n2) - 1] = j3
2094
+
2095
+ if j.is_number and m.is_number:
2096
+ diff_max = [ 2*x for x in jn ]
2097
+ diff = Add(*jn) - m
2098
+
2099
+ n = len(jn)
2100
+ tot = binomial(diff + n - 1, diff)
2101
+
2102
+ result = []
2103
+ for config_num in range(tot):
2104
+ diff_list = _confignum_to_difflist(config_num, diff, n)
2105
+ if any(d > p for d, p in zip(diff_list, diff_max)):
2106
+ continue
2107
+
2108
+ cg_terms = []
2109
+ for coupling in coupling_list:
2110
+ j1_n, j2_n, j1, j2, j3 = coupling
2111
+ m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
2112
+ m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
2113
+ m3 = m1 + m2
2114
+ cg_terms.append( (j1, m1, j2, m2, j3, m3) )
2115
+ coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
2116
+ state = TensorProduct(
2117
+ *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
2118
+ result.append(coeff*state)
2119
+ return Add(*result)
2120
+ else:
2121
+ # Symbolic coupling
2122
+ m_str = "m1:%d" % (len(jn) + 1)
2123
+ mvals = symbols(m_str)
2124
+ cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
2125
+ j2, Add(*[mvals[n - 1] for n in j2_n]),
2126
+ j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
2127
+ cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
2128
+ j2, Add(*[mvals[n - 1] for n in j2_n]),
2129
+ j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
2130
+ cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
2131
+ sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
2132
+ state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
2133
+ return Sum(cg_coeff*state, *sum_terms)
2134
+
2135
+
2136
+ def _confignum_to_difflist(config_num, diff, list_len):
2137
+ # Determines configuration of diffs into list_len number of slots
2138
+ diff_list = []
2139
+ for n in range(list_len):
2140
+ prev_diff = diff
2141
+ # Number of spots after current one
2142
+ rem_spots = list_len - n - 1
2143
+ # Number of configurations of distributing diff among the remaining spots
2144
+ rem_configs = binomial(diff + rem_spots - 1, diff)
2145
+ while config_num >= rem_configs:
2146
+ config_num -= rem_configs
2147
+ diff -= 1
2148
+ rem_configs = binomial(diff + rem_spots - 1, diff)
2149
+ diff_list.append(prev_diff - diff)
2150
+ return diff_list
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract tensor product."""
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.sympify import sympify
8
+ from sympy.matrices.dense import DenseMatrix as Matrix
9
+ from sympy.matrices.immutable import ImmutableDenseMatrix as ImmutableMatrix
10
+ from sympy.printing.pretty.stringpict import prettyForm
11
+
12
+ from sympy.physics.quantum.qexpr import QuantumError
13
+ from sympy.physics.quantum.dagger import Dagger
14
+ from sympy.physics.quantum.commutator import Commutator
15
+ from sympy.physics.quantum.anticommutator import AntiCommutator
16
+ from sympy.physics.quantum.state import Ket, Bra
17
+ from sympy.physics.quantum.matrixutils import (
18
+ numpy_ndarray,
19
+ scipy_sparse_matrix,
20
+ matrix_tensor_product
21
+ )
22
+ from sympy.physics.quantum.trace import Tr
23
+
24
+
25
+ __all__ = [
26
+ 'TensorProduct',
27
+ 'tensor_product_simp'
28
+ ]
29
+
30
+ #-----------------------------------------------------------------------------
31
+ # Tensor product
32
+ #-----------------------------------------------------------------------------
33
+
34
+ _combined_printing = False
35
+
36
+
37
+ def combined_tensor_printing(combined):
38
+ """Set flag controlling whether tensor products of states should be
39
+ printed as a combined bra/ket or as an explicit tensor product of different
40
+ bra/kets. This is a global setting for all TensorProduct class instances.
41
+
42
+ Parameters
43
+ ----------
44
+ combine : bool
45
+ When true, tensor product states are combined into one ket/bra, and
46
+ when false explicit tensor product notation is used between each
47
+ ket/bra.
48
+ """
49
+ global _combined_printing
50
+ _combined_printing = combined
51
+
52
+
53
+ class TensorProduct(Expr):
54
+ """The tensor product of two or more arguments.
55
+
56
+ For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
57
+ or tensor product matrix. For other objects a symbolic ``TensorProduct``
58
+ instance is returned. The tensor product is a non-commutative
59
+ multiplication that is used primarily with operators and states in quantum
60
+ mechanics.
61
+
62
+ Currently, the tensor product distinguishes between commutative and
63
+ non-commutative arguments. Commutative arguments are assumed to be scalars
64
+ and are pulled out in front of the ``TensorProduct``. Non-commutative
65
+ arguments remain in the resulting ``TensorProduct``.
66
+
67
+ Parameters
68
+ ==========
69
+
70
+ args : tuple
71
+ A sequence of the objects to take the tensor product of.
72
+
73
+ Examples
74
+ ========
75
+
76
+ Start with a simple tensor product of SymPy matrices::
77
+
78
+ >>> from sympy import Matrix
79
+ >>> from sympy.physics.quantum import TensorProduct
80
+
81
+ >>> m1 = Matrix([[1,2],[3,4]])
82
+ >>> m2 = Matrix([[1,0],[0,1]])
83
+ >>> TensorProduct(m1, m2)
84
+ Matrix([
85
+ [1, 0, 2, 0],
86
+ [0, 1, 0, 2],
87
+ [3, 0, 4, 0],
88
+ [0, 3, 0, 4]])
89
+ >>> TensorProduct(m2, m1)
90
+ Matrix([
91
+ [1, 2, 0, 0],
92
+ [3, 4, 0, 0],
93
+ [0, 0, 1, 2],
94
+ [0, 0, 3, 4]])
95
+
96
+ We can also construct tensor products of non-commutative symbols:
97
+
98
+ >>> from sympy import Symbol
99
+ >>> A = Symbol('A',commutative=False)
100
+ >>> B = Symbol('B',commutative=False)
101
+ >>> tp = TensorProduct(A, B)
102
+ >>> tp
103
+ AxB
104
+
105
+ We can take the dagger of a tensor product (note the order does NOT reverse
106
+ like the dagger of a normal product):
107
+
108
+ >>> from sympy.physics.quantum import Dagger
109
+ >>> Dagger(tp)
110
+ Dagger(A)xDagger(B)
111
+
112
+ Expand can be used to distribute a tensor product across addition:
113
+
114
+ >>> C = Symbol('C',commutative=False)
115
+ >>> tp = TensorProduct(A+B,C)
116
+ >>> tp
117
+ (A + B)xC
118
+ >>> tp.expand(tensorproduct=True)
119
+ AxC + BxC
120
+ """
121
+ is_commutative = False
122
+
123
+ def __new__(cls, *args):
124
+ if isinstance(args[0], (Matrix, ImmutableMatrix, numpy_ndarray,
125
+ scipy_sparse_matrix)):
126
+ return matrix_tensor_product(*args)
127
+ c_part, new_args = cls.flatten(sympify(args))
128
+ c_part = Mul(*c_part)
129
+ if len(new_args) == 0:
130
+ return c_part
131
+ elif len(new_args) == 1:
132
+ return c_part * new_args[0]
133
+ else:
134
+ tp = Expr.__new__(cls, *new_args)
135
+ return c_part * tp
136
+
137
+ @classmethod
138
+ def flatten(cls, args):
139
+ # TODO: disallow nested TensorProducts.
140
+ c_part = []
141
+ nc_parts = []
142
+ for arg in args:
143
+ cp, ncp = arg.args_cnc()
144
+ c_part.extend(list(cp))
145
+ nc_parts.append(Mul._from_args(ncp))
146
+ return c_part, nc_parts
147
+
148
+ def _eval_adjoint(self):
149
+ return TensorProduct(*[Dagger(i) for i in self.args])
150
+
151
+ def _eval_rewrite(self, rule, args, **hints):
152
+ return TensorProduct(*args).expand(tensorproduct=True)
153
+
154
+ def _sympystr(self, printer, *args):
155
+ length = len(self.args)
156
+ s = ''
157
+ for i in range(length):
158
+ if isinstance(self.args[i], (Add, Pow, Mul)):
159
+ s = s + '('
160
+ s = s + printer._print(self.args[i])
161
+ if isinstance(self.args[i], (Add, Pow, Mul)):
162
+ s = s + ')'
163
+ if i != length - 1:
164
+ s = s + 'x'
165
+ return s
166
+
167
+ def _pretty(self, printer, *args):
168
+
169
+ if (_combined_printing and
170
+ (all(isinstance(arg, Ket) for arg in self.args) or
171
+ all(isinstance(arg, Bra) for arg in self.args))):
172
+
173
+ length = len(self.args)
174
+ pform = printer._print('', *args)
175
+ for i in range(length):
176
+ next_pform = printer._print('', *args)
177
+ length_i = len(self.args[i].args)
178
+ for j in range(length_i):
179
+ part_pform = printer._print(self.args[i].args[j], *args)
180
+ next_pform = prettyForm(*next_pform.right(part_pform))
181
+ if j != length_i - 1:
182
+ next_pform = prettyForm(*next_pform.right(', '))
183
+
184
+ if len(self.args[i].args) > 1:
185
+ next_pform = prettyForm(
186
+ *next_pform.parens(left='{', right='}'))
187
+ pform = prettyForm(*pform.right(next_pform))
188
+ if i != length - 1:
189
+ pform = prettyForm(*pform.right(',' + ' '))
190
+
191
+ pform = prettyForm(*pform.left(self.args[0].lbracket))
192
+ pform = prettyForm(*pform.right(self.args[0].rbracket))
193
+ return pform
194
+
195
+ length = len(self.args)
196
+ pform = printer._print('', *args)
197
+ for i in range(length):
198
+ next_pform = printer._print(self.args[i], *args)
199
+ if isinstance(self.args[i], (Add, Mul)):
200
+ next_pform = prettyForm(
201
+ *next_pform.parens(left='(', right=')')
202
+ )
203
+ pform = prettyForm(*pform.right(next_pform))
204
+ if i != length - 1:
205
+ if printer._use_unicode:
206
+ pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
207
+ else:
208
+ pform = prettyForm(*pform.right('x' + ' '))
209
+ return pform
210
+
211
+ def _latex(self, printer, *args):
212
+
213
+ if (_combined_printing and
214
+ (all(isinstance(arg, Ket) for arg in self.args) or
215
+ all(isinstance(arg, Bra) for arg in self.args))):
216
+
217
+ def _label_wrap(label, nlabels):
218
+ return label if nlabels == 1 else r"\left\{%s\right\}" % label
219
+
220
+ s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
221
+ len(arg.args)) for arg in self.args])
222
+
223
+ return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
224
+ self.args[0].rbracket_latex)
225
+
226
+ length = len(self.args)
227
+ s = ''
228
+ for i in range(length):
229
+ if isinstance(self.args[i], (Add, Mul)):
230
+ s = s + '\\left('
231
+ # The extra {} brackets are needed to get matplotlib's latex
232
+ # rendered to render this properly.
233
+ s = s + '{' + printer._print(self.args[i], *args) + '}'
234
+ if isinstance(self.args[i], (Add, Mul)):
235
+ s = s + '\\right)'
236
+ if i != length - 1:
237
+ s = s + '\\otimes '
238
+ return s
239
+
240
+ def doit(self, **hints):
241
+ return TensorProduct(*[item.doit(**hints) for item in self.args])
242
+
243
+ def _eval_expand_tensorproduct(self, **hints):
244
+ """Distribute TensorProducts across addition."""
245
+ args = self.args
246
+ add_args = []
247
+ for i in range(len(args)):
248
+ if isinstance(args[i], Add):
249
+ for aa in args[i].args:
250
+ tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
251
+ c_part, nc_part = tp.args_cnc()
252
+ # Check for TensorProduct object: is the one object in nc_part, if any:
253
+ # (Note: any other object type to be expanded must be added here)
254
+ if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct):
255
+ nc_part = (nc_part[0]._eval_expand_tensorproduct(), )
256
+ add_args.append(Mul(*c_part)*Mul(*nc_part))
257
+ break
258
+
259
+ if add_args:
260
+ return Add(*add_args)
261
+ else:
262
+ return self
263
+
264
+ def _eval_trace(self, **kwargs):
265
+ indices = kwargs.get('indices', None)
266
+ exp = tensor_product_simp(self)
267
+
268
+ if indices is None or len(indices) == 0:
269
+ return Mul(*[Tr(arg).doit() for arg in exp.args])
270
+ else:
271
+ return Mul(*[Tr(value).doit() if idx in indices else value
272
+ for idx, value in enumerate(exp.args)])
273
+
274
+
275
+ def tensor_product_simp_Mul(e):
276
+ """Simplify a Mul with TensorProducts.
277
+
278
+ Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
279
+ to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
280
+ simple cases where the initial ``Mul`` only has scalars and raw
281
+ ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
282
+ ``TensorProduct``s.
283
+
284
+ Parameters
285
+ ==========
286
+
287
+ e : Expr
288
+ A ``Mul`` of ``TensorProduct``s to be simplified.
289
+
290
+ Returns
291
+ =======
292
+
293
+ e : Expr
294
+ A ``TensorProduct`` of ``Mul``s.
295
+
296
+ Examples
297
+ ========
298
+
299
+ This is an example of the type of simplification that this function
300
+ performs::
301
+
302
+ >>> from sympy.physics.quantum.tensorproduct import \
303
+ tensor_product_simp_Mul, TensorProduct
304
+ >>> from sympy import Symbol
305
+ >>> A = Symbol('A',commutative=False)
306
+ >>> B = Symbol('B',commutative=False)
307
+ >>> C = Symbol('C',commutative=False)
308
+ >>> D = Symbol('D',commutative=False)
309
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
310
+ >>> e
311
+ AxB*CxD
312
+ >>> tensor_product_simp_Mul(e)
313
+ (A*C)x(B*D)
314
+
315
+ """
316
+ # TODO: This won't work with Muls that have other composites of
317
+ # TensorProducts, like an Add, Commutator, etc.
318
+ # TODO: This only works for the equivalent of single Qbit gates.
319
+ if not isinstance(e, Mul):
320
+ return e
321
+ c_part, nc_part = e.args_cnc()
322
+ n_nc = len(nc_part)
323
+ if n_nc == 0:
324
+ return e
325
+ elif n_nc == 1:
326
+ if isinstance(nc_part[0], Pow):
327
+ return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])
328
+ return e
329
+ elif e.has(TensorProduct):
330
+ current = nc_part[0]
331
+ if not isinstance(current, TensorProduct):
332
+ if isinstance(current, Pow):
333
+ if isinstance(current.base, TensorProduct):
334
+ current = tensor_product_simp_Pow(current)
335
+ else:
336
+ raise TypeError('TensorProduct expected, got: %r' % current)
337
+ n_terms = len(current.args)
338
+ new_args = list(current.args)
339
+ for next in nc_part[1:]:
340
+ # TODO: check the hilbert spaces of next and current here.
341
+ if isinstance(next, TensorProduct):
342
+ if n_terms != len(next.args):
343
+ raise QuantumError(
344
+ 'TensorProducts of different lengths: %r and %r' %
345
+ (current, next)
346
+ )
347
+ for i in range(len(new_args)):
348
+ new_args[i] = new_args[i] * next.args[i]
349
+ else:
350
+ if isinstance(next, Pow):
351
+ if isinstance(next.base, TensorProduct):
352
+ new_tp = tensor_product_simp_Pow(next)
353
+ for i in range(len(new_args)):
354
+ new_args[i] = new_args[i] * new_tp.args[i]
355
+ else:
356
+ raise TypeError('TensorProduct expected, got: %r' % next)
357
+ else:
358
+ raise TypeError('TensorProduct expected, got: %r' % next)
359
+ current = next
360
+ return Mul(*c_part) * TensorProduct(*new_args)
361
+ elif e.has(Pow):
362
+ new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]
363
+ return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))
364
+ else:
365
+ return e
366
+
367
+ def tensor_product_simp_Pow(e):
368
+ """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""
369
+ if not isinstance(e, Pow):
370
+ return e
371
+
372
+ if isinstance(e.base, TensorProduct):
373
+ return TensorProduct(*[ b**e.exp for b in e.base.args])
374
+ else:
375
+ return e
376
+
377
+ def tensor_product_simp(e, **hints):
378
+ """Try to simplify and combine TensorProducts.
379
+
380
+ In general this will try to pull expressions inside of ``TensorProducts``.
381
+ It currently only works for relatively simple cases where the products have
382
+ only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
383
+ of ``TensorProducts``. It is best to see what it does by showing examples.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy.physics.quantum import tensor_product_simp
389
+ >>> from sympy.physics.quantum import TensorProduct
390
+ >>> from sympy import Symbol
391
+ >>> A = Symbol('A',commutative=False)
392
+ >>> B = Symbol('B',commutative=False)
393
+ >>> C = Symbol('C',commutative=False)
394
+ >>> D = Symbol('D',commutative=False)
395
+
396
+ First see what happens to products of tensor products:
397
+
398
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
399
+ >>> e
400
+ AxB*CxD
401
+ >>> tensor_product_simp(e)
402
+ (A*C)x(B*D)
403
+
404
+ This is the core logic of this function, and it works inside, powers, sums,
405
+ commutators and anticommutators as well:
406
+
407
+ >>> tensor_product_simp(e**2)
408
+ (A*C)x(B*D)**2
409
+
410
+ """
411
+ if isinstance(e, Add):
412
+ return Add(*[tensor_product_simp(arg) for arg in e.args])
413
+ elif isinstance(e, Pow):
414
+ if isinstance(e.base, TensorProduct):
415
+ return tensor_product_simp_Pow(e)
416
+ else:
417
+ return tensor_product_simp(e.base) ** e.exp
418
+ elif isinstance(e, Mul):
419
+ return tensor_product_simp_Mul(e)
420
+ elif isinstance(e, Commutator):
421
+ return Commutator(*[tensor_product_simp(arg) for arg in e.args])
422
+ elif isinstance(e, AntiCommutator):
423
+ return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
424
+ else:
425
+ return e
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_boson.cpython-310.pyc ADDED
Binary file (1.68 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_constants.cpython-310.pyc ADDED
Binary file (588 Bytes). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_dagger.cpython-310.pyc ADDED
Binary file (3.52 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_density.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc ADDED
Binary file (1.84 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_gate.cpython-310.pyc ADDED
Binary file (12 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_identitysearch.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc ADDED
Binary file (5.3 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_piab.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc ADDED
Binary file (6.21 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_shor.cpython-310.pyc ADDED
Binary file (1.02 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_anticommutator.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Integer
2
+ from sympy.core.symbol import symbols
3
+
4
+ from sympy.physics.quantum.dagger import Dagger
5
+ from sympy.physics.quantum.anticommutator import AntiCommutator as AComm
6
+ from sympy.physics.quantum.operator import Operator
7
+
8
+
9
+ a, b, c = symbols('a,b,c')
10
+ A, B, C, D = symbols('A,B,C,D', commutative=False)
11
+
12
+
13
+ def test_anticommutator():
14
+ ac = AComm(A, B)
15
+ assert isinstance(ac, AComm)
16
+ assert ac.is_commutative is False
17
+ assert ac.subs(A, C) == AComm(C, B)
18
+
19
+
20
+ def test_commutator_identities():
21
+ assert AComm(a*A, b*B) == a*b*AComm(A, B)
22
+ assert AComm(A, A) == 2*A**2
23
+ assert AComm(A, B) == AComm(B, A)
24
+ assert AComm(a, b) == 2*a*b
25
+ assert AComm(A, B).doit() == A*B + B*A
26
+
27
+
28
+ def test_anticommutator_dagger():
29
+ assert Dagger(AComm(A, B)) == AComm(Dagger(A), Dagger(B))
30
+
31
+
32
+ class Foo(Operator):
33
+
34
+ def _eval_anticommutator_Bar(self, bar):
35
+ return Integer(0)
36
+
37
+
38
+ class Bar(Operator):
39
+ pass
40
+
41
+
42
+ class Tam(Operator):
43
+
44
+ def _eval_anticommutator_Foo(self, foo):
45
+ return Integer(1)
46
+
47
+
48
+ def test_eval_commutator():
49
+ F = Foo('F')
50
+ B = Bar('B')
51
+ T = Tam('T')
52
+ assert AComm(F, B).doit() == 0
53
+ assert AComm(B, F).doit() == 0
54
+ assert AComm(F, T).doit() == 1
55
+ assert AComm(T, F).doit() == 1
56
+ assert AComm(B, T).doit() == B*T + T*B
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.core.numbers import Rational
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.physics.quantum import Dagger, Commutator, qapply
7
+ from sympy.physics.quantum.boson import BosonOp
8
+ from sympy.physics.quantum.boson import (
9
+ BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra)
10
+
11
+
12
+ def test_bosonoperator():
13
+ a = BosonOp('a')
14
+ b = BosonOp('b')
15
+
16
+ assert isinstance(a, BosonOp)
17
+ assert isinstance(Dagger(a), BosonOp)
18
+
19
+ assert a.is_annihilation
20
+ assert not Dagger(a).is_annihilation
21
+
22
+ assert BosonOp("a") == BosonOp("a", True)
23
+ assert BosonOp("a") != BosonOp("c")
24
+ assert BosonOp("a", True) != BosonOp("a", False)
25
+
26
+ assert Commutator(a, Dagger(a)).doit() == 1
27
+
28
+ assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a
29
+
30
+ assert Dagger(exp(a)) == exp(Dagger(a))
31
+
32
+
33
+ def test_boson_states():
34
+ a = BosonOp("a")
35
+
36
+ # Fock states
37
+ n = 3
38
+ assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0
39
+ assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1
40
+ assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \
41
+ == sqrt(prod(range(1, n+1)))
42
+
43
+ # Coherent states
44
+ alpha1, alpha2 = 1.2, 4.3
45
+ assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1
46
+ assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1
47
+ assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() -
48
+ exp((alpha1 - alpha2) ** 2 * Rational(-1, 2))) < 1e-12
49
+ assert qapply(a * BosonCoherentKet(alpha1)) == \
50
+ alpha1 * BosonCoherentKet(alpha1)
pllava/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for cartesian.py"""
2
+
3
+ from sympy.core.numbers import (I, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.exponential import exp
7
+ from sympy.functions.elementary.miscellaneous import sqrt
8
+ from sympy.functions.special.delta_functions import DiracDelta
9
+ from sympy.sets.sets import Interval
10
+
11
+ from sympy.physics.quantum import qapply, represent, L2, Dagger
12
+ from sympy.physics.quantum import Commutator, hbar
13
+ from sympy.physics.quantum.cartesian import (
14
+ XOp, YOp, ZOp, PxOp, X, Y, Z, Px, XKet, XBra, PxKet, PxBra,
15
+ PositionKet3D, PositionBra3D
16
+ )
17
+ from sympy.physics.quantum.operator import DifferentialOperator
18
+
19
+ x, y, z, x_1, x_2, x_3, y_1, z_1 = symbols('x,y,z,x_1,x_2,x_3,y_1,z_1')
20
+ px, py, px_1, px_2 = symbols('px py px_1 px_2')
21
+
22
+
23
+ def test_x():
24
+ assert X.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
25
+ assert Commutator(X, Px).doit() == I*hbar
26
+ assert qapply(X*XKet(x)) == x*XKet(x)
27
+ assert XKet(x).dual_class() == XBra
28
+ assert XBra(x).dual_class() == XKet
29
+ assert (Dagger(XKet(y))*XKet(x)).doit() == DiracDelta(x - y)
30
+ assert (PxBra(px)*XKet(x)).doit() == \
31
+ exp(-I*x*px/hbar)/sqrt(2*pi*hbar)
32
+ assert represent(XKet(x)) == DiracDelta(x - x_1)
33
+ assert represent(XBra(x)) == DiracDelta(-x + x_1)
34
+ assert XBra(x).position == x
35
+ assert represent(XOp()*XKet()) == x*DiracDelta(x - x_2)
36
+ assert represent(XOp()*XKet()*XBra('y')) == \
37
+ x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
38
+ assert represent(XBra("y")*XKet()) == DiracDelta(x - y)
39
+ assert represent(
40
+ XKet()*XBra()) == DiracDelta(x - x_2) * DiracDelta(x_1 - x)
41
+
42
+ rep_p = represent(XOp(), basis=PxOp)
43
+ assert rep_p == hbar*I*DiracDelta(px_1 - px_2)*DifferentialOperator(px_1)
44
+ assert rep_p == represent(XOp(), basis=PxOp())
45
+ assert rep_p == represent(XOp(), basis=PxKet)
46
+ assert rep_p == represent(XOp(), basis=PxKet())
47
+
48
+ assert represent(XOp()*PxKet(), basis=PxKet) == \
49
+ hbar*I*DiracDelta(px - px_2)*DifferentialOperator(px)
50
+
51
+
52
+ def test_p():
53
+ assert Px.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
54
+ assert qapply(Px*PxKet(px)) == px*PxKet(px)
55
+ assert PxKet(px).dual_class() == PxBra
56
+ assert PxBra(x).dual_class() == PxKet
57
+ assert (Dagger(PxKet(py))*PxKet(px)).doit() == DiracDelta(px - py)
58
+ assert (XBra(x)*PxKet(px)).doit() == \
59
+ exp(I*x*px/hbar)/sqrt(2*pi*hbar)
60
+ assert represent(PxKet(px)) == DiracDelta(px - px_1)
61
+
62
+ rep_x = represent(PxOp(), basis=XOp)
63
+ assert rep_x == -hbar*I*DiracDelta(x_1 - x_2)*DifferentialOperator(x_1)
64
+ assert rep_x == represent(PxOp(), basis=XOp())
65
+ assert rep_x == represent(PxOp(), basis=XKet)
66
+ assert rep_x == represent(PxOp(), basis=XKet())
67
+
68
+ assert represent(PxOp()*XKet(), basis=XKet) == \
69
+ -hbar*I*DiracDelta(x - x_2)*DifferentialOperator(x)
70
+ assert represent(XBra("y")*PxOp()*XKet(), basis=XKet) == \
71
+ -hbar*I*DiracDelta(x - y)*DifferentialOperator(x)
72
+
73
+
74
+ def test_3dpos():
75
+ assert Y.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
76
+ assert Z.hilbert_space == L2(Interval(S.NegativeInfinity, S.Infinity))
77
+
78
+ test_ket = PositionKet3D(x, y, z)
79
+ assert qapply(X*test_ket) == x*test_ket
80
+ assert qapply(Y*test_ket) == y*test_ket
81
+ assert qapply(Z*test_ket) == z*test_ket
82
+ assert qapply(X*Y*test_ket) == x*y*test_ket
83
+ assert qapply(X*Y*Z*test_ket) == x*y*z*test_ket
84
+ assert qapply(Y*Z*test_ket) == y*z*test_ket
85
+
86
+ assert PositionKet3D() == test_ket
87
+ assert YOp() == Y
88
+ assert ZOp() == Z
89
+
90
+ assert PositionKet3D.dual_class() == PositionBra3D
91
+ assert PositionBra3D.dual_class() == PositionKet3D
92
+
93
+ other_ket = PositionKet3D(x_1, y_1, z_1)
94
+ assert (Dagger(other_ket)*test_ket).doit() == \
95
+ DiracDelta(x - x_1)*DiracDelta(y - y_1)*DiracDelta(z - z_1)
96
+
97
+ assert test_ket.position_x == x
98
+ assert test_ket.position_y == y
99
+ assert test_ket.position_z == z
100
+ assert other_ket.position_x == x_1
101
+ assert other_ket.position_y == y_1
102
+ assert other_ket.position_z == z_1
103
+
104
+ # TODO: Add tests for representations