ZTWHHH commited on
Commit
9b6d659
·
verified ·
1 Parent(s): dc4505d

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 +1 -0
  2. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py +59 -0
  3. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py +341 -0
  4. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/cg.py +754 -0
  5. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py +97 -0
  6. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/density.py +319 -0
  7. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py +191 -0
  8. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py +137 -0
  9. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/operatorordering.py +290 -0
  10. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py +279 -0
  11. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/qft.py +215 -0
  12. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/shor.py +173 -0
  13. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/state.py +1017 -0
  14. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py +0 -0
  15. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc +0 -0
  16. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc +0 -0
  17. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitutils.cpython-310.pyc +0 -0
  18. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc +0 -0
  19. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_constants.cpython-310.pyc +0 -0
  20. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc +0 -0
  21. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc +0 -0
  22. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_identitysearch.cpython-310.pyc +0 -0
  23. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operator.cpython-310.pyc +0 -0
  24. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc +0 -0
  25. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc +0 -0
  26. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qapply.cpython-310.pyc +0 -0
  27. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qasm.cpython-310.pyc +0 -0
  28. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qexpr.cpython-310.pyc +0 -0
  29. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qft.cpython-310.pyc +0 -0
  30. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc +0 -0
  31. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_tensorproduct.cpython-310.pyc +0 -0
  32. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc +0 -0
  33. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_boson.py +50 -0
  34. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py +104 -0
  35. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py +13 -0
  36. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_density.py +289 -0
  37. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py +62 -0
  38. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py +360 -0
  39. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_hilbert.py +110 -0
  40. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_identitysearch.py +492 -0
  41. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_innerproduct.py +71 -0
  42. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_piab.py +29 -0
  43. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_qft.py +52 -0
  44. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py +186 -0
  45. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_state.py +248 -0
  46. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/__init__.cpython-310.pyc +0 -0
  47. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc +0 -0
  48. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/quantities.cpython-310.pyc +0 -0
  49. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc +0 -0
  50. evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1274,3 +1274,4 @@ falcon/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc
1274
  falcon/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1275
  falcon/lib/python3.10/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1276
  evalkit_tf437/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1274
  falcon/lib/python3.10/site-packages/torch/__pycache__/_meta_registrations.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1275
  falcon/lib/python3.10/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1276
  evalkit_tf437/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1277
+ evalkit_tf437/lib/python3.10/site-packages/transformers/__pycache__/training_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/__init__.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Names exposed by 'from sympy.physics.quantum import *'
2
+
3
+ __all__ = [
4
+ 'AntiCommutator',
5
+
6
+ 'qapply',
7
+
8
+ 'Commutator',
9
+
10
+ 'Dagger',
11
+
12
+ 'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace',
13
+ 'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2',
14
+ 'FockSpace',
15
+
16
+ 'InnerProduct',
17
+
18
+ 'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator',
19
+ 'OuterProduct', 'DifferentialOperator',
20
+
21
+ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result',
22
+ 'get_basis', 'enumerate_states',
23
+
24
+ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState',
25
+ 'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra',
26
+ 'OrthogonalState', 'Wavefunction',
27
+
28
+ 'TensorProduct', 'tensor_product_simp',
29
+
30
+ 'hbar', 'HBar',
31
+
32
+ ]
33
+ from .anticommutator import AntiCommutator
34
+
35
+ from .qapply import qapply
36
+
37
+ from .commutator import Commutator
38
+
39
+ from .dagger import Dagger
40
+
41
+ from .hilbert import (HilbertSpaceError, HilbertSpace,
42
+ TensorProductHilbertSpace, TensorPowerHilbertSpace,
43
+ DirectSumHilbertSpace, ComplexSpace, L2, FockSpace)
44
+
45
+ from .innerproduct import InnerProduct
46
+
47
+ from .operator import (Operator, HermitianOperator, UnitaryOperator,
48
+ IdentityOperator, OuterProduct, DifferentialOperator)
49
+
50
+ from .represent import (represent, rep_innerproduct, rep_expectation,
51
+ integrate_result, get_basis, enumerate_states)
52
+
53
+ from .state import (KetBase, BraBase, StateBase, State, Ket, Bra,
54
+ TimeDepState, TimeDepBra, TimeDepKet, OrthogonalKet,
55
+ OrthogonalBra, OrthogonalState, Wavefunction)
56
+
57
+ from .tensorproduct import TensorProduct, tensor_product_simp
58
+
59
+ from .constants import hbar, HBar
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Operators and states for 1D cartesian position and momentum.
2
+
3
+ TODO:
4
+
5
+ * Add 3D classes to mappings in operatorset.py
6
+
7
+ """
8
+
9
+ from sympy.core.numbers import (I, pi)
10
+ from sympy.core.singleton import S
11
+ from sympy.functions.elementary.exponential import exp
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.functions.special.delta_functions import DiracDelta
14
+ from sympy.sets.sets import Interval
15
+
16
+ from sympy.physics.quantum.constants import hbar
17
+ from sympy.physics.quantum.hilbert import L2
18
+ from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator
19
+ from sympy.physics.quantum.state import Ket, Bra, State
20
+
21
+ __all__ = [
22
+ 'XOp',
23
+ 'YOp',
24
+ 'ZOp',
25
+ 'PxOp',
26
+ 'X',
27
+ 'Y',
28
+ 'Z',
29
+ 'Px',
30
+ 'XKet',
31
+ 'XBra',
32
+ 'PxKet',
33
+ 'PxBra',
34
+ 'PositionState3D',
35
+ 'PositionKet3D',
36
+ 'PositionBra3D'
37
+ ]
38
+
39
+ #-------------------------------------------------------------------------
40
+ # Position operators
41
+ #-------------------------------------------------------------------------
42
+
43
+
44
+ class XOp(HermitianOperator):
45
+ """1D cartesian position operator."""
46
+
47
+ @classmethod
48
+ def default_args(self):
49
+ return ("X",)
50
+
51
+ @classmethod
52
+ def _eval_hilbert_space(self, args):
53
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
54
+
55
+ def _eval_commutator_PxOp(self, other):
56
+ return I*hbar
57
+
58
+ def _apply_operator_XKet(self, ket, **options):
59
+ return ket.position*ket
60
+
61
+ def _apply_operator_PositionKet3D(self, ket, **options):
62
+ return ket.position_x*ket
63
+
64
+ def _represent_PxKet(self, basis, *, index=1, **options):
65
+ states = basis._enumerate_state(2, start_index=index)
66
+ coord1 = states[0].momentum
67
+ coord2 = states[1].momentum
68
+ d = DifferentialOperator(coord1)
69
+ delta = DiracDelta(coord1 - coord2)
70
+
71
+ return I*hbar*(d*delta)
72
+
73
+
74
+ class YOp(HermitianOperator):
75
+ """ Y cartesian coordinate operator (for 2D or 3D systems) """
76
+
77
+ @classmethod
78
+ def default_args(self):
79
+ return ("Y",)
80
+
81
+ @classmethod
82
+ def _eval_hilbert_space(self, args):
83
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
84
+
85
+ def _apply_operator_PositionKet3D(self, ket, **options):
86
+ return ket.position_y*ket
87
+
88
+
89
+ class ZOp(HermitianOperator):
90
+ """ Z cartesian coordinate operator (for 3D systems) """
91
+
92
+ @classmethod
93
+ def default_args(self):
94
+ return ("Z",)
95
+
96
+ @classmethod
97
+ def _eval_hilbert_space(self, args):
98
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
99
+
100
+ def _apply_operator_PositionKet3D(self, ket, **options):
101
+ return ket.position_z*ket
102
+
103
+ #-------------------------------------------------------------------------
104
+ # Momentum operators
105
+ #-------------------------------------------------------------------------
106
+
107
+
108
+ class PxOp(HermitianOperator):
109
+ """1D cartesian momentum operator."""
110
+
111
+ @classmethod
112
+ def default_args(self):
113
+ return ("Px",)
114
+
115
+ @classmethod
116
+ def _eval_hilbert_space(self, args):
117
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
118
+
119
+ def _apply_operator_PxKet(self, ket, **options):
120
+ return ket.momentum*ket
121
+
122
+ def _represent_XKet(self, basis, *, index=1, **options):
123
+ states = basis._enumerate_state(2, start_index=index)
124
+ coord1 = states[0].position
125
+ coord2 = states[1].position
126
+ d = DifferentialOperator(coord1)
127
+ delta = DiracDelta(coord1 - coord2)
128
+
129
+ return -I*hbar*(d*delta)
130
+
131
+ X = XOp('X')
132
+ Y = YOp('Y')
133
+ Z = ZOp('Z')
134
+ Px = PxOp('Px')
135
+
136
+ #-------------------------------------------------------------------------
137
+ # Position eigenstates
138
+ #-------------------------------------------------------------------------
139
+
140
+
141
+ class XKet(Ket):
142
+ """1D cartesian position eigenket."""
143
+
144
+ @classmethod
145
+ def _operators_to_state(self, op, **options):
146
+ return self.__new__(self, *_lowercase_labels(op), **options)
147
+
148
+ def _state_to_operators(self, op_class, **options):
149
+ return op_class.__new__(op_class,
150
+ *_uppercase_labels(self), **options)
151
+
152
+ @classmethod
153
+ def default_args(self):
154
+ return ("x",)
155
+
156
+ @classmethod
157
+ def dual_class(self):
158
+ return XBra
159
+
160
+ @property
161
+ def position(self):
162
+ """The position of the state."""
163
+ return self.label[0]
164
+
165
+ def _enumerate_state(self, num_states, **options):
166
+ return _enumerate_continuous_1D(self, num_states, **options)
167
+
168
+ def _eval_innerproduct_XBra(self, bra, **hints):
169
+ return DiracDelta(self.position - bra.position)
170
+
171
+ def _eval_innerproduct_PxBra(self, bra, **hints):
172
+ return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar)
173
+
174
+
175
+ class XBra(Bra):
176
+ """1D cartesian position eigenbra."""
177
+
178
+ @classmethod
179
+ def default_args(self):
180
+ return ("x",)
181
+
182
+ @classmethod
183
+ def dual_class(self):
184
+ return XKet
185
+
186
+ @property
187
+ def position(self):
188
+ """The position of the state."""
189
+ return self.label[0]
190
+
191
+
192
+ class PositionState3D(State):
193
+ """ Base class for 3D cartesian position eigenstates """
194
+
195
+ @classmethod
196
+ def _operators_to_state(self, op, **options):
197
+ return self.__new__(self, *_lowercase_labels(op), **options)
198
+
199
+ def _state_to_operators(self, op_class, **options):
200
+ return op_class.__new__(op_class,
201
+ *_uppercase_labels(self), **options)
202
+
203
+ @classmethod
204
+ def default_args(self):
205
+ return ("x", "y", "z")
206
+
207
+ @property
208
+ def position_x(self):
209
+ """ The x coordinate of the state """
210
+ return self.label[0]
211
+
212
+ @property
213
+ def position_y(self):
214
+ """ The y coordinate of the state """
215
+ return self.label[1]
216
+
217
+ @property
218
+ def position_z(self):
219
+ """ The z coordinate of the state """
220
+ return self.label[2]
221
+
222
+
223
+ class PositionKet3D(Ket, PositionState3D):
224
+ """ 3D cartesian position eigenket """
225
+
226
+ def _eval_innerproduct_PositionBra3D(self, bra, **options):
227
+ x_diff = self.position_x - bra.position_x
228
+ y_diff = self.position_y - bra.position_y
229
+ z_diff = self.position_z - bra.position_z
230
+
231
+ return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff)
232
+
233
+ @classmethod
234
+ def dual_class(self):
235
+ return PositionBra3D
236
+
237
+
238
+ # XXX: The type:ignore here is because mypy gives Definition of
239
+ # "_state_to_operators" in base class "PositionState3D" is incompatible with
240
+ # definition in base class "BraBase"
241
+ class PositionBra3D(Bra, PositionState3D): # type: ignore
242
+ """ 3D cartesian position eigenbra """
243
+
244
+ @classmethod
245
+ def dual_class(self):
246
+ return PositionKet3D
247
+
248
+ #-------------------------------------------------------------------------
249
+ # Momentum eigenstates
250
+ #-------------------------------------------------------------------------
251
+
252
+
253
+ class PxKet(Ket):
254
+ """1D cartesian momentum eigenket."""
255
+
256
+ @classmethod
257
+ def _operators_to_state(self, op, **options):
258
+ return self.__new__(self, *_lowercase_labels(op), **options)
259
+
260
+ def _state_to_operators(self, op_class, **options):
261
+ return op_class.__new__(op_class,
262
+ *_uppercase_labels(self), **options)
263
+
264
+ @classmethod
265
+ def default_args(self):
266
+ return ("px",)
267
+
268
+ @classmethod
269
+ def dual_class(self):
270
+ return PxBra
271
+
272
+ @property
273
+ def momentum(self):
274
+ """The momentum of the state."""
275
+ return self.label[0]
276
+
277
+ def _enumerate_state(self, *args, **options):
278
+ return _enumerate_continuous_1D(self, *args, **options)
279
+
280
+ def _eval_innerproduct_XBra(self, bra, **hints):
281
+ return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar)
282
+
283
+ def _eval_innerproduct_PxBra(self, bra, **hints):
284
+ return DiracDelta(self.momentum - bra.momentum)
285
+
286
+
287
+ class PxBra(Bra):
288
+ """1D cartesian momentum eigenbra."""
289
+
290
+ @classmethod
291
+ def default_args(self):
292
+ return ("px",)
293
+
294
+ @classmethod
295
+ def dual_class(self):
296
+ return PxKet
297
+
298
+ @property
299
+ def momentum(self):
300
+ """The momentum of the state."""
301
+ return self.label[0]
302
+
303
+ #-------------------------------------------------------------------------
304
+ # Global helper functions
305
+ #-------------------------------------------------------------------------
306
+
307
+
308
+ def _enumerate_continuous_1D(*args, **options):
309
+ state = args[0]
310
+ num_states = args[1]
311
+ state_class = state.__class__
312
+ index_list = options.pop('index_list', [])
313
+
314
+ if len(index_list) == 0:
315
+ start_index = options.pop('start_index', 1)
316
+ index_list = list(range(start_index, start_index + num_states))
317
+
318
+ enum_states = [0 for i in range(len(index_list))]
319
+
320
+ for i, ind in enumerate(index_list):
321
+ label = state.args[0]
322
+ enum_states[i] = state_class(str(label) + "_" + str(ind), **options)
323
+
324
+ return enum_states
325
+
326
+
327
+ def _lowercase_labels(ops):
328
+ if not isinstance(ops, set):
329
+ ops = [ops]
330
+
331
+ return [str(arg.label[0]).lower() for arg in ops]
332
+
333
+
334
+ def _uppercase_labels(ops):
335
+ if not isinstance(ops, set):
336
+ ops = [ops]
337
+
338
+ new_args = [str(arg.label[0])[0].upper() +
339
+ str(arg.label[0])[1:] for arg in ops]
340
+
341
+ return new_args
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/cg.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #TODO:
2
+ # -Implement Clebsch-Gordan symmetries
3
+ # -Improve simplification method
4
+ # -Implement new simplifications
5
+ """Clebsch-Gordon Coefficients."""
6
+
7
+ from sympy.concrete.summations import Sum
8
+ from sympy.core.add import Add
9
+ from sympy.core.expr import Expr
10
+ from sympy.core.function import expand
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.power import Pow
13
+ from sympy.core.relational import Eq
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import (Wild, symbols)
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.elementary.miscellaneous import sqrt
18
+ from sympy.functions.elementary.piecewise import Piecewise
19
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
20
+
21
+ from sympy.functions.special.tensor_functions import KroneckerDelta
22
+ from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
23
+ from sympy.printing.precedence import PRECEDENCE
24
+
25
+ __all__ = [
26
+ 'CG',
27
+ 'Wigner3j',
28
+ 'Wigner6j',
29
+ 'Wigner9j',
30
+ 'cg_simp'
31
+ ]
32
+
33
+ #-----------------------------------------------------------------------------
34
+ # CG Coefficients
35
+ #-----------------------------------------------------------------------------
36
+
37
+
38
+ class Wigner3j(Expr):
39
+ """Class for the Wigner-3j symbols.
40
+
41
+ Explanation
42
+ ===========
43
+
44
+ Wigner 3j-symbols are coefficients determined by the coupling of
45
+ two angular momenta. When created, they are expressed as symbolic
46
+ quantities that, for numerical parameters, can be evaluated using the
47
+ ``.doit()`` method [1]_.
48
+
49
+ Parameters
50
+ ==========
51
+
52
+ j1, m1, j2, m2, j3, m3 : Number, Symbol
53
+ Terms determining the angular momentum of coupled angular momentum
54
+ systems.
55
+
56
+ Examples
57
+ ========
58
+
59
+ Declare a Wigner-3j coefficient and calculate its value
60
+
61
+ >>> from sympy.physics.quantum.cg import Wigner3j
62
+ >>> w3j = Wigner3j(6,0,4,0,2,0)
63
+ >>> w3j
64
+ Wigner3j(6, 0, 4, 0, 2, 0)
65
+ >>> w3j.doit()
66
+ sqrt(715)/143
67
+
68
+ See Also
69
+ ========
70
+
71
+ CG: Clebsch-Gordan coefficients
72
+
73
+ References
74
+ ==========
75
+
76
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
77
+ """
78
+
79
+ is_commutative = True
80
+
81
+ def __new__(cls, j1, m1, j2, m2, j3, m3):
82
+ args = map(sympify, (j1, m1, j2, m2, j3, m3))
83
+ return Expr.__new__(cls, *args)
84
+
85
+ @property
86
+ def j1(self):
87
+ return self.args[0]
88
+
89
+ @property
90
+ def m1(self):
91
+ return self.args[1]
92
+
93
+ @property
94
+ def j2(self):
95
+ return self.args[2]
96
+
97
+ @property
98
+ def m2(self):
99
+ return self.args[3]
100
+
101
+ @property
102
+ def j3(self):
103
+ return self.args[4]
104
+
105
+ @property
106
+ def m3(self):
107
+ return self.args[5]
108
+
109
+ @property
110
+ def is_symbolic(self):
111
+ return not all(arg.is_number for arg in self.args)
112
+
113
+ # This is modified from the _print_Matrix method
114
+ def _pretty(self, printer, *args):
115
+ m = ((printer._print(self.j1), printer._print(self.m1)),
116
+ (printer._print(self.j2), printer._print(self.m2)),
117
+ (printer._print(self.j3), printer._print(self.m3)))
118
+ hsep = 2
119
+ vsep = 1
120
+ maxw = [-1]*3
121
+ for j in range(3):
122
+ maxw[j] = max(m[j][i].width() for i in range(2))
123
+ D = None
124
+ for i in range(2):
125
+ D_row = None
126
+ for j in range(3):
127
+ s = m[j][i]
128
+ wdelta = maxw[j] - s.width()
129
+ wleft = wdelta //2
130
+ wright = wdelta - wleft
131
+
132
+ s = prettyForm(*s.right(' '*wright))
133
+ s = prettyForm(*s.left(' '*wleft))
134
+
135
+ if D_row is None:
136
+ D_row = s
137
+ continue
138
+ D_row = prettyForm(*D_row.right(' '*hsep))
139
+ D_row = prettyForm(*D_row.right(s))
140
+ if D is None:
141
+ D = D_row
142
+ continue
143
+ for _ in range(vsep):
144
+ D = prettyForm(*D.below(' '))
145
+ D = prettyForm(*D.below(D_row))
146
+ D = prettyForm(*D.parens())
147
+ return D
148
+
149
+ def _latex(self, printer, *args):
150
+ label = map(printer._print, (self.j1, self.j2, self.j3,
151
+ self.m1, self.m2, self.m3))
152
+ return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
153
+ tuple(label)
154
+
155
+ def doit(self, **hints):
156
+ if self.is_symbolic:
157
+ raise ValueError("Coefficients must be numerical")
158
+ return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
159
+
160
+
161
+ class CG(Wigner3j):
162
+ r"""Class for Clebsch-Gordan coefficient.
163
+
164
+ Explanation
165
+ ===========
166
+
167
+ Clebsch-Gordan coefficients describe the angular momentum coupling between
168
+ two systems. The coefficients give the expansion of a coupled total angular
169
+ momentum state and an uncoupled tensor product state. The Clebsch-Gordan
170
+ coefficients are defined as [1]_:
171
+
172
+ .. math ::
173
+ C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ j1, m1, j2, m2 : Number, Symbol
179
+ Angular momenta of states 1 and 2.
180
+
181
+ j3, m3: Number, Symbol
182
+ Total angular momentum of the coupled system.
183
+
184
+ Examples
185
+ ========
186
+
187
+ Define a Clebsch-Gordan coefficient and evaluate its value
188
+
189
+ >>> from sympy.physics.quantum.cg import CG
190
+ >>> from sympy import S
191
+ >>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
192
+ >>> cg
193
+ CG(3/2, 3/2, 1/2, -1/2, 1, 1)
194
+ >>> cg.doit()
195
+ sqrt(3)/2
196
+ >>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
197
+ sqrt(2)/2
198
+
199
+
200
+ Compare [2]_.
201
+
202
+ See Also
203
+ ========
204
+
205
+ Wigner3j: Wigner-3j symbols
206
+
207
+ References
208
+ ==========
209
+
210
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
211
+ .. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
212
+ <https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
213
+ in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
214
+ 2020, 083C01 (2020).
215
+ """
216
+ precedence = PRECEDENCE["Pow"] - 1
217
+
218
+ def doit(self, **hints):
219
+ if self.is_symbolic:
220
+ raise ValueError("Coefficients must be numerical")
221
+ return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
222
+
223
+ def _pretty(self, printer, *args):
224
+ bot = printer._print_seq(
225
+ (self.j1, self.m1, self.j2, self.m2), delimiter=',')
226
+ top = printer._print_seq((self.j3, self.m3), delimiter=',')
227
+
228
+ pad = max(top.width(), bot.width())
229
+ bot = prettyForm(*bot.left(' '))
230
+ top = prettyForm(*top.left(' '))
231
+
232
+ if not pad == bot.width():
233
+ bot = prettyForm(*bot.right(' '*(pad - bot.width())))
234
+ if not pad == top.width():
235
+ top = prettyForm(*top.right(' '*(pad - top.width())))
236
+ s = stringPict('C' + ' '*pad)
237
+ s = prettyForm(*s.below(bot))
238
+ s = prettyForm(*s.above(top))
239
+ return s
240
+
241
+ def _latex(self, printer, *args):
242
+ label = map(printer._print, (self.j3, self.m3, self.j1,
243
+ self.m1, self.j2, self.m2))
244
+ return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
245
+
246
+
247
+ class Wigner6j(Expr):
248
+ """Class for the Wigner-6j symbols
249
+
250
+ See Also
251
+ ========
252
+
253
+ Wigner3j: Wigner-3j symbols
254
+
255
+ """
256
+ def __new__(cls, j1, j2, j12, j3, j, j23):
257
+ args = map(sympify, (j1, j2, j12, j3, j, j23))
258
+ return Expr.__new__(cls, *args)
259
+
260
+ @property
261
+ def j1(self):
262
+ return self.args[0]
263
+
264
+ @property
265
+ def j2(self):
266
+ return self.args[1]
267
+
268
+ @property
269
+ def j12(self):
270
+ return self.args[2]
271
+
272
+ @property
273
+ def j3(self):
274
+ return self.args[3]
275
+
276
+ @property
277
+ def j(self):
278
+ return self.args[4]
279
+
280
+ @property
281
+ def j23(self):
282
+ return self.args[5]
283
+
284
+ @property
285
+ def is_symbolic(self):
286
+ return not all(arg.is_number for arg in self.args)
287
+
288
+ # This is modified from the _print_Matrix method
289
+ def _pretty(self, printer, *args):
290
+ m = ((printer._print(self.j1), printer._print(self.j3)),
291
+ (printer._print(self.j2), printer._print(self.j)),
292
+ (printer._print(self.j12), printer._print(self.j23)))
293
+ hsep = 2
294
+ vsep = 1
295
+ maxw = [-1]*3
296
+ for j in range(3):
297
+ maxw[j] = max(m[j][i].width() for i in range(2))
298
+ D = None
299
+ for i in range(2):
300
+ D_row = None
301
+ for j in range(3):
302
+ s = m[j][i]
303
+ wdelta = maxw[j] - s.width()
304
+ wleft = wdelta //2
305
+ wright = wdelta - wleft
306
+
307
+ s = prettyForm(*s.right(' '*wright))
308
+ s = prettyForm(*s.left(' '*wleft))
309
+
310
+ if D_row is None:
311
+ D_row = s
312
+ continue
313
+ D_row = prettyForm(*D_row.right(' '*hsep))
314
+ D_row = prettyForm(*D_row.right(s))
315
+ if D is None:
316
+ D = D_row
317
+ continue
318
+ for _ in range(vsep):
319
+ D = prettyForm(*D.below(' '))
320
+ D = prettyForm(*D.below(D_row))
321
+ D = prettyForm(*D.parens(left='{', right='}'))
322
+ return D
323
+
324
+ def _latex(self, printer, *args):
325
+ label = map(printer._print, (self.j1, self.j2, self.j12,
326
+ self.j3, self.j, self.j23))
327
+ return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
328
+ tuple(label)
329
+
330
+ def doit(self, **hints):
331
+ if self.is_symbolic:
332
+ raise ValueError("Coefficients must be numerical")
333
+ return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
334
+
335
+
336
+ class Wigner9j(Expr):
337
+ """Class for the Wigner-9j symbols
338
+
339
+ See Also
340
+ ========
341
+
342
+ Wigner3j: Wigner-3j symbols
343
+
344
+ """
345
+ def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
346
+ args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
347
+ return Expr.__new__(cls, *args)
348
+
349
+ @property
350
+ def j1(self):
351
+ return self.args[0]
352
+
353
+ @property
354
+ def j2(self):
355
+ return self.args[1]
356
+
357
+ @property
358
+ def j12(self):
359
+ return self.args[2]
360
+
361
+ @property
362
+ def j3(self):
363
+ return self.args[3]
364
+
365
+ @property
366
+ def j4(self):
367
+ return self.args[4]
368
+
369
+ @property
370
+ def j34(self):
371
+ return self.args[5]
372
+
373
+ @property
374
+ def j13(self):
375
+ return self.args[6]
376
+
377
+ @property
378
+ def j24(self):
379
+ return self.args[7]
380
+
381
+ @property
382
+ def j(self):
383
+ return self.args[8]
384
+
385
+ @property
386
+ def is_symbolic(self):
387
+ return not all(arg.is_number for arg in self.args)
388
+
389
+ # This is modified from the _print_Matrix method
390
+ def _pretty(self, printer, *args):
391
+ m = (
392
+ (printer._print(
393
+ self.j1), printer._print(self.j3), printer._print(self.j13)),
394
+ (printer._print(
395
+ self.j2), printer._print(self.j4), printer._print(self.j24)),
396
+ (printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
397
+ hsep = 2
398
+ vsep = 1
399
+ maxw = [-1]*3
400
+ for j in range(3):
401
+ maxw[j] = max(m[j][i].width() for i in range(3))
402
+ D = None
403
+ for i in range(3):
404
+ D_row = None
405
+ for j in range(3):
406
+ s = m[j][i]
407
+ wdelta = maxw[j] - s.width()
408
+ wleft = wdelta //2
409
+ wright = wdelta - wleft
410
+
411
+ s = prettyForm(*s.right(' '*wright))
412
+ s = prettyForm(*s.left(' '*wleft))
413
+
414
+ if D_row is None:
415
+ D_row = s
416
+ continue
417
+ D_row = prettyForm(*D_row.right(' '*hsep))
418
+ D_row = prettyForm(*D_row.right(s))
419
+ if D is None:
420
+ D = D_row
421
+ continue
422
+ for _ in range(vsep):
423
+ D = prettyForm(*D.below(' '))
424
+ D = prettyForm(*D.below(D_row))
425
+ D = prettyForm(*D.parens(left='{', right='}'))
426
+ return D
427
+
428
+ def _latex(self, printer, *args):
429
+ label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
430
+ self.j4, self.j34, self.j13, self.j24, self.j))
431
+ return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
432
+ tuple(label)
433
+
434
+ def doit(self, **hints):
435
+ if self.is_symbolic:
436
+ raise ValueError("Coefficients must be numerical")
437
+ return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
438
+
439
+
440
+ def cg_simp(e):
441
+ """Simplify and combine CG coefficients.
442
+
443
+ Explanation
444
+ ===========
445
+
446
+ This function uses various symmetry and properties of sums and
447
+ products of Clebsch-Gordan coefficients to simplify statements
448
+ involving these terms [1]_.
449
+
450
+ Examples
451
+ ========
452
+
453
+ Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
454
+ 2*a+1
455
+
456
+ >>> from sympy.physics.quantum.cg import CG, cg_simp
457
+ >>> a = CG(1,1,0,0,1,1)
458
+ >>> b = CG(1,0,0,0,1,0)
459
+ >>> c = CG(1,-1,0,0,1,-1)
460
+ >>> cg_simp(a+b+c)
461
+ 3
462
+
463
+ See Also
464
+ ========
465
+
466
+ CG: Clebsh-Gordan coefficients
467
+
468
+ References
469
+ ==========
470
+
471
+ .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
472
+ """
473
+ if isinstance(e, Add):
474
+ return _cg_simp_add(e)
475
+ elif isinstance(e, Sum):
476
+ return _cg_simp_sum(e)
477
+ elif isinstance(e, Mul):
478
+ return Mul(*[cg_simp(arg) for arg in e.args])
479
+ elif isinstance(e, Pow):
480
+ return Pow(cg_simp(e.base), e.exp)
481
+ else:
482
+ return e
483
+
484
+
485
+ def _cg_simp_add(e):
486
+ #TODO: Improve simplification method
487
+ """Takes a sum of terms involving Clebsch-Gordan coefficients and
488
+ simplifies the terms.
489
+
490
+ Explanation
491
+ ===========
492
+
493
+ First, we create two lists, cg_part, which is all the terms involving CG
494
+ coefficients, and other_part, which is all other terms. The cg_part list
495
+ is then passed to the simplification methods, which return the new cg_part
496
+ and any additional terms that are added to other_part
497
+ """
498
+ cg_part = []
499
+ other_part = []
500
+
501
+ e = expand(e)
502
+ for arg in e.args:
503
+ if arg.has(CG):
504
+ if isinstance(arg, Sum):
505
+ other_part.append(_cg_simp_sum(arg))
506
+ elif isinstance(arg, Mul):
507
+ terms = 1
508
+ for term in arg.args:
509
+ if isinstance(term, Sum):
510
+ terms *= _cg_simp_sum(term)
511
+ else:
512
+ terms *= term
513
+ if terms.has(CG):
514
+ cg_part.append(terms)
515
+ else:
516
+ other_part.append(terms)
517
+ else:
518
+ cg_part.append(arg)
519
+ else:
520
+ other_part.append(arg)
521
+
522
+ cg_part, other = _check_varsh_871_1(cg_part)
523
+ other_part.append(other)
524
+ cg_part, other = _check_varsh_871_2(cg_part)
525
+ other_part.append(other)
526
+ cg_part, other = _check_varsh_872_9(cg_part)
527
+ other_part.append(other)
528
+ return Add(*cg_part) + Add(*other_part)
529
+
530
+
531
+ def _check_varsh_871_1(term_list):
532
+ # Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
533
+ a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
534
+ expr = lt*CG(a, alpha, b, 0, a, alpha)
535
+ simp = (2*a + 1)*KroneckerDelta(b, 0)
536
+ sign = lt/abs(lt)
537
+ build_expr = 2*a + 1
538
+ index_expr = a + alpha
539
+ return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
540
+
541
+
542
+ def _check_varsh_871_2(term_list):
543
+ # Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
544
+ a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
545
+ expr = lt*CG(a, alpha, a, -alpha, c, 0)
546
+ simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
547
+ sign = (-1)**(a - alpha)*lt/abs(lt)
548
+ build_expr = 2*a + 1
549
+ index_expr = a + alpha
550
+ return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
551
+
552
+
553
+ def _check_varsh_872_9(term_list):
554
+ # Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
555
+ a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
556
+ 'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
557
+ # Case alpha==alphap, beta==betap
558
+
559
+ # For numerical alpha,beta
560
+ expr = lt*CG(a, alpha, b, beta, c, gamma)**2
561
+ simp = S.One
562
+ sign = lt/abs(lt)
563
+ x = abs(a - b)
564
+ y = abs(alpha + beta)
565
+ build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
566
+ index_expr = a + b - c
567
+ term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
568
+
569
+ # For symbolic alpha,beta
570
+ x = abs(a - b)
571
+ y = a + b
572
+ build_expr = (y + 1 - x)*(x + y + 1)
573
+ index_expr = (c - x)*(x + c) + c + gamma
574
+ term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
575
+
576
+ # Case alpha!=alphap or beta!=betap
577
+ # Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
578
+ # For numerical alpha,alphap,beta,betap
579
+ expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
580
+ simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
581
+ sign = S.One
582
+ x = abs(a - b)
583
+ y = abs(alpha + beta)
584
+ build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
585
+ index_expr = a + b - c
586
+ term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
587
+
588
+ # For symbolic alpha,alphap,beta,betap
589
+ x = abs(a - b)
590
+ y = a + b
591
+ build_expr = (y + 1 - x)*(x + y + 1)
592
+ index_expr = (c - x)*(x + c) + c + gamma
593
+ term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
594
+
595
+ return term_list, other1 + other2 + other4
596
+
597
+
598
+ def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
599
+ """ Checks for simplifications that can be made, returning a tuple of the
600
+ simplified list of terms and any terms generated by simplification.
601
+
602
+ Parameters
603
+ ==========
604
+
605
+ expr: expression
606
+ The expression with Wild terms that will be matched to the terms in
607
+ the sum
608
+
609
+ simp: expression
610
+ The expression with Wild terms that is substituted in place of the CG
611
+ terms in the case of simplification
612
+
613
+ sign: expression
614
+ The expression with Wild terms denoting the sign that is on expr that
615
+ must match
616
+
617
+ lt: expression
618
+ The expression with Wild terms that gives the leading term of the
619
+ matched expr
620
+
621
+ term_list: list
622
+ A list of all of the terms is the sum to be simplified
623
+
624
+ variables: list
625
+ A list of all the variables that appears in expr
626
+
627
+ dep_variables: list
628
+ A list of the variables that must match for all the terms in the sum,
629
+ i.e. the dependent variables
630
+
631
+ build_index_expr: expression
632
+ Expression with Wild terms giving the number of elements in cg_index
633
+
634
+ index_expr: expression
635
+ Expression with Wild terms giving the index terms have when storing
636
+ them to cg_index
637
+
638
+ """
639
+ other_part = 0
640
+ i = 0
641
+ while i < len(term_list):
642
+ sub_1 = _check_cg(term_list[i], expr, len(variables))
643
+ if sub_1 is None:
644
+ i += 1
645
+ continue
646
+ if not build_index_expr.subs(sub_1).is_number:
647
+ i += 1
648
+ continue
649
+ sub_dep = [(x, sub_1[x]) for x in dep_variables]
650
+ cg_index = [None]*build_index_expr.subs(sub_1)
651
+ for j in range(i, len(term_list)):
652
+ sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
653
+ if sub_2 is None:
654
+ continue
655
+ if not index_expr.subs(sub_dep).subs(sub_2).is_number:
656
+ continue
657
+ cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
658
+ if not any(i is None for i in cg_index):
659
+ min_lt = min(*[ abs(term[2]) for term in cg_index ])
660
+ indices = [ term[0] for term in cg_index]
661
+ indices.sort()
662
+ indices.reverse()
663
+ [ term_list.pop(j) for j in indices ]
664
+ for term in cg_index:
665
+ if abs(term[2]) > min_lt:
666
+ term_list.append( (term[2] - min_lt*term[3])*term[1] )
667
+ other_part += min_lt*(sign*simp).subs(sub_1)
668
+ else:
669
+ i += 1
670
+ return term_list, other_part
671
+
672
+
673
+ def _check_cg(cg_term, expr, length, sign=None):
674
+ """Checks whether a term matches the given expression"""
675
+ # TODO: Check for symmetries
676
+ matches = cg_term.match(expr)
677
+ if matches is None:
678
+ return
679
+ if sign is not None:
680
+ if not isinstance(sign, tuple):
681
+ raise TypeError('sign must be a tuple')
682
+ if not sign[0] == (sign[1]).subs(matches):
683
+ return
684
+ if len(matches) == length:
685
+ return matches
686
+
687
+
688
+ def _cg_simp_sum(e):
689
+ e = _check_varsh_sum_871_1(e)
690
+ e = _check_varsh_sum_871_2(e)
691
+ e = _check_varsh_sum_872_4(e)
692
+ return e
693
+
694
+
695
+ def _check_varsh_sum_871_1(e):
696
+ a = Wild('a')
697
+ alpha = symbols('alpha')
698
+ b = Wild('b')
699
+ match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
700
+ if match is not None and len(match) == 2:
701
+ return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
702
+ return e
703
+
704
+
705
+ def _check_varsh_sum_871_2(e):
706
+ a = Wild('a')
707
+ alpha = symbols('alpha')
708
+ c = Wild('c')
709
+ match = e.match(
710
+ Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
711
+ if match is not None and len(match) == 2:
712
+ return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
713
+ return e
714
+
715
+
716
+ def _check_varsh_sum_872_4(e):
717
+ alpha = symbols('alpha')
718
+ beta = symbols('beta')
719
+ a = Wild('a')
720
+ b = Wild('b')
721
+ c = Wild('c')
722
+ cp = Wild('cp')
723
+ gamma = Wild('gamma')
724
+ gammap = Wild('gammap')
725
+ cg1 = CG(a, alpha, b, beta, c, gamma)
726
+ cg2 = CG(a, alpha, b, beta, cp, gammap)
727
+ match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
728
+ if match1 is not None and len(match1) == 6:
729
+ return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
730
+ match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
731
+ if match2 is not None and len(match2) == 4:
732
+ return S.One
733
+ return e
734
+
735
+
736
+ def _cg_list(term):
737
+ if isinstance(term, CG):
738
+ return (term,), 1, 1
739
+ cg = []
740
+ coeff = 1
741
+ if not isinstance(term, (Mul, Pow)):
742
+ raise NotImplementedError('term must be CG, Add, Mul or Pow')
743
+ if isinstance(term, Pow) and term.exp.is_number:
744
+ if term.exp.is_number:
745
+ [ cg.append(term.base) for _ in range(term.exp) ]
746
+ else:
747
+ return (term,), 1, 1
748
+ if isinstance(term, Mul):
749
+ for arg in term.args:
750
+ if isinstance(arg, CG):
751
+ cg.append(arg)
752
+ else:
753
+ coeff *= arg
754
+ return cg, coeff, coeff/abs(coeff)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/dagger.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hermitian conjugation."""
2
+
3
+ from sympy.core import Expr, Mul, sympify
4
+ from sympy.functions.elementary.complexes import adjoint
5
+
6
+ __all__ = [
7
+ 'Dagger'
8
+ ]
9
+
10
+
11
+ class Dagger(adjoint):
12
+ """General Hermitian conjugate operation.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ Take the Hermetian conjugate of an argument [1]_. For matrices this
18
+ operation is equivalent to transpose and complex conjugate [2]_.
19
+
20
+ Parameters
21
+ ==========
22
+
23
+ arg : Expr
24
+ The SymPy expression that we want to take the dagger of.
25
+ evaluate : bool
26
+ Whether the resulting expression should be directly evaluated.
27
+
28
+ Examples
29
+ ========
30
+
31
+ Daggering various quantum objects:
32
+
33
+ >>> from sympy.physics.quantum.dagger import Dagger
34
+ >>> from sympy.physics.quantum.state import Ket, Bra
35
+ >>> from sympy.physics.quantum.operator import Operator
36
+ >>> Dagger(Ket('psi'))
37
+ <psi|
38
+ >>> Dagger(Bra('phi'))
39
+ |phi>
40
+ >>> Dagger(Operator('A'))
41
+ Dagger(A)
42
+
43
+ Inner and outer products::
44
+
45
+ >>> from sympy.physics.quantum import InnerProduct, OuterProduct
46
+ >>> Dagger(InnerProduct(Bra('a'), Ket('b')))
47
+ <b|a>
48
+ >>> Dagger(OuterProduct(Ket('a'), Bra('b')))
49
+ |b><a|
50
+
51
+ Powers, sums and products::
52
+
53
+ >>> A = Operator('A')
54
+ >>> B = Operator('B')
55
+ >>> Dagger(A*B)
56
+ Dagger(B)*Dagger(A)
57
+ >>> Dagger(A+B)
58
+ Dagger(A) + Dagger(B)
59
+ >>> Dagger(A**2)
60
+ Dagger(A)**2
61
+
62
+ Dagger also seamlessly handles complex numbers and matrices::
63
+
64
+ >>> from sympy import Matrix, I
65
+ >>> m = Matrix([[1,I],[2,I]])
66
+ >>> m
67
+ Matrix([
68
+ [1, I],
69
+ [2, I]])
70
+ >>> Dagger(m)
71
+ Matrix([
72
+ [ 1, 2],
73
+ [-I, -I]])
74
+
75
+ References
76
+ ==========
77
+
78
+ .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint
79
+ .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose
80
+ """
81
+
82
+ def __new__(cls, arg, evaluate=True):
83
+ if hasattr(arg, 'adjoint') and evaluate:
84
+ return arg.adjoint()
85
+ elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose') and evaluate:
86
+ return arg.conjugate().transpose()
87
+ return Expr.__new__(cls, sympify(arg))
88
+
89
+ def __mul__(self, other):
90
+ from sympy.physics.quantum import IdentityOperator
91
+ if isinstance(other, IdentityOperator):
92
+ return self
93
+
94
+ return Mul(self, other)
95
+
96
+ adjoint.__name__ = "Dagger"
97
+ adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
evalkit_tf437/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()
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/fermion.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fermionic quantum operators."""
2
+
3
+ from sympy.core.numbers import Integer
4
+ from sympy.core.singleton import S
5
+ from sympy.physics.quantum import Operator
6
+ from sympy.physics.quantum import HilbertSpace, Ket, Bra
7
+ from sympy.functions.special.tensor_functions import KroneckerDelta
8
+
9
+
10
+ __all__ = [
11
+ 'FermionOp',
12
+ 'FermionFockKet',
13
+ 'FermionFockBra'
14
+ ]
15
+
16
+
17
+ class FermionOp(Operator):
18
+ """A fermionic operator that satisfies {c, Dagger(c)} == 1.
19
+
20
+ Parameters
21
+ ==========
22
+
23
+ name : str
24
+ A string that labels the fermionic mode.
25
+
26
+ annihilation : bool
27
+ A bool that indicates if the fermionic operator is an annihilation
28
+ (True, default value) or creation operator (False)
29
+
30
+ Examples
31
+ ========
32
+
33
+ >>> from sympy.physics.quantum import Dagger, AntiCommutator
34
+ >>> from sympy.physics.quantum.fermion import FermionOp
35
+ >>> c = FermionOp("c")
36
+ >>> AntiCommutator(c, Dagger(c)).doit()
37
+ 1
38
+ """
39
+ @property
40
+ def name(self):
41
+ return self.args[0]
42
+
43
+ @property
44
+ def is_annihilation(self):
45
+ return bool(self.args[1])
46
+
47
+ @classmethod
48
+ def default_args(self):
49
+ return ("c", True)
50
+
51
+ def __new__(cls, *args, **hints):
52
+ if not len(args) in [1, 2]:
53
+ raise ValueError('1 or 2 parameters expected, got %s' % args)
54
+
55
+ if len(args) == 1:
56
+ args = (args[0], S.One)
57
+
58
+ if len(args) == 2:
59
+ args = (args[0], Integer(args[1]))
60
+
61
+ return Operator.__new__(cls, *args)
62
+
63
+ def _eval_commutator_FermionOp(self, other, **hints):
64
+ if 'independent' in hints and hints['independent']:
65
+ # [c, d] = 0
66
+ return S.Zero
67
+
68
+ return None
69
+
70
+ def _eval_anticommutator_FermionOp(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.One
75
+
76
+ elif 'independent' in hints and hints['independent']:
77
+ # {c, d} = 2 * c * d, because [c, d] = 0 for independent operators
78
+ return 2 * self * other
79
+
80
+ return None
81
+
82
+ def _eval_anticommutator_BosonOp(self, other, **hints):
83
+ # because fermions and bosons commute
84
+ return 2 * self * other
85
+
86
+ def _eval_commutator_BosonOp(self, other, **hints):
87
+ return S.Zero
88
+
89
+ def _eval_adjoint(self):
90
+ return FermionOp(str(self.name), not self.is_annihilation)
91
+
92
+ def _print_contents_latex(self, printer, *args):
93
+ if self.is_annihilation:
94
+ return r'{%s}' % str(self.name)
95
+ else:
96
+ return r'{{%s}^\dagger}' % str(self.name)
97
+
98
+ def _print_contents(self, printer, *args):
99
+ if self.is_annihilation:
100
+ return r'%s' % str(self.name)
101
+ else:
102
+ return r'Dagger(%s)' % str(self.name)
103
+
104
+ def _print_contents_pretty(self, printer, *args):
105
+ from sympy.printing.pretty.stringpict import prettyForm
106
+ pform = printer._print(self.args[0], *args)
107
+ if self.is_annihilation:
108
+ return pform
109
+ else:
110
+ return pform**prettyForm('\N{DAGGER}')
111
+
112
+ def _eval_power(self, exp):
113
+ from sympy.core.singleton import S
114
+ if exp == 0:
115
+ return S.One
116
+ elif exp == 1:
117
+ return self
118
+ elif (exp > 1) == True and exp.is_integer == True:
119
+ return S.Zero
120
+ elif (exp < 0) == True or exp.is_integer == False:
121
+ raise ValueError("Fermionic operators can only be raised to a"
122
+ " positive integer power")
123
+ return Operator._eval_power(self, exp)
124
+
125
+ class FermionFockKet(Ket):
126
+ """Fock state ket for a fermionic mode.
127
+
128
+ Parameters
129
+ ==========
130
+
131
+ n : Number
132
+ The Fock state number.
133
+
134
+ """
135
+
136
+ def __new__(cls, n):
137
+ if n not in (0, 1):
138
+ raise ValueError("n must be 0 or 1")
139
+ return Ket.__new__(cls, n)
140
+
141
+ @property
142
+ def n(self):
143
+ return self.label[0]
144
+
145
+ @classmethod
146
+ def dual_class(self):
147
+ return FermionFockBra
148
+
149
+ @classmethod
150
+ def _eval_hilbert_space(cls, label):
151
+ return HilbertSpace()
152
+
153
+ def _eval_innerproduct_FermionFockBra(self, bra, **hints):
154
+ return KroneckerDelta(self.n, bra.n)
155
+
156
+ def _apply_from_right_to_FermionOp(self, op, **options):
157
+ if op.is_annihilation:
158
+ if self.n == 1:
159
+ return FermionFockKet(0)
160
+ else:
161
+ return S.Zero
162
+ else:
163
+ if self.n == 0:
164
+ return FermionFockKet(1)
165
+ else:
166
+ return S.Zero
167
+
168
+
169
+ class FermionFockBra(Bra):
170
+ """Fock state bra for a fermionic mode.
171
+
172
+ Parameters
173
+ ==========
174
+
175
+ n : Number
176
+ The Fock state number.
177
+
178
+ """
179
+
180
+ def __new__(cls, n):
181
+ if n not in (0, 1):
182
+ raise ValueError("n must be 0 or 1")
183
+ return Bra.__new__(cls, n)
184
+
185
+ @property
186
+ def n(self):
187
+ return self.label[0]
188
+
189
+ @classmethod
190
+ def dual_class(self):
191
+ return FermionFockKet
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/innerproduct.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Symbolic inner product."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.functions.elementary.complexes import conjugate
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ from sympy.physics.quantum.dagger import Dagger
7
+ from sympy.physics.quantum.state import KetBase, BraBase
8
+
9
+ __all__ = [
10
+ 'InnerProduct'
11
+ ]
12
+
13
+
14
+ # InnerProduct is not an QExpr because it is really just a regular commutative
15
+ # number. We have gone back and forth about this, but we gain a lot by having
16
+ # it subclass Expr. The main challenges were getting Dagger to work
17
+ # (we use _eval_conjugate) and represent (we can use atoms and subs). Having
18
+ # it be an Expr, mean that there are no commutative QExpr subclasses,
19
+ # which simplifies the design of everything.
20
+
21
+ class InnerProduct(Expr):
22
+ """An unevaluated inner product between a Bra and a Ket [1].
23
+
24
+ Parameters
25
+ ==========
26
+
27
+ bra : BraBase or subclass
28
+ The bra on the left side of the inner product.
29
+ ket : KetBase or subclass
30
+ The ket on the right side of the inner product.
31
+
32
+ Examples
33
+ ========
34
+
35
+ Create an InnerProduct and check its properties:
36
+
37
+ >>> from sympy.physics.quantum import Bra, Ket
38
+ >>> b = Bra('b')
39
+ >>> k = Ket('k')
40
+ >>> ip = b*k
41
+ >>> ip
42
+ <b|k>
43
+ >>> ip.bra
44
+ <b|
45
+ >>> ip.ket
46
+ |k>
47
+
48
+ In simple products of kets and bras inner products will be automatically
49
+ identified and created::
50
+
51
+ >>> b*k
52
+ <b|k>
53
+
54
+ But in more complex expressions, there is ambiguity in whether inner or
55
+ outer products should be created::
56
+
57
+ >>> k*b*k*b
58
+ |k><b|*|k>*<b|
59
+
60
+ A user can force the creation of a inner products in a complex expression
61
+ by using parentheses to group the bra and ket::
62
+
63
+ >>> k*(b*k)*b
64
+ <b|k>*|k>*<b|
65
+
66
+ Notice how the inner product <b|k> moved to the left of the expression
67
+ because inner products are commutative complex numbers.
68
+
69
+ References
70
+ ==========
71
+
72
+ .. [1] https://en.wikipedia.org/wiki/Inner_product
73
+ """
74
+ is_complex = True
75
+
76
+ def __new__(cls, bra, ket):
77
+ if not isinstance(ket, KetBase):
78
+ raise TypeError('KetBase subclass expected, got: %r' % ket)
79
+ if not isinstance(bra, BraBase):
80
+ raise TypeError('BraBase subclass expected, got: %r' % ket)
81
+ obj = Expr.__new__(cls, bra, ket)
82
+ return obj
83
+
84
+ @property
85
+ def bra(self):
86
+ return self.args[0]
87
+
88
+ @property
89
+ def ket(self):
90
+ return self.args[1]
91
+
92
+ def _eval_conjugate(self):
93
+ return InnerProduct(Dagger(self.ket), Dagger(self.bra))
94
+
95
+ def _sympyrepr(self, printer, *args):
96
+ return '%s(%s,%s)' % (self.__class__.__name__,
97
+ printer._print(self.bra, *args), printer._print(self.ket, *args))
98
+
99
+ def _sympystr(self, printer, *args):
100
+ sbra = printer._print(self.bra)
101
+ sket = printer._print(self.ket)
102
+ return '%s|%s' % (sbra[:-1], sket[1:])
103
+
104
+ def _pretty(self, printer, *args):
105
+ # Print state contents
106
+ bra = self.bra._print_contents_pretty(printer, *args)
107
+ ket = self.ket._print_contents_pretty(printer, *args)
108
+ # Print brackets
109
+ height = max(bra.height(), ket.height())
110
+ use_unicode = printer._use_unicode
111
+ lbracket, _ = self.bra._pretty_brackets(height, use_unicode)
112
+ cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode)
113
+ # Build innerproduct
114
+ pform = prettyForm(*bra.left(lbracket))
115
+ pform = prettyForm(*pform.right(cbracket))
116
+ pform = prettyForm(*pform.right(ket))
117
+ pform = prettyForm(*pform.right(rbracket))
118
+ return pform
119
+
120
+ def _latex(self, printer, *args):
121
+ bra_label = self.bra._print_contents_latex(printer, *args)
122
+ ket = printer._print(self.ket, *args)
123
+ return r'\left\langle %s \right. %s' % (bra_label, ket)
124
+
125
+ def doit(self, **hints):
126
+ try:
127
+ r = self.ket._eval_innerproduct(self.bra, **hints)
128
+ except NotImplementedError:
129
+ try:
130
+ r = conjugate(
131
+ self.bra.dual._eval_innerproduct(self.ket.dual, **hints)
132
+ )
133
+ except NotImplementedError:
134
+ r = None
135
+ if r is not None:
136
+ return r
137
+ return self
evalkit_tf437/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
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/operatorset.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ A module for mapping operators to their corresponding eigenstates
2
+ and vice versa
3
+
4
+ It contains a global dictionary with eigenstate-operator pairings.
5
+ If a new state-operator pair is created, this dictionary should be
6
+ updated as well.
7
+
8
+ It also contains functions operators_to_state and state_to_operators
9
+ for mapping between the two. These can handle both classes and
10
+ instances of operators and states. See the individual function
11
+ descriptions for details.
12
+
13
+ TODO List:
14
+ - Update the dictionary with a complete list of state-operator pairs
15
+ """
16
+
17
+ from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet,
18
+ PositionKet3D)
19
+ from sympy.physics.quantum.operator import Operator
20
+ from sympy.physics.quantum.state import StateBase, BraBase, Ket
21
+ from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet,
22
+ JzKet)
23
+
24
+ __all__ = [
25
+ 'operators_to_state',
26
+ 'state_to_operators'
27
+ ]
28
+
29
+ #state_mapping stores the mappings between states and their associated
30
+ #operators or tuples of operators. This should be updated when new
31
+ #classes are written! Entries are of the form PxKet : PxOp or
32
+ #something like 3DKet : (ROp, ThetaOp, PhiOp)
33
+
34
+ #frozenset is used so that the reverse mapping can be made
35
+ #(regular sets are not hashable because they are mutable
36
+ state_mapping = { JxKet: frozenset((J2Op, JxOp)),
37
+ JyKet: frozenset((J2Op, JyOp)),
38
+ JzKet: frozenset((J2Op, JzOp)),
39
+ Ket: Operator,
40
+ PositionKet3D: frozenset((XOp, YOp, ZOp)),
41
+ PxKet: PxOp,
42
+ XKet: XOp }
43
+
44
+ op_mapping = {v: k for k, v in state_mapping.items()}
45
+
46
+
47
+ def operators_to_state(operators, **options):
48
+ """ Returns the eigenstate of the given operator or set of operators
49
+
50
+ A global function for mapping operator classes to their associated
51
+ states. It takes either an Operator or a set of operators and
52
+ returns the state associated with these.
53
+
54
+ This function can handle both instances of a given operator or
55
+ just the class itself (i.e. both XOp() and XOp)
56
+
57
+ There are multiple use cases to consider:
58
+
59
+ 1) A class or set of classes is passed: First, we try to
60
+ instantiate default instances for these operators. If this fails,
61
+ then the class is simply returned. If we succeed in instantiating
62
+ default instances, then we try to call state._operators_to_state
63
+ on the operator instances. If this fails, the class is returned.
64
+ Otherwise, the instance returned by _operators_to_state is returned.
65
+
66
+ 2) An instance or set of instances is passed: In this case,
67
+ state._operators_to_state is called on the instances passed. If
68
+ this fails, a state class is returned. If the method returns an
69
+ instance, that instance is returned.
70
+
71
+ In both cases, if the operator class or set does not exist in the
72
+ state_mapping dictionary, None is returned.
73
+
74
+ Parameters
75
+ ==========
76
+
77
+ arg: Operator or set
78
+ The class or instance of the operator or set of operators
79
+ to be mapped to a state
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.physics.quantum.cartesian import XOp, PxOp
85
+ >>> from sympy.physics.quantum.operatorset import operators_to_state
86
+ >>> from sympy.physics.quantum.operator import Operator
87
+ >>> operators_to_state(XOp)
88
+ |x>
89
+ >>> operators_to_state(XOp())
90
+ |x>
91
+ >>> operators_to_state(PxOp)
92
+ |px>
93
+ >>> operators_to_state(PxOp())
94
+ |px>
95
+ >>> operators_to_state(Operator)
96
+ |psi>
97
+ >>> operators_to_state(Operator())
98
+ |psi>
99
+ """
100
+
101
+ if not (isinstance(operators, (Operator, set)) or issubclass(operators, Operator)):
102
+ raise NotImplementedError("Argument is not an Operator or a set!")
103
+
104
+ if isinstance(operators, set):
105
+ for s in operators:
106
+ if not (isinstance(s, Operator)
107
+ or issubclass(s, Operator)):
108
+ raise NotImplementedError("Set is not all Operators!")
109
+
110
+ ops = frozenset(operators)
111
+
112
+ if ops in op_mapping: # ops is a list of classes in this case
113
+ #Try to get an object from default instances of the
114
+ #operators...if this fails, return the class
115
+ try:
116
+ op_instances = [op() for op in ops]
117
+ ret = _get_state(op_mapping[ops], set(op_instances), **options)
118
+ except NotImplementedError:
119
+ ret = op_mapping[ops]
120
+
121
+ return ret
122
+ else:
123
+ tmp = [type(o) for o in ops]
124
+ classes = frozenset(tmp)
125
+
126
+ if classes in op_mapping:
127
+ ret = _get_state(op_mapping[classes], ops, **options)
128
+ else:
129
+ ret = None
130
+
131
+ return ret
132
+ else:
133
+ if operators in op_mapping:
134
+ try:
135
+ op_instance = operators()
136
+ ret = _get_state(op_mapping[operators], op_instance, **options)
137
+ except NotImplementedError:
138
+ ret = op_mapping[operators]
139
+
140
+ return ret
141
+ elif type(operators) in op_mapping:
142
+ return _get_state(op_mapping[type(operators)], operators, **options)
143
+ else:
144
+ return None
145
+
146
+
147
+ def state_to_operators(state, **options):
148
+ """ Returns the operator or set of operators corresponding to the
149
+ given eigenstate
150
+
151
+ A global function for mapping state classes to their associated
152
+ operators or sets of operators. It takes either a state class
153
+ or instance.
154
+
155
+ This function can handle both instances of a given state or just
156
+ the class itself (i.e. both XKet() and XKet)
157
+
158
+ There are multiple use cases to consider:
159
+
160
+ 1) A state class is passed: In this case, we first try
161
+ instantiating a default instance of the class. If this succeeds,
162
+ then we try to call state._state_to_operators on that instance.
163
+ If the creation of the default instance or if the calling of
164
+ _state_to_operators fails, then either an operator class or set of
165
+ operator classes is returned. Otherwise, the appropriate
166
+ operator instances are returned.
167
+
168
+ 2) A state instance is returned: Here, state._state_to_operators
169
+ is called for the instance. If this fails, then a class or set of
170
+ operator classes is returned. Otherwise, the instances are returned.
171
+
172
+ In either case, if the state's class does not exist in
173
+ state_mapping, None is returned.
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ arg: StateBase class or instance (or subclasses)
179
+ The class or instance of the state to be mapped to an
180
+ operator or set of operators
181
+
182
+ Examples
183
+ ========
184
+
185
+ >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra
186
+ >>> from sympy.physics.quantum.operatorset import state_to_operators
187
+ >>> from sympy.physics.quantum.state import Ket, Bra
188
+ >>> state_to_operators(XKet)
189
+ X
190
+ >>> state_to_operators(XKet())
191
+ X
192
+ >>> state_to_operators(PxKet)
193
+ Px
194
+ >>> state_to_operators(PxKet())
195
+ Px
196
+ >>> state_to_operators(PxBra)
197
+ Px
198
+ >>> state_to_operators(XBra)
199
+ X
200
+ >>> state_to_operators(Ket)
201
+ O
202
+ >>> state_to_operators(Bra)
203
+ O
204
+ """
205
+
206
+ if not (isinstance(state, StateBase) or issubclass(state, StateBase)):
207
+ raise NotImplementedError("Argument is not a state!")
208
+
209
+ if state in state_mapping: # state is a class
210
+ state_inst = _make_default(state)
211
+ try:
212
+ ret = _get_ops(state_inst,
213
+ _make_set(state_mapping[state]), **options)
214
+ except (NotImplementedError, TypeError):
215
+ ret = state_mapping[state]
216
+ elif type(state) in state_mapping:
217
+ ret = _get_ops(state,
218
+ _make_set(state_mapping[type(state)]), **options)
219
+ elif isinstance(state, BraBase) and state.dual_class() in state_mapping:
220
+ ret = _get_ops(state,
221
+ _make_set(state_mapping[state.dual_class()]))
222
+ elif issubclass(state, BraBase) and state.dual_class() in state_mapping:
223
+ state_inst = _make_default(state)
224
+ try:
225
+ ret = _get_ops(state_inst,
226
+ _make_set(state_mapping[state.dual_class()]))
227
+ except (NotImplementedError, TypeError):
228
+ ret = state_mapping[state.dual_class()]
229
+ else:
230
+ ret = None
231
+
232
+ return _make_set(ret)
233
+
234
+
235
+ def _make_default(expr):
236
+ # XXX: Catching TypeError like this is a bad way of distinguishing between
237
+ # classes and instances. The logic using this function should be rewritten
238
+ # somehow.
239
+ try:
240
+ ret = expr()
241
+ except TypeError:
242
+ ret = expr
243
+
244
+ return ret
245
+
246
+
247
+ def _get_state(state_class, ops, **options):
248
+ # Try to get a state instance from the operator INSTANCES.
249
+ # If this fails, get the class
250
+ try:
251
+ ret = state_class._operators_to_state(ops, **options)
252
+ except NotImplementedError:
253
+ ret = _make_default(state_class)
254
+
255
+ return ret
256
+
257
+
258
+ def _get_ops(state_inst, op_classes, **options):
259
+ # Try to get operator instances from the state INSTANCE.
260
+ # If this fails, just return the classes
261
+ try:
262
+ ret = state_inst._state_to_operators(op_classes, **options)
263
+ except NotImplementedError:
264
+ if isinstance(op_classes, (set, tuple, frozenset)):
265
+ ret = tuple(_make_default(x) for x in op_classes)
266
+ else:
267
+ ret = _make_default(op_classes)
268
+
269
+ if isinstance(ret, set) and len(ret) == 1:
270
+ return ret[0]
271
+
272
+ return ret
273
+
274
+
275
+ def _make_set(ops):
276
+ if isinstance(ops, (tuple, list, frozenset)):
277
+ return set(ops)
278
+ else:
279
+ return ops
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/qft.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An implementation of qubits and gates acting on them.
2
+
3
+ Todo:
4
+
5
+ * Update docstrings.
6
+ * Update tests.
7
+ * Implement apply using decompose.
8
+ * Implement represent using decompose or something smarter. For this to
9
+ work we first have to implement represent for SWAP.
10
+ * Decide if we want upper index to be inclusive in the constructor.
11
+ * Fix the printing of Rk gates in plotting.
12
+ """
13
+
14
+ from sympy.core.expr import Expr
15
+ from sympy.core.numbers import (I, Integer, pi)
16
+ from sympy.core.symbol import Symbol
17
+ from sympy.functions.elementary.exponential import exp
18
+ from sympy.matrices.dense import Matrix
19
+ from sympy.functions import sqrt
20
+
21
+ from sympy.physics.quantum.qapply import qapply
22
+ from sympy.physics.quantum.qexpr import QuantumError, QExpr
23
+ from sympy.matrices import eye
24
+ from sympy.physics.quantum.tensorproduct import matrix_tensor_product
25
+
26
+ from sympy.physics.quantum.gate import (
27
+ Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate
28
+ )
29
+
30
+ from sympy.functions.elementary.complexes import sign
31
+
32
+ __all__ = [
33
+ 'QFT',
34
+ 'IQFT',
35
+ 'RkGate',
36
+ 'Rk'
37
+ ]
38
+
39
+ #-----------------------------------------------------------------------------
40
+ # Fourier stuff
41
+ #-----------------------------------------------------------------------------
42
+
43
+
44
+ class RkGate(OneQubitGate):
45
+ """This is the R_k gate of the QTF."""
46
+ gate_name = 'Rk'
47
+ gate_name_latex = 'R'
48
+
49
+ def __new__(cls, *args):
50
+ if len(args) != 2:
51
+ raise QuantumError(
52
+ 'Rk gates only take two arguments, got: %r' % args
53
+ )
54
+ # For small k, Rk gates simplify to other gates, using these
55
+ # substitutions give us familiar results for the QFT for small numbers
56
+ # of qubits.
57
+ target = args[0]
58
+ k = args[1]
59
+ if k == 1:
60
+ return ZGate(target)
61
+ elif k == 2:
62
+ return PhaseGate(target)
63
+ elif k == 3:
64
+ return TGate(target)
65
+ args = cls._eval_args(args)
66
+ inst = Expr.__new__(cls, *args)
67
+ inst.hilbert_space = cls._eval_hilbert_space(args)
68
+ return inst
69
+
70
+ @classmethod
71
+ def _eval_args(cls, args):
72
+ # Fall back to this, because Gate._eval_args assumes that args is
73
+ # all targets and can't contain duplicates.
74
+ return QExpr._eval_args(args)
75
+
76
+ @property
77
+ def k(self):
78
+ return self.label[1]
79
+
80
+ @property
81
+ def targets(self):
82
+ return self.label[:1]
83
+
84
+ @property
85
+ def gate_name_plot(self):
86
+ return r'$%s_%s$' % (self.gate_name_latex, str(self.k))
87
+
88
+ def get_target_matrix(self, format='sympy'):
89
+ if format == 'sympy':
90
+ return Matrix([[1, 0], [0, exp(sign(self.k)*Integer(2)*pi*I/(Integer(2)**abs(self.k)))]])
91
+ raise NotImplementedError(
92
+ 'Invalid format for the R_k gate: %r' % format)
93
+
94
+
95
+ Rk = RkGate
96
+
97
+
98
+ class Fourier(Gate):
99
+ """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
100
+
101
+ @classmethod
102
+ def _eval_args(self, args):
103
+ if len(args) != 2:
104
+ raise QuantumError(
105
+ 'QFT/IQFT only takes two arguments, got: %r' % args
106
+ )
107
+ if args[0] >= args[1]:
108
+ raise QuantumError("Start must be smaller than finish")
109
+ return Gate._eval_args(args)
110
+
111
+ def _represent_default_basis(self, **options):
112
+ return self._represent_ZGate(None, **options)
113
+
114
+ def _represent_ZGate(self, basis, **options):
115
+ """
116
+ Represents the (I)QFT In the Z Basis
117
+ """
118
+ nqubits = options.get('nqubits', 0)
119
+ if nqubits == 0:
120
+ raise QuantumError(
121
+ 'The number of qubits must be given as nqubits.')
122
+ if nqubits < self.min_qubits:
123
+ raise QuantumError(
124
+ 'The number of qubits %r is too small for the gate.' % nqubits
125
+ )
126
+ size = self.size
127
+ omega = self.omega
128
+
129
+ #Make a matrix that has the basic Fourier Transform Matrix
130
+ arrayFT = [[omega**(
131
+ i*j % size)/sqrt(size) for i in range(size)] for j in range(size)]
132
+ matrixFT = Matrix(arrayFT)
133
+
134
+ #Embed the FT Matrix in a higher space, if necessary
135
+ if self.label[0] != 0:
136
+ matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT)
137
+ if self.min_qubits < nqubits:
138
+ matrixFT = matrix_tensor_product(
139
+ matrixFT, eye(2**(nqubits - self.min_qubits)))
140
+
141
+ return matrixFT
142
+
143
+ @property
144
+ def targets(self):
145
+ return range(self.label[0], self.label[1])
146
+
147
+ @property
148
+ def min_qubits(self):
149
+ return self.label[1]
150
+
151
+ @property
152
+ def size(self):
153
+ """Size is the size of the QFT matrix"""
154
+ return 2**(self.label[1] - self.label[0])
155
+
156
+ @property
157
+ def omega(self):
158
+ return Symbol('omega')
159
+
160
+
161
+ class QFT(Fourier):
162
+ """The forward quantum Fourier transform."""
163
+
164
+ gate_name = 'QFT'
165
+ gate_name_latex = 'QFT'
166
+
167
+ def decompose(self):
168
+ """Decomposes QFT into elementary gates."""
169
+ start = self.label[0]
170
+ finish = self.label[1]
171
+ circuit = 1
172
+ for level in reversed(range(start, finish)):
173
+ circuit = HadamardGate(level)*circuit
174
+ for i in range(level - start):
175
+ circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit
176
+ for i in range((finish - start)//2):
177
+ circuit = SwapGate(i + start, finish - i - 1)*circuit
178
+ return circuit
179
+
180
+ def _apply_operator_Qubit(self, qubits, **options):
181
+ return qapply(self.decompose()*qubits)
182
+
183
+ def _eval_inverse(self):
184
+ return IQFT(*self.args)
185
+
186
+ @property
187
+ def omega(self):
188
+ return exp(2*pi*I/self.size)
189
+
190
+
191
+ class IQFT(Fourier):
192
+ """The inverse quantum Fourier transform."""
193
+
194
+ gate_name = 'IQFT'
195
+ gate_name_latex = '{QFT^{-1}}'
196
+
197
+ def decompose(self):
198
+ """Decomposes IQFT into elementary gates."""
199
+ start = self.args[0]
200
+ finish = self.args[1]
201
+ circuit = 1
202
+ for i in range((finish - start)//2):
203
+ circuit = SwapGate(i + start, finish - i - 1)*circuit
204
+ for level in range(start, finish):
205
+ for i in reversed(range(level - start)):
206
+ circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit
207
+ circuit = HadamardGate(level)*circuit
208
+ return circuit
209
+
210
+ def _eval_inverse(self):
211
+ return QFT(*self.args)
212
+
213
+ @property
214
+ def omega(self):
215
+ return exp(-2*pi*I/self.size)
evalkit_tf437/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
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/state.py ADDED
@@ -0,0 +1,1017 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dirac notation for states."""
2
+
3
+ from sympy.core.cache import cacheit
4
+ from sympy.core.containers import Tuple
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.function import Function
7
+ from sympy.core.numbers import oo, equal_valued
8
+ from sympy.core.singleton import S
9
+ from sympy.functions.elementary.complexes import conjugate
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.integrals.integrals import integrate
12
+ from sympy.printing.pretty.stringpict import stringPict
13
+ from sympy.physics.quantum.qexpr import QExpr, dispatch_method
14
+
15
+ __all__ = [
16
+ 'KetBase',
17
+ 'BraBase',
18
+ 'StateBase',
19
+ 'State',
20
+ 'Ket',
21
+ 'Bra',
22
+ 'TimeDepState',
23
+ 'TimeDepBra',
24
+ 'TimeDepKet',
25
+ 'OrthogonalKet',
26
+ 'OrthogonalBra',
27
+ 'OrthogonalState',
28
+ 'Wavefunction'
29
+ ]
30
+
31
+
32
+ #-----------------------------------------------------------------------------
33
+ # States, bras and kets.
34
+ #-----------------------------------------------------------------------------
35
+
36
+ # ASCII brackets
37
+ _lbracket = "<"
38
+ _rbracket = ">"
39
+ _straight_bracket = "|"
40
+
41
+
42
+ # Unicode brackets
43
+ # MATHEMATICAL ANGLE BRACKETS
44
+ _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
45
+ _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
46
+ # LIGHT VERTICAL BAR
47
+ _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
48
+
49
+ # Other options for unicode printing of <, > and | for Dirac notation.
50
+
51
+ # LEFT-POINTING ANGLE BRACKET
52
+ # _lbracket = "\u2329"
53
+ # _rbracket = "\u232A"
54
+
55
+ # LEFT ANGLE BRACKET
56
+ # _lbracket = "\u3008"
57
+ # _rbracket = "\u3009"
58
+
59
+ # VERTICAL LINE
60
+ # _straight_bracket = "\u007C"
61
+
62
+
63
+ class StateBase(QExpr):
64
+ """Abstract base class for general abstract states in quantum mechanics.
65
+
66
+ All other state classes defined will need to inherit from this class. It
67
+ carries the basic structure for all other states such as dual, _eval_adjoint
68
+ and label.
69
+
70
+ This is an abstract base class and you should not instantiate it directly,
71
+ instead use State.
72
+ """
73
+
74
+ @classmethod
75
+ def _operators_to_state(self, ops, **options):
76
+ """ Returns the eigenstate instance for the passed operators.
77
+
78
+ This method should be overridden in subclasses. It will handle being
79
+ passed either an Operator instance or set of Operator instances. It
80
+ should return the corresponding state INSTANCE or simply raise a
81
+ NotImplementedError. See cartesian.py for an example.
82
+ """
83
+
84
+ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
85
+
86
+ def _state_to_operators(self, op_classes, **options):
87
+ """ Returns the operators which this state instance is an eigenstate
88
+ of.
89
+
90
+ This method should be overridden in subclasses. It will be called on
91
+ state instances and be passed the operator classes that we wish to make
92
+ into instances. The state instance will then transform the classes
93
+ appropriately, or raise a NotImplementedError if it cannot return
94
+ operator instances. See cartesian.py for examples,
95
+ """
96
+
97
+ raise NotImplementedError(
98
+ "Cannot map this state to operators. Method not implemented!")
99
+
100
+ @property
101
+ def operators(self):
102
+ """Return the operator(s) that this state is an eigenstate of"""
103
+ from .operatorset import state_to_operators # import internally to avoid circular import errors
104
+ return state_to_operators(self)
105
+
106
+ def _enumerate_state(self, num_states, **options):
107
+ raise NotImplementedError("Cannot enumerate this state!")
108
+
109
+ def _represent_default_basis(self, **options):
110
+ return self._represent(basis=self.operators)
111
+
112
+ def _apply_operator(self, op, **options):
113
+ return None
114
+
115
+ #-------------------------------------------------------------------------
116
+ # Dagger/dual
117
+ #-------------------------------------------------------------------------
118
+
119
+ @property
120
+ def dual(self):
121
+ """Return the dual state of this one."""
122
+ return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
123
+
124
+ @classmethod
125
+ def dual_class(self):
126
+ """Return the class used to construct the dual."""
127
+ raise NotImplementedError(
128
+ 'dual_class must be implemented in a subclass'
129
+ )
130
+
131
+ def _eval_adjoint(self):
132
+ """Compute the dagger of this state using the dual."""
133
+ return self.dual
134
+
135
+ #-------------------------------------------------------------------------
136
+ # Printing
137
+ #-------------------------------------------------------------------------
138
+
139
+ def _pretty_brackets(self, height, use_unicode=True):
140
+ # Return pretty printed brackets for the state
141
+ # Ideally, this could be done by pform.parens but it does not support the angled < and >
142
+
143
+ # Setup for unicode vs ascii
144
+ if use_unicode:
145
+ lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
146
+ slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
147
+ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
148
+ '\N{BOX DRAWINGS LIGHT VERTICAL}'
149
+ else:
150
+ lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
151
+ slash, bslash, vert = '/', '\\', '|'
152
+
153
+ # If height is 1, just return brackets
154
+ if height == 1:
155
+ return stringPict(lbracket), stringPict(rbracket)
156
+ # Make height even
157
+ height += (height % 2)
158
+
159
+ brackets = []
160
+ for bracket in lbracket, rbracket:
161
+ # Create left bracket
162
+ if bracket in {_lbracket, _lbracket_ucode}:
163
+ bracket_args = [ ' ' * (height//2 - i - 1) +
164
+ slash for i in range(height // 2)]
165
+ bracket_args.extend(
166
+ [' ' * i + bslash for i in range(height // 2)])
167
+ # Create right bracket
168
+ elif bracket in {_rbracket, _rbracket_ucode}:
169
+ bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
170
+ bracket_args.extend([ ' ' * (
171
+ height//2 - i - 1) + slash for i in range(height // 2)])
172
+ # Create straight bracket
173
+ elif bracket in {_straight_bracket, _straight_bracket_ucode}:
174
+ bracket_args = [vert] * height
175
+ else:
176
+ raise ValueError(bracket)
177
+ brackets.append(
178
+ stringPict('\n'.join(bracket_args), baseline=height//2))
179
+ return brackets
180
+
181
+ def _sympystr(self, printer, *args):
182
+ contents = self._print_contents(printer, *args)
183
+ return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
184
+
185
+ def _pretty(self, printer, *args):
186
+ from sympy.printing.pretty.stringpict import prettyForm
187
+ # Get brackets
188
+ pform = self._print_contents_pretty(printer, *args)
189
+ lbracket, rbracket = self._pretty_brackets(
190
+ pform.height(), printer._use_unicode)
191
+ # Put together state
192
+ pform = prettyForm(*pform.left(lbracket))
193
+ pform = prettyForm(*pform.right(rbracket))
194
+ return pform
195
+
196
+ def _latex(self, printer, *args):
197
+ contents = self._print_contents_latex(printer, *args)
198
+ # The extra {} brackets are needed to get matplotlib's latex
199
+ # rendered to render this properly.
200
+ return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
201
+
202
+
203
+ class KetBase(StateBase):
204
+ """Base class for Kets.
205
+
206
+ This class defines the dual property and the brackets for printing. This is
207
+ an abstract base class and you should not instantiate it directly, instead
208
+ use Ket.
209
+ """
210
+
211
+ lbracket = _straight_bracket
212
+ rbracket = _rbracket
213
+ lbracket_ucode = _straight_bracket_ucode
214
+ rbracket_ucode = _rbracket_ucode
215
+ lbracket_latex = r'\left|'
216
+ rbracket_latex = r'\right\rangle '
217
+
218
+ @classmethod
219
+ def default_args(self):
220
+ return ("psi",)
221
+
222
+ @classmethod
223
+ def dual_class(self):
224
+ return BraBase
225
+
226
+ def __mul__(self, other):
227
+ """KetBase*other"""
228
+ from sympy.physics.quantum.operator import OuterProduct
229
+ if isinstance(other, BraBase):
230
+ return OuterProduct(self, other)
231
+ else:
232
+ return Expr.__mul__(self, other)
233
+
234
+ def __rmul__(self, other):
235
+ """other*KetBase"""
236
+ from sympy.physics.quantum.innerproduct import InnerProduct
237
+ if isinstance(other, BraBase):
238
+ return InnerProduct(other, self)
239
+ else:
240
+ return Expr.__rmul__(self, other)
241
+
242
+ #-------------------------------------------------------------------------
243
+ # _eval_* methods
244
+ #-------------------------------------------------------------------------
245
+
246
+ def _eval_innerproduct(self, bra, **hints):
247
+ """Evaluate the inner product between this ket and a bra.
248
+
249
+ This is called to compute <bra|ket>, where the ket is ``self``.
250
+
251
+ This method will dispatch to sub-methods having the format::
252
+
253
+ ``def _eval_innerproduct_BraClass(self, **hints):``
254
+
255
+ Subclasses should define these methods (one for each BraClass) to
256
+ teach the ket how to take inner products with bras.
257
+ """
258
+ return dispatch_method(self, '_eval_innerproduct', bra, **hints)
259
+
260
+ def _apply_from_right_to(self, op, **options):
261
+ """Apply an Operator to this Ket as Operator*Ket
262
+
263
+ This method will dispatch to methods having the format::
264
+
265
+ ``def _apply_from_right_to_OperatorName(op, **options):``
266
+
267
+ Subclasses should define these methods (one for each OperatorName) to
268
+ teach the Ket how to implement OperatorName*Ket
269
+
270
+ Parameters
271
+ ==========
272
+
273
+ op : Operator
274
+ The Operator that is acting on the Ket as op*Ket
275
+ options : dict
276
+ A dict of key/value pairs that control how the operator is applied
277
+ to the Ket.
278
+ """
279
+ return dispatch_method(self, '_apply_from_right_to', op, **options)
280
+
281
+
282
+ class BraBase(StateBase):
283
+ """Base class for Bras.
284
+
285
+ This class defines the dual property and the brackets for printing. This
286
+ is an abstract base class and you should not instantiate it directly,
287
+ instead use Bra.
288
+ """
289
+
290
+ lbracket = _lbracket
291
+ rbracket = _straight_bracket
292
+ lbracket_ucode = _lbracket_ucode
293
+ rbracket_ucode = _straight_bracket_ucode
294
+ lbracket_latex = r'\left\langle '
295
+ rbracket_latex = r'\right|'
296
+
297
+ @classmethod
298
+ def _operators_to_state(self, ops, **options):
299
+ state = self.dual_class()._operators_to_state(ops, **options)
300
+ return state.dual
301
+
302
+ def _state_to_operators(self, op_classes, **options):
303
+ return self.dual._state_to_operators(op_classes, **options)
304
+
305
+ def _enumerate_state(self, num_states, **options):
306
+ dual_states = self.dual._enumerate_state(num_states, **options)
307
+ return [x.dual for x in dual_states]
308
+
309
+ @classmethod
310
+ def default_args(self):
311
+ return self.dual_class().default_args()
312
+
313
+ @classmethod
314
+ def dual_class(self):
315
+ return KetBase
316
+
317
+ def __mul__(self, other):
318
+ """BraBase*other"""
319
+ from sympy.physics.quantum.innerproduct import InnerProduct
320
+ if isinstance(other, KetBase):
321
+ return InnerProduct(self, other)
322
+ else:
323
+ return Expr.__mul__(self, other)
324
+
325
+ def __rmul__(self, other):
326
+ """other*BraBase"""
327
+ from sympy.physics.quantum.operator import OuterProduct
328
+ if isinstance(other, KetBase):
329
+ return OuterProduct(other, self)
330
+ else:
331
+ return Expr.__rmul__(self, other)
332
+
333
+ def _represent(self, **options):
334
+ """A default represent that uses the Ket's version."""
335
+ from sympy.physics.quantum.dagger import Dagger
336
+ return Dagger(self.dual._represent(**options))
337
+
338
+
339
+ class State(StateBase):
340
+ """General abstract quantum state used as a base class for Ket and Bra."""
341
+ pass
342
+
343
+
344
+ class Ket(State, KetBase):
345
+ """A general time-independent Ket in quantum mechanics.
346
+
347
+ Inherits from State and KetBase. This class should be used as the base
348
+ class for all physical, time-independent Kets in a system. This class
349
+ and its subclasses will be the main classes that users will use for
350
+ expressing Kets in Dirac notation [1]_.
351
+
352
+ Parameters
353
+ ==========
354
+
355
+ args : tuple
356
+ The list of numbers or parameters that uniquely specify the
357
+ ket. This will usually be its symbol or its quantum numbers. For
358
+ time-dependent state, this will include the time.
359
+
360
+ Examples
361
+ ========
362
+
363
+ Create a simple Ket and looking at its properties::
364
+
365
+ >>> from sympy.physics.quantum import Ket
366
+ >>> from sympy import symbols, I
367
+ >>> k = Ket('psi')
368
+ >>> k
369
+ |psi>
370
+ >>> k.hilbert_space
371
+ H
372
+ >>> k.is_commutative
373
+ False
374
+ >>> k.label
375
+ (psi,)
376
+
377
+ Ket's know about their associated bra::
378
+
379
+ >>> k.dual
380
+ <psi|
381
+ >>> k.dual_class()
382
+ <class 'sympy.physics.quantum.state.Bra'>
383
+
384
+ Take a linear combination of two kets::
385
+
386
+ >>> k0 = Ket(0)
387
+ >>> k1 = Ket(1)
388
+ >>> 2*I*k0 - 4*k1
389
+ 2*I*|0> - 4*|1>
390
+
391
+ Compound labels are passed as tuples::
392
+
393
+ >>> n, m = symbols('n,m')
394
+ >>> k = Ket(n,m)
395
+ >>> k
396
+ |nm>
397
+
398
+ References
399
+ ==========
400
+
401
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
402
+ """
403
+
404
+ @classmethod
405
+ def dual_class(self):
406
+ return Bra
407
+
408
+
409
+ class Bra(State, BraBase):
410
+ """A general time-independent Bra in quantum mechanics.
411
+
412
+ Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
413
+ class and its subclasses will be the main classes that users will use for
414
+ expressing Bras in Dirac notation.
415
+
416
+ Parameters
417
+ ==========
418
+
419
+ args : tuple
420
+ The list of numbers or parameters that uniquely specify the
421
+ ket. This will usually be its symbol or its quantum numbers. For
422
+ time-dependent state, this will include the time.
423
+
424
+ Examples
425
+ ========
426
+
427
+ Create a simple Bra and look at its properties::
428
+
429
+ >>> from sympy.physics.quantum import Bra
430
+ >>> from sympy import symbols, I
431
+ >>> b = Bra('psi')
432
+ >>> b
433
+ <psi|
434
+ >>> b.hilbert_space
435
+ H
436
+ >>> b.is_commutative
437
+ False
438
+
439
+ Bra's know about their dual Ket's::
440
+
441
+ >>> b.dual
442
+ |psi>
443
+ >>> b.dual_class()
444
+ <class 'sympy.physics.quantum.state.Ket'>
445
+
446
+ Like Kets, Bras can have compound labels and be manipulated in a similar
447
+ manner::
448
+
449
+ >>> n, m = symbols('n,m')
450
+ >>> b = Bra(n,m) - I*Bra(m,n)
451
+ >>> b
452
+ -I*<mn| + <nm|
453
+
454
+ Symbols in a Bra can be substituted using ``.subs``::
455
+
456
+ >>> b.subs(n,m)
457
+ <mm| - I*<mm|
458
+
459
+ References
460
+ ==========
461
+
462
+ .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
463
+ """
464
+
465
+ @classmethod
466
+ def dual_class(self):
467
+ return Ket
468
+
469
+ #-----------------------------------------------------------------------------
470
+ # Time dependent states, bras and kets.
471
+ #-----------------------------------------------------------------------------
472
+
473
+
474
+ class TimeDepState(StateBase):
475
+ """Base class for a general time-dependent quantum state.
476
+
477
+ This class is used as a base class for any time-dependent state. The main
478
+ difference between this class and the time-independent state is that this
479
+ class takes a second argument that is the time in addition to the usual
480
+ label argument.
481
+
482
+ Parameters
483
+ ==========
484
+
485
+ args : tuple
486
+ The list of numbers or parameters that uniquely specify the ket. This
487
+ will usually be its symbol or its quantum numbers. For time-dependent
488
+ state, this will include the time as the final argument.
489
+ """
490
+
491
+ #-------------------------------------------------------------------------
492
+ # Initialization
493
+ #-------------------------------------------------------------------------
494
+
495
+ @classmethod
496
+ def default_args(self):
497
+ return ("psi", "t")
498
+
499
+ #-------------------------------------------------------------------------
500
+ # Properties
501
+ #-------------------------------------------------------------------------
502
+
503
+ @property
504
+ def label(self):
505
+ """The label of the state."""
506
+ return self.args[:-1]
507
+
508
+ @property
509
+ def time(self):
510
+ """The time of the state."""
511
+ return self.args[-1]
512
+
513
+ #-------------------------------------------------------------------------
514
+ # Printing
515
+ #-------------------------------------------------------------------------
516
+
517
+ def _print_time(self, printer, *args):
518
+ return printer._print(self.time, *args)
519
+
520
+ _print_time_repr = _print_time
521
+ _print_time_latex = _print_time
522
+
523
+ def _print_time_pretty(self, printer, *args):
524
+ pform = printer._print(self.time, *args)
525
+ return pform
526
+
527
+ def _print_contents(self, printer, *args):
528
+ label = self._print_label(printer, *args)
529
+ time = self._print_time(printer, *args)
530
+ return '%s;%s' % (label, time)
531
+
532
+ def _print_label_repr(self, printer, *args):
533
+ label = self._print_sequence(self.label, ',', printer, *args)
534
+ time = self._print_time_repr(printer, *args)
535
+ return '%s,%s' % (label, time)
536
+
537
+ def _print_contents_pretty(self, printer, *args):
538
+ label = self._print_label_pretty(printer, *args)
539
+ time = self._print_time_pretty(printer, *args)
540
+ return printer._print_seq((label, time), delimiter=';')
541
+
542
+ def _print_contents_latex(self, printer, *args):
543
+ label = self._print_sequence(
544
+ self.label, self._label_separator, printer, *args)
545
+ time = self._print_time_latex(printer, *args)
546
+ return '%s;%s' % (label, time)
547
+
548
+
549
+ class TimeDepKet(TimeDepState, KetBase):
550
+ """General time-dependent Ket in quantum mechanics.
551
+
552
+ This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
553
+ that should be used for Kets that vary with time. Its dual is a
554
+ ``TimeDepBra``.
555
+
556
+ Parameters
557
+ ==========
558
+
559
+ args : tuple
560
+ The list of numbers or parameters that uniquely specify the ket. This
561
+ will usually be its symbol or its quantum numbers. For time-dependent
562
+ state, this will include the time as the final argument.
563
+
564
+ Examples
565
+ ========
566
+
567
+ Create a TimeDepKet and look at its attributes::
568
+
569
+ >>> from sympy.physics.quantum import TimeDepKet
570
+ >>> k = TimeDepKet('psi', 't')
571
+ >>> k
572
+ |psi;t>
573
+ >>> k.time
574
+ t
575
+ >>> k.label
576
+ (psi,)
577
+ >>> k.hilbert_space
578
+ H
579
+
580
+ TimeDepKets know about their dual bra::
581
+
582
+ >>> k.dual
583
+ <psi;t|
584
+ >>> k.dual_class()
585
+ <class 'sympy.physics.quantum.state.TimeDepBra'>
586
+ """
587
+
588
+ @classmethod
589
+ def dual_class(self):
590
+ return TimeDepBra
591
+
592
+
593
+ class TimeDepBra(TimeDepState, BraBase):
594
+ """General time-dependent Bra in quantum mechanics.
595
+
596
+ This inherits from TimeDepState and BraBase and is the main class that
597
+ should be used for Bras that vary with time. Its dual is a TimeDepBra.
598
+
599
+ Parameters
600
+ ==========
601
+
602
+ args : tuple
603
+ The list of numbers or parameters that uniquely specify the ket. This
604
+ will usually be its symbol or its quantum numbers. For time-dependent
605
+ state, this will include the time as the final argument.
606
+
607
+ Examples
608
+ ========
609
+
610
+ >>> from sympy.physics.quantum import TimeDepBra
611
+ >>> b = TimeDepBra('psi', 't')
612
+ >>> b
613
+ <psi;t|
614
+ >>> b.time
615
+ t
616
+ >>> b.label
617
+ (psi,)
618
+ >>> b.hilbert_space
619
+ H
620
+ >>> b.dual
621
+ |psi;t>
622
+ """
623
+
624
+ @classmethod
625
+ def dual_class(self):
626
+ return TimeDepKet
627
+
628
+
629
+ class OrthogonalState(State, StateBase):
630
+ """General abstract quantum state used as a base class for Ket and Bra."""
631
+ pass
632
+
633
+ class OrthogonalKet(OrthogonalState, KetBase):
634
+ """Orthogonal Ket in quantum mechanics.
635
+
636
+ The inner product of two states with different labels will give zero,
637
+ states with the same label will give one.
638
+
639
+ >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
640
+ >>> from sympy.abc import m, n
641
+ >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
642
+ 1
643
+ >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
644
+ 0
645
+ >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
646
+ <n|m>
647
+ """
648
+
649
+ @classmethod
650
+ def dual_class(self):
651
+ return OrthogonalBra
652
+
653
+ def _eval_innerproduct(self, bra, **hints):
654
+
655
+ if len(self.args) != len(bra.args):
656
+ raise ValueError('Cannot multiply a ket that has a different number of labels.')
657
+
658
+ for arg, bra_arg in zip(self.args, bra.args):
659
+ diff = arg - bra_arg
660
+ diff = diff.expand()
661
+
662
+ is_zero = diff.is_zero
663
+
664
+ if is_zero is False:
665
+ return S.Zero # i.e. Integer(0)
666
+
667
+ if is_zero is None:
668
+ return None
669
+
670
+ return S.One # i.e. Integer(1)
671
+
672
+
673
+ class OrthogonalBra(OrthogonalState, BraBase):
674
+ """Orthogonal Bra in quantum mechanics.
675
+ """
676
+
677
+ @classmethod
678
+ def dual_class(self):
679
+ return OrthogonalKet
680
+
681
+
682
+ class Wavefunction(Function):
683
+ """Class for representations in continuous bases
684
+
685
+ This class takes an expression and coordinates in its constructor. It can
686
+ be used to easily calculate normalizations and probabilities.
687
+
688
+ Parameters
689
+ ==========
690
+
691
+ expr : Expr
692
+ The expression representing the functional form of the w.f.
693
+
694
+ coords : Symbol or tuple
695
+ The coordinates to be integrated over, and their bounds
696
+
697
+ Examples
698
+ ========
699
+
700
+ Particle in a box, specifying bounds in the more primitive way of using
701
+ Piecewise:
702
+
703
+ >>> from sympy import Symbol, Piecewise, pi, N
704
+ >>> from sympy.functions import sqrt, sin
705
+ >>> from sympy.physics.quantum.state import Wavefunction
706
+ >>> x = Symbol('x', real=True)
707
+ >>> n = 1
708
+ >>> L = 1
709
+ >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
710
+ >>> f = Wavefunction(g, x)
711
+ >>> f.norm
712
+ 1
713
+ >>> f.is_normalized
714
+ True
715
+ >>> p = f.prob()
716
+ >>> p(0)
717
+ 0
718
+ >>> p(L)
719
+ 0
720
+ >>> p(0.5)
721
+ 2
722
+ >>> p(0.85*L)
723
+ 2*sin(0.85*pi)**2
724
+ >>> N(p(0.85*L))
725
+ 0.412214747707527
726
+
727
+ Additionally, you can specify the bounds of the function and the indices in
728
+ a more compact way:
729
+
730
+ >>> from sympy import symbols, pi, diff
731
+ >>> from sympy.functions import sqrt, sin
732
+ >>> from sympy.physics.quantum.state import Wavefunction
733
+ >>> x, L = symbols('x,L', positive=True)
734
+ >>> n = symbols('n', integer=True, positive=True)
735
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
736
+ >>> f = Wavefunction(g, (x, 0, L))
737
+ >>> f.norm
738
+ 1
739
+ >>> f(L+1)
740
+ 0
741
+ >>> f(L-1)
742
+ sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
743
+ >>> f(-1)
744
+ 0
745
+ >>> f(0.85)
746
+ sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
747
+ >>> f(0.85, n=1, L=1)
748
+ sqrt(2)*sin(0.85*pi)
749
+ >>> f.is_commutative
750
+ False
751
+
752
+ All arguments are automatically sympified, so you can define the variables
753
+ as strings rather than symbols:
754
+
755
+ >>> expr = x**2
756
+ >>> f = Wavefunction(expr, 'x')
757
+ >>> type(f.variables[0])
758
+ <class 'sympy.core.symbol.Symbol'>
759
+
760
+ Derivatives of Wavefunctions will return Wavefunctions:
761
+
762
+ >>> diff(f, x)
763
+ Wavefunction(2*x, x)
764
+
765
+ """
766
+
767
+ #Any passed tuples for coordinates and their bounds need to be
768
+ #converted to Tuples before Function's constructor is called, to
769
+ #avoid errors from calling is_Float in the constructor
770
+ def __new__(cls, *args, **options):
771
+ new_args = [None for i in args]
772
+ ct = 0
773
+ for arg in args:
774
+ if isinstance(arg, tuple):
775
+ new_args[ct] = Tuple(*arg)
776
+ else:
777
+ new_args[ct] = arg
778
+ ct += 1
779
+
780
+ return super().__new__(cls, *new_args, **options)
781
+
782
+ def __call__(self, *args, **options):
783
+ var = self.variables
784
+
785
+ if len(args) != len(var):
786
+ raise NotImplementedError(
787
+ "Incorrect number of arguments to function!")
788
+
789
+ ct = 0
790
+ #If the passed value is outside the specified bounds, return 0
791
+ for v in var:
792
+ lower, upper = self.limits[v]
793
+
794
+ #Do the comparison to limits only if the passed symbol is actually
795
+ #a symbol present in the limits;
796
+ #Had problems with a comparison of x > L
797
+ if isinstance(args[ct], Expr) and \
798
+ not (lower in args[ct].free_symbols
799
+ or upper in args[ct].free_symbols):
800
+ continue
801
+
802
+ if (args[ct] < lower) == True or (args[ct] > upper) == True:
803
+ return S.Zero
804
+
805
+ ct += 1
806
+
807
+ expr = self.expr
808
+
809
+ #Allows user to make a call like f(2, 4, m=1, n=1)
810
+ for symbol in list(expr.free_symbols):
811
+ if str(symbol) in options.keys():
812
+ val = options[str(symbol)]
813
+ expr = expr.subs(symbol, val)
814
+
815
+ return expr.subs(zip(var, args))
816
+
817
+ def _eval_derivative(self, symbol):
818
+ expr = self.expr
819
+ deriv = expr._eval_derivative(symbol)
820
+
821
+ return Wavefunction(deriv, *self.args[1:])
822
+
823
+ def _eval_conjugate(self):
824
+ return Wavefunction(conjugate(self.expr), *self.args[1:])
825
+
826
+ def _eval_transpose(self):
827
+ return self
828
+
829
+ @property
830
+ def free_symbols(self):
831
+ return self.expr.free_symbols
832
+
833
+ @property
834
+ def is_commutative(self):
835
+ """
836
+ Override Function's is_commutative so that order is preserved in
837
+ represented expressions
838
+ """
839
+ return False
840
+
841
+ @classmethod
842
+ def eval(self, *args):
843
+ return None
844
+
845
+ @property
846
+ def variables(self):
847
+ """
848
+ Return the coordinates which the wavefunction depends on
849
+
850
+ Examples
851
+ ========
852
+
853
+ >>> from sympy.physics.quantum.state import Wavefunction
854
+ >>> from sympy import symbols
855
+ >>> x,y = symbols('x,y')
856
+ >>> f = Wavefunction(x*y, x, y)
857
+ >>> f.variables
858
+ (x, y)
859
+ >>> g = Wavefunction(x*y, x)
860
+ >>> g.variables
861
+ (x,)
862
+
863
+ """
864
+ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
865
+ return tuple(var)
866
+
867
+ @property
868
+ def limits(self):
869
+ """
870
+ Return the limits of the coordinates which the w.f. depends on If no
871
+ limits are specified, defaults to ``(-oo, oo)``.
872
+
873
+ Examples
874
+ ========
875
+
876
+ >>> from sympy.physics.quantum.state import Wavefunction
877
+ >>> from sympy import symbols
878
+ >>> x, y = symbols('x, y')
879
+ >>> f = Wavefunction(x**2, (x, 0, 1))
880
+ >>> f.limits
881
+ {x: (0, 1)}
882
+ >>> f = Wavefunction(x**2, x)
883
+ >>> f.limits
884
+ {x: (-oo, oo)}
885
+ >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
886
+ >>> f.limits
887
+ {x: (-oo, oo), y: (-1, 2)}
888
+
889
+ """
890
+ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
891
+ for g in self._args[1:]]
892
+ return dict(zip(self.variables, tuple(limits)))
893
+
894
+ @property
895
+ def expr(self):
896
+ """
897
+ Return the expression which is the functional form of the Wavefunction
898
+
899
+ Examples
900
+ ========
901
+
902
+ >>> from sympy.physics.quantum.state import Wavefunction
903
+ >>> from sympy import symbols
904
+ >>> x, y = symbols('x, y')
905
+ >>> f = Wavefunction(x**2, x)
906
+ >>> f.expr
907
+ x**2
908
+
909
+ """
910
+ return self._args[0]
911
+
912
+ @property
913
+ def is_normalized(self):
914
+ """
915
+ Returns true if the Wavefunction is properly normalized
916
+
917
+ Examples
918
+ ========
919
+
920
+ >>> from sympy import symbols, pi
921
+ >>> from sympy.functions import sqrt, sin
922
+ >>> from sympy.physics.quantum.state import Wavefunction
923
+ >>> x, L = symbols('x,L', positive=True)
924
+ >>> n = symbols('n', integer=True, positive=True)
925
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
926
+ >>> f = Wavefunction(g, (x, 0, L))
927
+ >>> f.is_normalized
928
+ True
929
+
930
+ """
931
+
932
+ return equal_valued(self.norm, 1)
933
+
934
+ @property # type: ignore
935
+ @cacheit
936
+ def norm(self):
937
+ """
938
+ Return the normalization of the specified functional form.
939
+
940
+ This function integrates over the coordinates of the Wavefunction, with
941
+ the bounds specified.
942
+
943
+ Examples
944
+ ========
945
+
946
+ >>> from sympy import symbols, pi
947
+ >>> from sympy.functions import sqrt, sin
948
+ >>> from sympy.physics.quantum.state import Wavefunction
949
+ >>> x, L = symbols('x,L', positive=True)
950
+ >>> n = symbols('n', integer=True, positive=True)
951
+ >>> g = sqrt(2/L)*sin(n*pi*x/L)
952
+ >>> f = Wavefunction(g, (x, 0, L))
953
+ >>> f.norm
954
+ 1
955
+ >>> g = sin(n*pi*x/L)
956
+ >>> f = Wavefunction(g, (x, 0, L))
957
+ >>> f.norm
958
+ sqrt(2)*sqrt(L)/2
959
+
960
+ """
961
+
962
+ exp = self.expr*conjugate(self.expr)
963
+ var = self.variables
964
+ limits = self.limits
965
+
966
+ for v in var:
967
+ curr_limits = limits[v]
968
+ exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
969
+
970
+ return sqrt(exp)
971
+
972
+ def normalize(self):
973
+ """
974
+ Return a normalized version of the Wavefunction
975
+
976
+ Examples
977
+ ========
978
+
979
+ >>> from sympy import symbols, pi
980
+ >>> from sympy.functions import sin
981
+ >>> from sympy.physics.quantum.state import Wavefunction
982
+ >>> x = symbols('x', real=True)
983
+ >>> L = symbols('L', positive=True)
984
+ >>> n = symbols('n', integer=True, positive=True)
985
+ >>> g = sin(n*pi*x/L)
986
+ >>> f = Wavefunction(g, (x, 0, L))
987
+ >>> f.normalize()
988
+ Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
989
+
990
+ """
991
+ const = self.norm
992
+
993
+ if const is oo:
994
+ raise NotImplementedError("The function is not normalizable!")
995
+ else:
996
+ return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
997
+
998
+ def prob(self):
999
+ r"""
1000
+ Return the absolute magnitude of the w.f., `|\psi(x)|^2`
1001
+
1002
+ Examples
1003
+ ========
1004
+
1005
+ >>> from sympy import symbols, pi
1006
+ >>> from sympy.functions import sin
1007
+ >>> from sympy.physics.quantum.state import Wavefunction
1008
+ >>> x, L = symbols('x,L', real=True)
1009
+ >>> n = symbols('n', integer=True)
1010
+ >>> g = sin(n*pi*x/L)
1011
+ >>> f = Wavefunction(g, (x, 0, L))
1012
+ >>> f.prob()
1013
+ Wavefunction(sin(pi*n*x/L)**2, x)
1014
+
1015
+ """
1016
+
1017
+ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py ADDED
File without changes
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitutils.cpython-310.pyc ADDED
Binary file (8.81 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc ADDED
Binary file (3.45 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_constants.cpython-310.pyc ADDED
Binary file (595 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc ADDED
Binary file (1.84 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_grover.cpython-310.pyc ADDED
Binary file (3.45 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_identitysearch.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operator.cpython-310.pyc ADDED
Binary file (7.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qapply.cpython-310.pyc ADDED
Binary file (6.35 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qasm.cpython-310.pyc ADDED
Binary file (4.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qexpr.cpython-310.pyc ADDED
Binary file (1.89 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qft.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc ADDED
Binary file (6.22 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_tensorproduct.cpython-310.pyc ADDED
Binary file (4.85 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc ADDED
Binary file (3.31 kB). View file
 
evalkit_tf437/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)
evalkit_tf437/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
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+
3
+ from sympy.physics.quantum.constants import hbar
4
+
5
+
6
+ def test_hbar():
7
+ assert hbar.is_commutative is True
8
+ assert hbar.is_real is True
9
+ assert hbar.is_positive is True
10
+ assert hbar.is_negative is False
11
+ assert hbar.is_irrational is True
12
+
13
+ assert hbar.evalf() == Float(1.05457162e-34)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_density.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import log
5
+ from sympy.external import import_module
6
+ from sympy.physics.quantum.density import Density, entropy, fidelity
7
+ from sympy.physics.quantum.state import Ket, TimeDepKet
8
+ from sympy.physics.quantum.qubit import Qubit
9
+ from sympy.physics.quantum.represent import represent
10
+ from sympy.physics.quantum.dagger import Dagger
11
+ from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp
12
+ from sympy.physics.quantum.spin import JzKet
13
+ from sympy.physics.quantum.operator import OuterProduct
14
+ from sympy.physics.quantum.trace import Tr
15
+ from sympy.functions import sqrt
16
+ from sympy.testing.pytest import raises
17
+ from sympy.physics.quantum.matrixutils import scipy_sparse_matrix
18
+ from sympy.physics.quantum.tensorproduct import TensorProduct
19
+
20
+
21
+ def test_eval_args():
22
+ # check instance created
23
+ assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density)
24
+ assert isinstance(Density([Qubit('00'), 1/sqrt(2)],
25
+ [Qubit('11'), 1/sqrt(2)]), Density)
26
+
27
+ #test if Qubit object type preserved
28
+ d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)])
29
+ for (state, prob) in d.args:
30
+ assert isinstance(state, Qubit)
31
+
32
+ # check for value error, when prob is not provided
33
+ raises(ValueError, lambda: Density([Ket(0)], [Ket(1)]))
34
+
35
+
36
+ def test_doit():
37
+
38
+ x, y = symbols('x y')
39
+ A, B, C, D, E, F = symbols('A B C D E F', commutative=False)
40
+ d = Density([XKet(), 0.5], [PxKet(), 0.5])
41
+ assert (0.5*(PxKet()*Dagger(PxKet())) +
42
+ 0.5*(XKet()*Dagger(XKet()))) == d.doit()
43
+
44
+ # check for kets with expr in them
45
+ d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
46
+ assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) +
47
+ 0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit()
48
+
49
+ d = Density([(A + B)*C, 1.0])
50
+ assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) +
51
+ 1.0*A*C*Dagger(C)*Dagger(B) +
52
+ 1.0*B*C*Dagger(C)*Dagger(A) +
53
+ 1.0*B*C*Dagger(C)*Dagger(B))
54
+
55
+ # With TensorProducts as args
56
+ # Density with simple tensor products as args
57
+ t = TensorProduct(A, B, C)
58
+ d = Density([t, 1.0])
59
+ assert d.doit() == \
60
+ 1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C))
61
+
62
+ # Density with multiple Tensorproducts as states
63
+ t2 = TensorProduct(A, B)
64
+ t3 = TensorProduct(C, D)
65
+
66
+ d = Density([t2, 0.5], [t3, 0.5])
67
+ assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
68
+ 0.5 * TensorProduct(C*Dagger(C), D*Dagger(D)))
69
+
70
+ #Density with mixed states
71
+ d = Density([t2 + t3, 1.0])
72
+ assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) +
73
+ 1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) +
74
+ 1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) +
75
+ 1.0 * TensorProduct(C*Dagger(C), D*Dagger(D)))
76
+
77
+ #Density operators with spin states
78
+ tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1))
79
+ d = Density([tp1, 1])
80
+
81
+ # full trace
82
+ t = Tr(d)
83
+ assert t.doit() == 1
84
+
85
+ #Partial trace on density operators with spin states
86
+ t = Tr(d, [0])
87
+ assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1))
88
+ t = Tr(d, [1])
89
+ assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1))
90
+
91
+ # with another spin state
92
+ tp2 = TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2)))
93
+ d = Density([tp2, 1])
94
+
95
+ #full trace
96
+ t = Tr(d)
97
+ assert t.doit() == 1
98
+
99
+ #Partial trace on density operators with spin states
100
+ t = Tr(d, [0])
101
+ assert t.doit() == JzKet(S.Half, Rational(-1, 2)) * Dagger(JzKet(S.Half, Rational(-1, 2)))
102
+ t = Tr(d, [1])
103
+ assert t.doit() == JzKet(S.Half, S.Half) * Dagger(JzKet(S.Half, S.Half))
104
+
105
+
106
+ def test_apply_op():
107
+ d = Density([Ket(0), 0.5], [Ket(1), 0.5])
108
+ assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5],
109
+ [XOp()*Ket(1), 0.5])
110
+
111
+
112
+ def test_represent():
113
+ x, y = symbols('x y')
114
+ d = Density([XKet(), 0.5], [PxKet(), 0.5])
115
+ assert (represent(0.5*(PxKet()*Dagger(PxKet()))) +
116
+ represent(0.5*(XKet()*Dagger(XKet())))) == represent(d)
117
+
118
+ # check for kets with expr in them
119
+ d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5])
120
+ assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) +
121
+ represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \
122
+ represent(d_with_sym)
123
+
124
+ # check when given explicit basis
125
+ assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) +
126
+ represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \
127
+ represent(d, basis=PxOp())
128
+
129
+
130
+ def test_states():
131
+ d = Density([Ket(0), 0.5], [Ket(1), 0.5])
132
+ states = d.states()
133
+ assert states[0] == Ket(0) and states[1] == Ket(1)
134
+
135
+
136
+ def test_probs():
137
+ d = Density([Ket(0), .75], [Ket(1), 0.25])
138
+ probs = d.probs()
139
+ assert probs[0] == 0.75 and probs[1] == 0.25
140
+
141
+ #probs can be symbols
142
+ x, y = symbols('x y')
143
+ d = Density([Ket(0), x], [Ket(1), y])
144
+ probs = d.probs()
145
+ assert probs[0] == x and probs[1] == y
146
+
147
+
148
+ def test_get_state():
149
+ x, y = symbols('x y')
150
+ d = Density([Ket(0), x], [Ket(1), y])
151
+ states = (d.get_state(0), d.get_state(1))
152
+ assert states[0] == Ket(0) and states[1] == Ket(1)
153
+
154
+
155
+ def test_get_prob():
156
+ x, y = symbols('x y')
157
+ d = Density([Ket(0), x], [Ket(1), y])
158
+ probs = (d.get_prob(0), d.get_prob(1))
159
+ assert probs[0] == x and probs[1] == y
160
+
161
+
162
+ def test_entropy():
163
+ up = JzKet(S.Half, S.Half)
164
+ down = JzKet(S.Half, Rational(-1, 2))
165
+ d = Density((up, S.Half), (down, S.Half))
166
+
167
+ # test for density object
168
+ ent = entropy(d)
169
+ assert entropy(d) == log(2)/2
170
+ assert d.entropy() == log(2)/2
171
+
172
+ np = import_module('numpy', min_module_version='1.4.0')
173
+ if np:
174
+ #do this test only if 'numpy' is available on test machine
175
+ np_mat = represent(d, format='numpy')
176
+ ent = entropy(np_mat)
177
+ assert isinstance(np_mat, np.ndarray)
178
+ assert ent.real == 0.69314718055994529
179
+ assert ent.imag == 0
180
+
181
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
182
+ if scipy and np:
183
+ #do this test only if numpy and scipy are available
184
+ mat = represent(d, format="scipy.sparse")
185
+ assert isinstance(mat, scipy_sparse_matrix)
186
+ assert ent.real == 0.69314718055994529
187
+ assert ent.imag == 0
188
+
189
+
190
+ def test_eval_trace():
191
+ up = JzKet(S.Half, S.Half)
192
+ down = JzKet(S.Half, Rational(-1, 2))
193
+ d = Density((up, 0.5), (down, 0.5))
194
+
195
+ t = Tr(d)
196
+ assert t.doit() == 1.0
197
+
198
+ #test dummy time dependent states
199
+ class TestTimeDepKet(TimeDepKet):
200
+ def _eval_trace(self, bra, **options):
201
+ return 1
202
+
203
+ x, t = symbols('x t')
204
+ k1 = TestTimeDepKet(0, 0.5)
205
+ k2 = TestTimeDepKet(0, 1)
206
+ d = Density([k1, 0.5], [k2, 0.5])
207
+ assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) +
208
+ 0.5 * OuterProduct(k2, k2.dual))
209
+
210
+ t = Tr(d)
211
+ assert t.doit() == 1.0
212
+
213
+
214
+ def test_fidelity():
215
+ #test with kets
216
+ up = JzKet(S.Half, S.Half)
217
+ down = JzKet(S.Half, Rational(-1, 2))
218
+ updown = (S.One/sqrt(2))*up + (S.One/sqrt(2))*down
219
+
220
+ #check with matrices
221
+ up_dm = represent(up * Dagger(up))
222
+ down_dm = represent(down * Dagger(down))
223
+ updown_dm = represent(updown * Dagger(updown))
224
+
225
+ assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
226
+ assert fidelity(up_dm, down_dm) < 1e-3
227
+ assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
228
+ assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
229
+
230
+ #check with density
231
+ up_dm = Density([up, 1.0])
232
+ down_dm = Density([down, 1.0])
233
+ updown_dm = Density([updown, 1.0])
234
+
235
+ assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3
236
+ assert abs(fidelity(up_dm, down_dm)) < 1e-3
237
+ assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3
238
+ assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3
239
+
240
+ #check mixed states with density
241
+ updown2 = sqrt(3)/2*up + S.Half*down
242
+ d1 = Density([updown, 0.25], [updown2, 0.75])
243
+ d2 = Density([updown, 0.75], [updown2, 0.25])
244
+ assert abs(fidelity(d1, d2) - 0.991) < 1e-3
245
+ assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3
246
+
247
+ #using qubits/density(pure states)
248
+ state1 = Qubit('0')
249
+ state2 = Qubit('1')
250
+ state3 = S.One/sqrt(2)*state1 + S.One/sqrt(2)*state2
251
+ state4 = sqrt(Rational(2, 3))*state1 + S.One/sqrt(3)*state2
252
+
253
+ state1_dm = Density([state1, 1])
254
+ state2_dm = Density([state2, 1])
255
+ state3_dm = Density([state3, 1])
256
+
257
+ assert fidelity(state1_dm, state1_dm) == 1
258
+ assert fidelity(state1_dm, state2_dm) == 0
259
+ assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3
260
+ assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3
261
+
262
+ #using qubits/density(mixed states)
263
+ d1 = Density([state3, 0.70], [state4, 0.30])
264
+ d2 = Density([state3, 0.20], [state4, 0.80])
265
+ assert abs(fidelity(d1, d1) - 1) < 1e-3
266
+ assert abs(fidelity(d1, d2) - 0.996) < 1e-3
267
+ assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3
268
+
269
+ #TODO: test for invalid arguments
270
+ # non-square matrix
271
+ mat1 = [[0, 0],
272
+ [0, 0],
273
+ [0, 0]]
274
+
275
+ mat2 = [[0, 0],
276
+ [0, 0]]
277
+ raises(ValueError, lambda: fidelity(mat1, mat2))
278
+
279
+ # unequal dimensions
280
+ mat1 = [[0, 0],
281
+ [0, 0]]
282
+ mat2 = [[0, 0, 0],
283
+ [0, 0, 0],
284
+ [0, 0, 0]]
285
+ raises(ValueError, lambda: fidelity(mat1, mat2))
286
+
287
+ # unsupported data-type
288
+ x, y = 1, 2 # random values that is not a matrix
289
+ raises(ValueError, lambda: fidelity(x, y))
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pytest import raises
2
+
3
+ import sympy
4
+ from sympy.physics.quantum import Dagger, AntiCommutator, qapply
5
+ from sympy.physics.quantum.fermion import FermionOp
6
+ from sympy.physics.quantum.fermion import FermionFockKet, FermionFockBra
7
+ from sympy import Symbol
8
+
9
+
10
+ def test_fermionoperator():
11
+ c = FermionOp('c')
12
+ d = FermionOp('d')
13
+
14
+ assert isinstance(c, FermionOp)
15
+ assert isinstance(Dagger(c), FermionOp)
16
+
17
+ assert c.is_annihilation
18
+ assert not Dagger(c).is_annihilation
19
+
20
+ assert FermionOp("c") == FermionOp("c", True)
21
+ assert FermionOp("c") != FermionOp("d")
22
+ assert FermionOp("c", True) != FermionOp("c", False)
23
+
24
+ assert AntiCommutator(c, Dagger(c)).doit() == 1
25
+
26
+ assert AntiCommutator(c, Dagger(d)).doit() == c * Dagger(d) + Dagger(d) * c
27
+
28
+
29
+ def test_fermion_states():
30
+ c = FermionOp("c")
31
+
32
+ # Fock states
33
+ assert (FermionFockBra(0) * FermionFockKet(1)).doit() == 0
34
+ assert (FermionFockBra(1) * FermionFockKet(1)).doit() == 1
35
+
36
+ assert qapply(c * FermionFockKet(1)) == FermionFockKet(0)
37
+ assert qapply(c * FermionFockKet(0)) == 0
38
+
39
+ assert qapply(Dagger(c) * FermionFockKet(0)) == FermionFockKet(1)
40
+ assert qapply(Dagger(c) * FermionFockKet(1)) == 0
41
+
42
+
43
+ def test_power():
44
+ c = FermionOp("c")
45
+ assert c**0 == 1
46
+ assert c**1 == c
47
+ assert c**2 == 0
48
+ assert c**3 == 0
49
+ assert Dagger(c)**1 == Dagger(c)
50
+ assert Dagger(c)**2 == 0
51
+
52
+ assert (c**Symbol('a')).func == sympy.core.power.Pow
53
+ assert (c**Symbol('a')).args == (c, Symbol('a'))
54
+
55
+ with raises(ValueError):
56
+ c**-1
57
+
58
+ with raises(ValueError):
59
+ c**3.2
60
+
61
+ with raises(TypeError):
62
+ c**1j
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.mul import Mul
2
+ from sympy.core.numbers import (I, Integer, Rational, pi)
3
+ from sympy.core.symbol import (Wild, symbols)
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.matrices import Matrix, ImmutableMatrix
7
+
8
+ from sympy.physics.quantum.gate import (XGate, YGate, ZGate, random_circuit,
9
+ CNOT, IdentityGate, H, X, Y, S, T, Z, SwapGate, gate_simp, gate_sort,
10
+ CNotGate, TGate, HadamardGate, PhaseGate, UGate, CGate)
11
+ from sympy.physics.quantum.commutator import Commutator
12
+ from sympy.physics.quantum.anticommutator import AntiCommutator
13
+ from sympy.physics.quantum.represent import represent
14
+ from sympy.physics.quantum.qapply import qapply
15
+ from sympy.physics.quantum.qubit import Qubit, IntQubit, qubit_to_matrix, \
16
+ matrix_to_qubit
17
+ from sympy.physics.quantum.matrixutils import matrix_to_zero
18
+ from sympy.physics.quantum.matrixcache import sqrt2_inv
19
+ from sympy.physics.quantum import Dagger
20
+
21
+
22
+ def test_gate():
23
+ """Test a basic gate."""
24
+ h = HadamardGate(1)
25
+ assert h.min_qubits == 2
26
+ assert h.nqubits == 1
27
+
28
+ i0 = Wild('i0')
29
+ i1 = Wild('i1')
30
+ h0_w1 = HadamardGate(i0)
31
+ h0_w2 = HadamardGate(i0)
32
+ h1_w1 = HadamardGate(i1)
33
+
34
+ assert h0_w1 == h0_w2
35
+ assert h0_w1 != h1_w1
36
+ assert h1_w1 != h0_w2
37
+
38
+ cnot_10_w1 = CNOT(i1, i0)
39
+ cnot_10_w2 = CNOT(i1, i0)
40
+ cnot_01_w1 = CNOT(i0, i1)
41
+
42
+ assert cnot_10_w1 == cnot_10_w2
43
+ assert cnot_10_w1 != cnot_01_w1
44
+ assert cnot_10_w2 != cnot_01_w1
45
+
46
+
47
+ def test_UGate():
48
+ a, b, c, d = symbols('a,b,c,d')
49
+ uMat = Matrix([[a, b], [c, d]])
50
+
51
+ # Test basic case where gate exists in 1-qubit space
52
+ u1 = UGate((0,), uMat)
53
+ assert represent(u1, nqubits=1) == uMat
54
+ assert qapply(u1*Qubit('0')) == a*Qubit('0') + c*Qubit('1')
55
+ assert qapply(u1*Qubit('1')) == b*Qubit('0') + d*Qubit('1')
56
+
57
+ # Test case where gate exists in a larger space
58
+ u2 = UGate((1,), uMat)
59
+ u2Rep = represent(u2, nqubits=2)
60
+ for i in range(4):
61
+ assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
62
+ qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
63
+
64
+
65
+ def test_cgate():
66
+ """Test the general CGate."""
67
+ # Test single control functionality
68
+ CNOTMatrix = Matrix(
69
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
70
+ assert represent(CGate(1, XGate(0)), nqubits=2) == CNOTMatrix
71
+
72
+ # Test multiple control bit functionality
73
+ ToffoliGate = CGate((1, 2), XGate(0))
74
+ assert represent(ToffoliGate, nqubits=3) == \
75
+ Matrix(
76
+ [[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0],
77
+ [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0,
78
+ 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1],
79
+ [0, 0, 0, 0, 0, 0, 1, 0]])
80
+
81
+ ToffoliGate = CGate((3, 0), XGate(1))
82
+ assert qapply(ToffoliGate*Qubit('1001')) == \
83
+ matrix_to_qubit(represent(ToffoliGate*Qubit('1001'), nqubits=4))
84
+ assert qapply(ToffoliGate*Qubit('0000')) == \
85
+ matrix_to_qubit(represent(ToffoliGate*Qubit('0000'), nqubits=4))
86
+
87
+ CYGate = CGate(1, YGate(0))
88
+ CYGate_matrix = Matrix(
89
+ ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 0, -I), (0, 0, I, 0)))
90
+ # Test 2 qubit controlled-Y gate decompose method.
91
+ assert represent(CYGate.decompose(), nqubits=2) == CYGate_matrix
92
+
93
+ CZGate = CGate(0, ZGate(1))
94
+ CZGate_matrix = Matrix(
95
+ ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, -1)))
96
+ assert qapply(CZGate*Qubit('11')) == -Qubit('11')
97
+ assert matrix_to_qubit(represent(CZGate*Qubit('11'), nqubits=2)) == \
98
+ -Qubit('11')
99
+ # Test 2 qubit controlled-Z gate decompose method.
100
+ assert represent(CZGate.decompose(), nqubits=2) == CZGate_matrix
101
+
102
+ CPhaseGate = CGate(0, PhaseGate(1))
103
+ assert qapply(CPhaseGate*Qubit('11')) == \
104
+ I*Qubit('11')
105
+ assert matrix_to_qubit(represent(CPhaseGate*Qubit('11'), nqubits=2)) == \
106
+ I*Qubit('11')
107
+
108
+ # Test that the dagger, inverse, and power of CGate is evaluated properly
109
+ assert Dagger(CZGate) == CZGate
110
+ assert pow(CZGate, 1) == Dagger(CZGate)
111
+ assert Dagger(CZGate) == CZGate.inverse()
112
+ assert Dagger(CPhaseGate) != CPhaseGate
113
+ assert Dagger(CPhaseGate) == CPhaseGate.inverse()
114
+ assert Dagger(CPhaseGate) == pow(CPhaseGate, -1)
115
+ assert pow(CPhaseGate, -1) == CPhaseGate.inverse()
116
+
117
+
118
+ def test_UGate_CGate_combo():
119
+ a, b, c, d = symbols('a,b,c,d')
120
+ uMat = Matrix([[a, b], [c, d]])
121
+ cMat = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, c, d]])
122
+
123
+ # Test basic case where gate exists in 1-qubit space.
124
+ u1 = UGate((0,), uMat)
125
+ cu1 = CGate(1, u1)
126
+ assert represent(cu1, nqubits=2) == cMat
127
+ assert qapply(cu1*Qubit('10')) == a*Qubit('10') + c*Qubit('11')
128
+ assert qapply(cu1*Qubit('11')) == b*Qubit('10') + d*Qubit('11')
129
+ assert qapply(cu1*Qubit('01')) == Qubit('01')
130
+ assert qapply(cu1*Qubit('00')) == Qubit('00')
131
+
132
+ # Test case where gate exists in a larger space.
133
+ u2 = UGate((1,), uMat)
134
+ u2Rep = represent(u2, nqubits=2)
135
+ for i in range(4):
136
+ assert u2Rep*qubit_to_matrix(IntQubit(i, 2)) == \
137
+ qubit_to_matrix(qapply(u2*IntQubit(i, 2)))
138
+
139
+ def test_UGate_OneQubitGate_combo():
140
+ v, w, f, g = symbols('v w f g')
141
+ uMat1 = ImmutableMatrix([[v, w], [f, g]])
142
+ cMat1 = Matrix([[v, w + 1, 0, 0], [f + 1, g, 0, 0], [0, 0, v, w + 1], [0, 0, f + 1, g]])
143
+ u1 = X(0) + UGate(0, uMat1)
144
+ assert represent(u1, nqubits=2) == cMat1
145
+
146
+ uMat2 = ImmutableMatrix([[1/sqrt(2), 1/sqrt(2)], [I/sqrt(2), -I/sqrt(2)]])
147
+ cMat2_1 = Matrix([[Rational(1, 2) + I/2, Rational(1, 2) - I/2],
148
+ [Rational(1, 2) - I/2, Rational(1, 2) + I/2]])
149
+ cMat2_2 = Matrix([[1, 0], [0, I]])
150
+ u2 = UGate(0, uMat2)
151
+ assert represent(H(0)*u2, nqubits=1) == cMat2_1
152
+ assert represent(u2*H(0), nqubits=1) == cMat2_2
153
+
154
+ def test_represent_hadamard():
155
+ """Test the representation of the hadamard gate."""
156
+ circuit = HadamardGate(0)*Qubit('00')
157
+ answer = represent(circuit, nqubits=2)
158
+ # Check that the answers are same to within an epsilon.
159
+ assert answer == Matrix([sqrt2_inv, sqrt2_inv, 0, 0])
160
+
161
+
162
+ def test_represent_xgate():
163
+ """Test the representation of the X gate."""
164
+ circuit = XGate(0)*Qubit('00')
165
+ answer = represent(circuit, nqubits=2)
166
+ assert Matrix([0, 1, 0, 0]) == answer
167
+
168
+
169
+ def test_represent_ygate():
170
+ """Test the representation of the Y gate."""
171
+ circuit = YGate(0)*Qubit('00')
172
+ answer = represent(circuit, nqubits=2)
173
+ assert answer[0] == 0 and answer[1] == I and \
174
+ answer[2] == 0 and answer[3] == 0
175
+
176
+
177
+ def test_represent_zgate():
178
+ """Test the representation of the Z gate."""
179
+ circuit = ZGate(0)*Qubit('00')
180
+ answer = represent(circuit, nqubits=2)
181
+ assert Matrix([1, 0, 0, 0]) == answer
182
+
183
+
184
+ def test_represent_phasegate():
185
+ """Test the representation of the S gate."""
186
+ circuit = PhaseGate(0)*Qubit('01')
187
+ answer = represent(circuit, nqubits=2)
188
+ assert Matrix([0, I, 0, 0]) == answer
189
+
190
+
191
+ def test_represent_tgate():
192
+ """Test the representation of the T gate."""
193
+ circuit = TGate(0)*Qubit('01')
194
+ assert Matrix([0, exp(I*pi/4), 0, 0]) == represent(circuit, nqubits=2)
195
+
196
+
197
+ def test_compound_gates():
198
+ """Test a compound gate representation."""
199
+ circuit = YGate(0)*ZGate(0)*XGate(0)*HadamardGate(0)*Qubit('00')
200
+ answer = represent(circuit, nqubits=2)
201
+ assert Matrix([I/sqrt(2), I/sqrt(2), 0, 0]) == answer
202
+
203
+
204
+ def test_cnot_gate():
205
+ """Test the CNOT gate."""
206
+ circuit = CNotGate(1, 0)
207
+ assert represent(circuit, nqubits=2) == \
208
+ Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
209
+ circuit = circuit*Qubit('111')
210
+ assert matrix_to_qubit(represent(circuit, nqubits=3)) == \
211
+ qapply(circuit)
212
+
213
+ circuit = CNotGate(1, 0)
214
+ assert Dagger(circuit) == circuit
215
+ assert Dagger(Dagger(circuit)) == circuit
216
+ assert circuit*circuit == 1
217
+
218
+
219
+ def test_gate_sort():
220
+ """Test gate_sort."""
221
+ for g in (X, Y, Z, H, S, T):
222
+ assert gate_sort(g(2)*g(1)*g(0)) == g(0)*g(1)*g(2)
223
+ e = gate_sort(X(1)*H(0)**2*CNOT(0, 1)*X(1)*X(0))
224
+ assert e == H(0)**2*CNOT(0, 1)*X(0)*X(1)**2
225
+ assert gate_sort(Z(0)*X(0)) == -X(0)*Z(0)
226
+ assert gate_sort(Z(0)*X(0)**2) == X(0)**2*Z(0)
227
+ assert gate_sort(Y(0)*H(0)) == -H(0)*Y(0)
228
+ assert gate_sort(Y(0)*X(0)) == -X(0)*Y(0)
229
+ assert gate_sort(Z(0)*Y(0)) == -Y(0)*Z(0)
230
+ assert gate_sort(T(0)*S(0)) == S(0)*T(0)
231
+ assert gate_sort(Z(0)*S(0)) == S(0)*Z(0)
232
+ assert gate_sort(Z(0)*T(0)) == T(0)*Z(0)
233
+ assert gate_sort(Z(0)*CNOT(0, 1)) == CNOT(0, 1)*Z(0)
234
+ assert gate_sort(S(0)*CNOT(0, 1)) == CNOT(0, 1)*S(0)
235
+ assert gate_sort(T(0)*CNOT(0, 1)) == CNOT(0, 1)*T(0)
236
+ assert gate_sort(X(1)*CNOT(0, 1)) == CNOT(0, 1)*X(1)
237
+ # This takes a long time and should only be uncommented once in a while.
238
+ # nqubits = 5
239
+ # ngates = 10
240
+ # trials = 10
241
+ # for i in range(trials):
242
+ # c = random_circuit(ngates, nqubits)
243
+ # assert represent(c, nqubits=nqubits) == \
244
+ # represent(gate_sort(c), nqubits=nqubits)
245
+
246
+
247
+ def test_gate_simp():
248
+ """Test gate_simp."""
249
+ e = H(0)*X(1)*H(0)**2*CNOT(0, 1)*X(1)**3*X(0)*Z(3)**2*S(4)**3
250
+ assert gate_simp(e) == H(0)*CNOT(0, 1)*S(4)*X(0)*Z(4)
251
+ assert gate_simp(X(0)*X(0)) == 1
252
+ assert gate_simp(Y(0)*Y(0)) == 1
253
+ assert gate_simp(Z(0)*Z(0)) == 1
254
+ assert gate_simp(H(0)*H(0)) == 1
255
+ assert gate_simp(T(0)*T(0)) == S(0)
256
+ assert gate_simp(S(0)*S(0)) == Z(0)
257
+ assert gate_simp(Integer(1)) == Integer(1)
258
+ assert gate_simp(X(0)**2 + Y(0)**2) == Integer(2)
259
+
260
+
261
+ def test_swap_gate():
262
+ """Test the SWAP gate."""
263
+ swap_gate_matrix = Matrix(
264
+ ((1, 0, 0, 0), (0, 0, 1, 0), (0, 1, 0, 0), (0, 0, 0, 1)))
265
+ assert represent(SwapGate(1, 0).decompose(), nqubits=2) == swap_gate_matrix
266
+ assert qapply(SwapGate(1, 3)*Qubit('0010')) == Qubit('1000')
267
+ nqubits = 4
268
+ for i in range(nqubits):
269
+ for j in range(i):
270
+ assert represent(SwapGate(i, j), nqubits=nqubits) == \
271
+ represent(SwapGate(i, j).decompose(), nqubits=nqubits)
272
+
273
+
274
+ def test_one_qubit_commutators():
275
+ """Test single qubit gate commutation relations."""
276
+ for g1 in (IdentityGate, X, Y, Z, H, T, S):
277
+ for g2 in (IdentityGate, X, Y, Z, H, T, S):
278
+ e = Commutator(g1(0), g2(0))
279
+ a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
280
+ b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
281
+ assert a == b
282
+
283
+ e = Commutator(g1(0), g2(1))
284
+ assert e.doit() == 0
285
+
286
+
287
+ def test_one_qubit_anticommutators():
288
+ """Test single qubit gate anticommutation relations."""
289
+ for g1 in (IdentityGate, X, Y, Z, H):
290
+ for g2 in (IdentityGate, X, Y, Z, H):
291
+ e = AntiCommutator(g1(0), g2(0))
292
+ a = matrix_to_zero(represent(e, nqubits=1, format='sympy'))
293
+ b = matrix_to_zero(represent(e.doit(), nqubits=1, format='sympy'))
294
+ assert a == b
295
+ e = AntiCommutator(g1(0), g2(1))
296
+ a = matrix_to_zero(represent(e, nqubits=2, format='sympy'))
297
+ b = matrix_to_zero(represent(e.doit(), nqubits=2, format='sympy'))
298
+ assert a == b
299
+
300
+
301
+ def test_cnot_commutators():
302
+ """Test commutators of involving CNOT gates."""
303
+ assert Commutator(CNOT(0, 1), Z(0)).doit() == 0
304
+ assert Commutator(CNOT(0, 1), T(0)).doit() == 0
305
+ assert Commutator(CNOT(0, 1), S(0)).doit() == 0
306
+ assert Commutator(CNOT(0, 1), X(1)).doit() == 0
307
+ assert Commutator(CNOT(0, 1), CNOT(0, 1)).doit() == 0
308
+ assert Commutator(CNOT(0, 1), CNOT(0, 2)).doit() == 0
309
+ assert Commutator(CNOT(0, 2), CNOT(0, 1)).doit() == 0
310
+ assert Commutator(CNOT(1, 2), CNOT(1, 0)).doit() == 0
311
+
312
+
313
+ def test_random_circuit():
314
+ c = random_circuit(10, 3)
315
+ assert isinstance(c, Mul)
316
+ m = represent(c, nqubits=3)
317
+ assert m.shape == (8, 8)
318
+ assert isinstance(m, Matrix)
319
+
320
+
321
+ def test_hermitian_XGate():
322
+ x = XGate(1, 2)
323
+ x_dagger = Dagger(x)
324
+
325
+ assert (x == x_dagger)
326
+
327
+
328
+ def test_hermitian_YGate():
329
+ y = YGate(1, 2)
330
+ y_dagger = Dagger(y)
331
+
332
+ assert (y == y_dagger)
333
+
334
+
335
+ def test_hermitian_ZGate():
336
+ z = ZGate(1, 2)
337
+ z_dagger = Dagger(z)
338
+
339
+ assert (z == z_dagger)
340
+
341
+
342
+ def test_unitary_XGate():
343
+ x = XGate(1, 2)
344
+ x_dagger = Dagger(x)
345
+
346
+ assert (x*x_dagger == 1)
347
+
348
+
349
+ def test_unitary_YGate():
350
+ y = YGate(1, 2)
351
+ y_dagger = Dagger(y)
352
+
353
+ assert (y*y_dagger == 1)
354
+
355
+
356
+ def test_unitary_ZGate():
357
+ z = ZGate(1, 2)
358
+ z_dagger = Dagger(z)
359
+
360
+ assert (z*z_dagger == 1)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_hilbert.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.quantum.hilbert import (
2
+ HilbertSpace, ComplexSpace, L2, FockSpace, TensorProductHilbertSpace,
3
+ DirectSumHilbertSpace, TensorPowerHilbertSpace
4
+ )
5
+
6
+ from sympy.core.numbers import oo
7
+ from sympy.core.symbol import Symbol
8
+ from sympy.printing.repr import srepr
9
+ from sympy.printing.str import sstr
10
+ from sympy.sets.sets import Interval
11
+
12
+
13
+ def test_hilbert_space():
14
+ hs = HilbertSpace()
15
+ assert isinstance(hs, HilbertSpace)
16
+ assert sstr(hs) == 'H'
17
+ assert srepr(hs) == 'HilbertSpace()'
18
+
19
+
20
+ def test_complex_space():
21
+ c1 = ComplexSpace(2)
22
+ assert isinstance(c1, ComplexSpace)
23
+ assert c1.dimension == 2
24
+ assert sstr(c1) == 'C(2)'
25
+ assert srepr(c1) == 'ComplexSpace(Integer(2))'
26
+
27
+ n = Symbol('n')
28
+ c2 = ComplexSpace(n)
29
+ assert isinstance(c2, ComplexSpace)
30
+ assert c2.dimension == n
31
+ assert sstr(c2) == 'C(n)'
32
+ assert srepr(c2) == "ComplexSpace(Symbol('n'))"
33
+ assert c2.subs(n, 2) == ComplexSpace(2)
34
+
35
+
36
+ def test_L2():
37
+ b1 = L2(Interval(-oo, 1))
38
+ assert isinstance(b1, L2)
39
+ assert b1.dimension is oo
40
+ assert b1.interval == Interval(-oo, 1)
41
+
42
+ x = Symbol('x', real=True)
43
+ y = Symbol('y', real=True)
44
+ b2 = L2(Interval(x, y))
45
+ assert b2.dimension is oo
46
+ assert b2.interval == Interval(x, y)
47
+ assert b2.subs(x, -1) == L2(Interval(-1, y))
48
+
49
+
50
+ def test_fock_space():
51
+ f1 = FockSpace()
52
+ f2 = FockSpace()
53
+ assert isinstance(f1, FockSpace)
54
+ assert f1.dimension is oo
55
+ assert f1 == f2
56
+
57
+
58
+ def test_tensor_product():
59
+ n = Symbol('n')
60
+ hs1 = ComplexSpace(2)
61
+ hs2 = ComplexSpace(n)
62
+
63
+ h = hs1*hs2
64
+ assert isinstance(h, TensorProductHilbertSpace)
65
+ assert h.dimension == 2*n
66
+ assert h.spaces == (hs1, hs2)
67
+
68
+ h = hs2*hs2
69
+ assert isinstance(h, TensorPowerHilbertSpace)
70
+ assert h.base == hs2
71
+ assert h.exp == 2
72
+ assert h.dimension == n**2
73
+
74
+ f = FockSpace()
75
+ h = hs1*hs2*f
76
+ assert h.dimension is oo
77
+
78
+
79
+ def test_tensor_power():
80
+ n = Symbol('n')
81
+ hs1 = ComplexSpace(2)
82
+ hs2 = ComplexSpace(n)
83
+
84
+ h = hs1**2
85
+ assert isinstance(h, TensorPowerHilbertSpace)
86
+ assert h.base == hs1
87
+ assert h.exp == 2
88
+ assert h.dimension == 4
89
+
90
+ h = hs2**3
91
+ assert isinstance(h, TensorPowerHilbertSpace)
92
+ assert h.base == hs2
93
+ assert h.exp == 3
94
+ assert h.dimension == n**3
95
+
96
+
97
+ def test_direct_sum():
98
+ n = Symbol('n')
99
+ hs1 = ComplexSpace(2)
100
+ hs2 = ComplexSpace(n)
101
+
102
+ h = hs1 + hs2
103
+ assert isinstance(h, DirectSumHilbertSpace)
104
+ assert h.dimension == 2 + n
105
+ assert h.spaces == (hs1, hs2)
106
+
107
+ f = FockSpace()
108
+ h = hs1 + f + hs2
109
+ assert h.dimension is oo
110
+ assert h.spaces == (hs1, f, hs2)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_identitysearch.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.numbers import Integer
4
+ from sympy.physics.quantum.dagger import Dagger
5
+ from sympy.physics.quantum.gate import (X, Y, Z, H, CNOT,
6
+ IdentityGate, CGate, PhaseGate, TGate)
7
+ from sympy.physics.quantum.identitysearch import (generate_gate_rules,
8
+ generate_equivalent_ids, GateIdentity, bfs_identity_search,
9
+ is_scalar_sparse_matrix,
10
+ is_scalar_nonsparse_matrix, is_degenerate, is_reducible)
11
+ from sympy.testing.pytest import skip
12
+
13
+
14
+ def create_gate_sequence(qubit=0):
15
+ gates = (X(qubit), Y(qubit), Z(qubit), H(qubit))
16
+ return gates
17
+
18
+
19
+ def test_generate_gate_rules_1():
20
+ # Test with tuples
21
+ (x, y, z, h) = create_gate_sequence()
22
+ ph = PhaseGate(0)
23
+ cgate_t = CGate(0, TGate(1))
24
+
25
+ assert generate_gate_rules((x,)) == {((x,), ())}
26
+
27
+ gate_rules = {((x, x), ()),
28
+ ((x,), (x,))}
29
+ assert generate_gate_rules((x, x)) == gate_rules
30
+
31
+ gate_rules = {((x, y, x), ()),
32
+ ((y, x, x), ()),
33
+ ((x, x, y), ()),
34
+ ((y, x), (x,)),
35
+ ((x, y), (x,)),
36
+ ((y,), (x, x))}
37
+ assert generate_gate_rules((x, y, x)) == gate_rules
38
+
39
+ gate_rules = {((x, y, z), ()), ((y, z, x), ()), ((z, x, y), ()),
40
+ ((), (x, z, y)), ((), (y, x, z)), ((), (z, y, x)),
41
+ ((x,), (z, y)), ((y, z), (x,)), ((y,), (x, z)),
42
+ ((z, x), (y,)), ((z,), (y, x)), ((x, y), (z,))}
43
+ actual = generate_gate_rules((x, y, z))
44
+ assert actual == gate_rules
45
+
46
+ gate_rules = {
47
+ ((), (h, z, y, x)), ((), (x, h, z, y)), ((), (y, x, h, z)),
48
+ ((), (z, y, x, h)), ((h,), (z, y, x)), ((x,), (h, z, y)),
49
+ ((y,), (x, h, z)), ((z,), (y, x, h)), ((h, x), (z, y)),
50
+ ((x, y), (h, z)), ((y, z), (x, h)), ((z, h), (y, x)),
51
+ ((h, x, y), (z,)), ((x, y, z), (h,)), ((y, z, h), (x,)),
52
+ ((z, h, x), (y,)), ((h, x, y, z), ()), ((x, y, z, h), ()),
53
+ ((y, z, h, x), ()), ((z, h, x, y), ())}
54
+ actual = generate_gate_rules((x, y, z, h))
55
+ assert actual == gate_rules
56
+
57
+ gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
58
+ ((), (ph**(-1), x, cgate_t**(-1))),
59
+ ((), (x, cgate_t**(-1), ph**(-1))),
60
+ ((cgate_t,), (ph**(-1), x)),
61
+ ((ph,), (x, cgate_t**(-1))),
62
+ ((x,), (cgate_t**(-1), ph**(-1))),
63
+ ((cgate_t, x), (ph**(-1),)),
64
+ ((ph, cgate_t), (x,)),
65
+ ((x, ph), (cgate_t**(-1),)),
66
+ ((cgate_t, x, ph), ()),
67
+ ((ph, cgate_t, x), ()),
68
+ ((x, ph, cgate_t), ())}
69
+ actual = generate_gate_rules((x, ph, cgate_t))
70
+ assert actual == gate_rules
71
+
72
+ gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
73
+ (Integer(1), ph**(-1)*x*cgate_t**(-1)),
74
+ (Integer(1), x*cgate_t**(-1)*ph**(-1)),
75
+ (cgate_t, ph**(-1)*x),
76
+ (ph, x*cgate_t**(-1)),
77
+ (x, cgate_t**(-1)*ph**(-1)),
78
+ (cgate_t*x, ph**(-1)),
79
+ (ph*cgate_t, x),
80
+ (x*ph, cgate_t**(-1)),
81
+ (cgate_t*x*ph, Integer(1)),
82
+ (ph*cgate_t*x, Integer(1)),
83
+ (x*ph*cgate_t, Integer(1))}
84
+ actual = generate_gate_rules((x, ph, cgate_t), return_as_muls=True)
85
+ assert actual == gate_rules
86
+
87
+
88
+ def test_generate_gate_rules_2():
89
+ # Test with Muls
90
+ (x, y, z, h) = create_gate_sequence()
91
+ ph = PhaseGate(0)
92
+ cgate_t = CGate(0, TGate(1))
93
+
94
+ # Note: 1 (type int) is not the same as 1 (type One)
95
+ expected = {(x, Integer(1))}
96
+ assert generate_gate_rules((x,), return_as_muls=True) == expected
97
+
98
+ expected = {(Integer(1), Integer(1))}
99
+ assert generate_gate_rules(x*x, return_as_muls=True) == expected
100
+
101
+ expected = {((), ())}
102
+ assert generate_gate_rules(x*x, return_as_muls=False) == expected
103
+
104
+ gate_rules = {(x*y*x, Integer(1)),
105
+ (y, Integer(1)),
106
+ (y*x, x),
107
+ (x*y, x)}
108
+ assert generate_gate_rules(x*y*x, return_as_muls=True) == gate_rules
109
+
110
+ gate_rules = {(x*y*z, Integer(1)),
111
+ (y*z*x, Integer(1)),
112
+ (z*x*y, Integer(1)),
113
+ (Integer(1), x*z*y),
114
+ (Integer(1), y*x*z),
115
+ (Integer(1), z*y*x),
116
+ (x, z*y),
117
+ (y*z, x),
118
+ (y, x*z),
119
+ (z*x, y),
120
+ (z, y*x),
121
+ (x*y, z)}
122
+ actual = generate_gate_rules(x*y*z, return_as_muls=True)
123
+ assert actual == gate_rules
124
+
125
+ gate_rules = {(Integer(1), h*z*y*x),
126
+ (Integer(1), x*h*z*y),
127
+ (Integer(1), y*x*h*z),
128
+ (Integer(1), z*y*x*h),
129
+ (h, z*y*x), (x, h*z*y),
130
+ (y, x*h*z), (z, y*x*h),
131
+ (h*x, z*y), (z*h, y*x),
132
+ (x*y, h*z), (y*z, x*h),
133
+ (h*x*y, z), (x*y*z, h),
134
+ (y*z*h, x), (z*h*x, y),
135
+ (h*x*y*z, Integer(1)),
136
+ (x*y*z*h, Integer(1)),
137
+ (y*z*h*x, Integer(1)),
138
+ (z*h*x*y, Integer(1))}
139
+ actual = generate_gate_rules(x*y*z*h, return_as_muls=True)
140
+ assert actual == gate_rules
141
+
142
+ gate_rules = {(Integer(1), cgate_t**(-1)*ph**(-1)*x),
143
+ (Integer(1), ph**(-1)*x*cgate_t**(-1)),
144
+ (Integer(1), x*cgate_t**(-1)*ph**(-1)),
145
+ (cgate_t, ph**(-1)*x),
146
+ (ph, x*cgate_t**(-1)),
147
+ (x, cgate_t**(-1)*ph**(-1)),
148
+ (cgate_t*x, ph**(-1)),
149
+ (ph*cgate_t, x),
150
+ (x*ph, cgate_t**(-1)),
151
+ (cgate_t*x*ph, Integer(1)),
152
+ (ph*cgate_t*x, Integer(1)),
153
+ (x*ph*cgate_t, Integer(1))}
154
+ actual = generate_gate_rules(x*ph*cgate_t, return_as_muls=True)
155
+ assert actual == gate_rules
156
+
157
+ gate_rules = {((), (cgate_t**(-1), ph**(-1), x)),
158
+ ((), (ph**(-1), x, cgate_t**(-1))),
159
+ ((), (x, cgate_t**(-1), ph**(-1))),
160
+ ((cgate_t,), (ph**(-1), x)),
161
+ ((ph,), (x, cgate_t**(-1))),
162
+ ((x,), (cgate_t**(-1), ph**(-1))),
163
+ ((cgate_t, x), (ph**(-1),)),
164
+ ((ph, cgate_t), (x,)),
165
+ ((x, ph), (cgate_t**(-1),)),
166
+ ((cgate_t, x, ph), ()),
167
+ ((ph, cgate_t, x), ()),
168
+ ((x, ph, cgate_t), ())}
169
+ actual = generate_gate_rules(x*ph*cgate_t)
170
+ assert actual == gate_rules
171
+
172
+
173
+ def test_generate_equivalent_ids_1():
174
+ # Test with tuples
175
+ (x, y, z, h) = create_gate_sequence()
176
+
177
+ assert generate_equivalent_ids((x,)) == {(x,)}
178
+ assert generate_equivalent_ids((x, x)) == {(x, x)}
179
+ assert generate_equivalent_ids((x, y)) == {(x, y), (y, x)}
180
+
181
+ gate_seq = (x, y, z)
182
+ gate_ids = {(x, y, z), (y, z, x), (z, x, y), (z, y, x),
183
+ (y, x, z), (x, z, y)}
184
+ assert generate_equivalent_ids(gate_seq) == gate_ids
185
+
186
+ gate_ids = {Mul(x, y, z), Mul(y, z, x), Mul(z, x, y),
187
+ Mul(z, y, x), Mul(y, x, z), Mul(x, z, y)}
188
+ assert generate_equivalent_ids(gate_seq, return_as_muls=True) == gate_ids
189
+
190
+ gate_seq = (x, y, z, h)
191
+ gate_ids = {(x, y, z, h), (y, z, h, x),
192
+ (h, x, y, z), (h, z, y, x),
193
+ (z, y, x, h), (y, x, h, z),
194
+ (z, h, x, y), (x, h, z, y)}
195
+ assert generate_equivalent_ids(gate_seq) == gate_ids
196
+
197
+ gate_seq = (x, y, x, y)
198
+ gate_ids = {(x, y, x, y), (y, x, y, x)}
199
+ assert generate_equivalent_ids(gate_seq) == gate_ids
200
+
201
+ cgate_y = CGate((1,), y)
202
+ gate_seq = (y, cgate_y, y, cgate_y)
203
+ gate_ids = {(y, cgate_y, y, cgate_y), (cgate_y, y, cgate_y, y)}
204
+ assert generate_equivalent_ids(gate_seq) == gate_ids
205
+
206
+ cnot = CNOT(1, 0)
207
+ cgate_z = CGate((0,), Z(1))
208
+ gate_seq = (cnot, h, cgate_z, h)
209
+ gate_ids = {(cnot, h, cgate_z, h), (h, cgate_z, h, cnot),
210
+ (h, cnot, h, cgate_z), (cgate_z, h, cnot, h)}
211
+ assert generate_equivalent_ids(gate_seq) == gate_ids
212
+
213
+
214
+ def test_generate_equivalent_ids_2():
215
+ # Test with Muls
216
+ (x, y, z, h) = create_gate_sequence()
217
+
218
+ assert generate_equivalent_ids((x,), return_as_muls=True) == {x}
219
+
220
+ gate_ids = {Integer(1)}
221
+ assert generate_equivalent_ids(x*x, return_as_muls=True) == gate_ids
222
+
223
+ gate_ids = {x*y, y*x}
224
+ assert generate_equivalent_ids(x*y, return_as_muls=True) == gate_ids
225
+
226
+ gate_ids = {(x, y), (y, x)}
227
+ assert generate_equivalent_ids(x*y) == gate_ids
228
+
229
+ circuit = Mul(*(x, y, z))
230
+ gate_ids = {x*y*z, y*z*x, z*x*y, z*y*x,
231
+ y*x*z, x*z*y}
232
+ assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
233
+
234
+ circuit = Mul(*(x, y, z, h))
235
+ gate_ids = {x*y*z*h, y*z*h*x,
236
+ h*x*y*z, h*z*y*x,
237
+ z*y*x*h, y*x*h*z,
238
+ z*h*x*y, x*h*z*y}
239
+ assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
240
+
241
+ circuit = Mul(*(x, y, x, y))
242
+ gate_ids = {x*y*x*y, y*x*y*x}
243
+ assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
244
+
245
+ cgate_y = CGate((1,), y)
246
+ circuit = Mul(*(y, cgate_y, y, cgate_y))
247
+ gate_ids = {y*cgate_y*y*cgate_y, cgate_y*y*cgate_y*y}
248
+ assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
249
+
250
+ cnot = CNOT(1, 0)
251
+ cgate_z = CGate((0,), Z(1))
252
+ circuit = Mul(*(cnot, h, cgate_z, h))
253
+ gate_ids = {cnot*h*cgate_z*h, h*cgate_z*h*cnot,
254
+ h*cnot*h*cgate_z, cgate_z*h*cnot*h}
255
+ assert generate_equivalent_ids(circuit, return_as_muls=True) == gate_ids
256
+
257
+
258
+ def test_is_scalar_nonsparse_matrix():
259
+ numqubits = 2
260
+ id_only = False
261
+
262
+ id_gate = (IdentityGate(1),)
263
+ actual = is_scalar_nonsparse_matrix(id_gate, numqubits, id_only)
264
+ assert actual is True
265
+
266
+ x0 = X(0)
267
+ xx_circuit = (x0, x0)
268
+ actual = is_scalar_nonsparse_matrix(xx_circuit, numqubits, id_only)
269
+ assert actual is True
270
+
271
+ x1 = X(1)
272
+ y1 = Y(1)
273
+ xy_circuit = (x1, y1)
274
+ actual = is_scalar_nonsparse_matrix(xy_circuit, numqubits, id_only)
275
+ assert actual is False
276
+
277
+ z1 = Z(1)
278
+ xyz_circuit = (x1, y1, z1)
279
+ actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
280
+ assert actual is True
281
+
282
+ cnot = CNOT(1, 0)
283
+ cnot_circuit = (cnot, cnot)
284
+ actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
285
+ assert actual is True
286
+
287
+ h = H(0)
288
+ hh_circuit = (h, h)
289
+ actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
290
+ assert actual is True
291
+
292
+ h1 = H(1)
293
+ xhzh_circuit = (x1, h1, z1, h1)
294
+ actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
295
+ assert actual is True
296
+
297
+ id_only = True
298
+ actual = is_scalar_nonsparse_matrix(xhzh_circuit, numqubits, id_only)
299
+ assert actual is True
300
+ actual = is_scalar_nonsparse_matrix(xyz_circuit, numqubits, id_only)
301
+ assert actual is False
302
+ actual = is_scalar_nonsparse_matrix(cnot_circuit, numqubits, id_only)
303
+ assert actual is True
304
+ actual = is_scalar_nonsparse_matrix(hh_circuit, numqubits, id_only)
305
+ assert actual is True
306
+
307
+
308
+ def test_is_scalar_sparse_matrix():
309
+ np = import_module('numpy')
310
+ if not np:
311
+ skip("numpy not installed.")
312
+
313
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
314
+ if not scipy:
315
+ skip("scipy not installed.")
316
+
317
+ numqubits = 2
318
+ id_only = False
319
+
320
+ id_gate = (IdentityGate(1),)
321
+ assert is_scalar_sparse_matrix(id_gate, numqubits, id_only) is True
322
+
323
+ x0 = X(0)
324
+ xx_circuit = (x0, x0)
325
+ assert is_scalar_sparse_matrix(xx_circuit, numqubits, id_only) is True
326
+
327
+ x1 = X(1)
328
+ y1 = Y(1)
329
+ xy_circuit = (x1, y1)
330
+ assert is_scalar_sparse_matrix(xy_circuit, numqubits, id_only) is False
331
+
332
+ z1 = Z(1)
333
+ xyz_circuit = (x1, y1, z1)
334
+ assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is True
335
+
336
+ cnot = CNOT(1, 0)
337
+ cnot_circuit = (cnot, cnot)
338
+ assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
339
+
340
+ h = H(0)
341
+ hh_circuit = (h, h)
342
+ assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
343
+
344
+ # NOTE:
345
+ # The elements of the sparse matrix for the following circuit
346
+ # is actually 1.0000000000000002+0.0j.
347
+ h1 = H(1)
348
+ xhzh_circuit = (x1, h1, z1, h1)
349
+ assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
350
+
351
+ id_only = True
352
+ assert is_scalar_sparse_matrix(xhzh_circuit, numqubits, id_only) is True
353
+ assert is_scalar_sparse_matrix(xyz_circuit, numqubits, id_only) is False
354
+ assert is_scalar_sparse_matrix(cnot_circuit, numqubits, id_only) is True
355
+ assert is_scalar_sparse_matrix(hh_circuit, numqubits, id_only) is True
356
+
357
+
358
+ def test_is_degenerate():
359
+ (x, y, z, h) = create_gate_sequence()
360
+
361
+ gate_id = GateIdentity(x, y, z)
362
+ ids = {gate_id}
363
+
364
+ another_id = (z, y, x)
365
+ assert is_degenerate(ids, another_id) is True
366
+
367
+
368
+ def test_is_reducible():
369
+ nqubits = 2
370
+ (x, y, z, h) = create_gate_sequence()
371
+
372
+ circuit = (x, y, y)
373
+ assert is_reducible(circuit, nqubits, 1, 3) is True
374
+
375
+ circuit = (x, y, x)
376
+ assert is_reducible(circuit, nqubits, 1, 3) is False
377
+
378
+ circuit = (x, y, y, x)
379
+ assert is_reducible(circuit, nqubits, 0, 4) is True
380
+
381
+ circuit = (x, y, y, x)
382
+ assert is_reducible(circuit, nqubits, 1, 3) is True
383
+
384
+ circuit = (x, y, z, y, y)
385
+ assert is_reducible(circuit, nqubits, 1, 5) is True
386
+
387
+
388
+ def test_bfs_identity_search():
389
+ assert bfs_identity_search([], 1) == set()
390
+
391
+ (x, y, z, h) = create_gate_sequence()
392
+
393
+ gate_list = [x]
394
+ id_set = {GateIdentity(x, x)}
395
+ assert bfs_identity_search(gate_list, 1, max_depth=2) == id_set
396
+
397
+ # Set should not contain degenerate quantum circuits
398
+ gate_list = [x, y, z]
399
+ id_set = {GateIdentity(x, x),
400
+ GateIdentity(y, y),
401
+ GateIdentity(z, z),
402
+ GateIdentity(x, y, z)}
403
+ assert bfs_identity_search(gate_list, 1) == id_set
404
+
405
+ id_set = {GateIdentity(x, x),
406
+ GateIdentity(y, y),
407
+ GateIdentity(z, z),
408
+ GateIdentity(x, y, z),
409
+ GateIdentity(x, y, x, y),
410
+ GateIdentity(x, z, x, z),
411
+ GateIdentity(y, z, y, z)}
412
+ assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
413
+ assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
414
+
415
+ gate_list = [x, y, z, h]
416
+ id_set = {GateIdentity(x, x),
417
+ GateIdentity(y, y),
418
+ GateIdentity(z, z),
419
+ GateIdentity(h, h),
420
+ GateIdentity(x, y, z),
421
+ GateIdentity(x, y, x, y),
422
+ GateIdentity(x, z, x, z),
423
+ GateIdentity(x, h, z, h),
424
+ GateIdentity(y, z, y, z),
425
+ GateIdentity(y, h, y, h)}
426
+ assert bfs_identity_search(gate_list, 1) == id_set
427
+
428
+ id_set = {GateIdentity(x, x),
429
+ GateIdentity(y, y),
430
+ GateIdentity(z, z),
431
+ GateIdentity(h, h)}
432
+ assert id_set == bfs_identity_search(gate_list, 1, max_depth=3,
433
+ identity_only=True)
434
+
435
+ id_set = {GateIdentity(x, x),
436
+ GateIdentity(y, y),
437
+ GateIdentity(z, z),
438
+ GateIdentity(h, h),
439
+ GateIdentity(x, y, z),
440
+ GateIdentity(x, y, x, y),
441
+ GateIdentity(x, z, x, z),
442
+ GateIdentity(x, h, z, h),
443
+ GateIdentity(y, z, y, z),
444
+ GateIdentity(y, h, y, h),
445
+ GateIdentity(x, y, h, x, h),
446
+ GateIdentity(x, z, h, y, h),
447
+ GateIdentity(y, z, h, z, h)}
448
+ assert bfs_identity_search(gate_list, 1, max_depth=5) == id_set
449
+
450
+ id_set = {GateIdentity(x, x),
451
+ GateIdentity(y, y),
452
+ GateIdentity(z, z),
453
+ GateIdentity(h, h),
454
+ GateIdentity(x, h, z, h)}
455
+ assert id_set == bfs_identity_search(gate_list, 1, max_depth=4,
456
+ identity_only=True)
457
+
458
+ cnot = CNOT(1, 0)
459
+ gate_list = [x, cnot]
460
+ id_set = {GateIdentity(x, x),
461
+ GateIdentity(cnot, cnot),
462
+ GateIdentity(x, cnot, x, cnot)}
463
+ assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
464
+
465
+ cgate_x = CGate((1,), x)
466
+ gate_list = [x, cgate_x]
467
+ id_set = {GateIdentity(x, x),
468
+ GateIdentity(cgate_x, cgate_x),
469
+ GateIdentity(x, cgate_x, x, cgate_x)}
470
+ assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
471
+
472
+ cgate_z = CGate((0,), Z(1))
473
+ gate_list = [cnot, cgate_z, h]
474
+ id_set = {GateIdentity(h, h),
475
+ GateIdentity(cgate_z, cgate_z),
476
+ GateIdentity(cnot, cnot),
477
+ GateIdentity(cnot, h, cgate_z, h)}
478
+ assert bfs_identity_search(gate_list, 2, max_depth=4) == id_set
479
+
480
+ s = PhaseGate(0)
481
+ t = TGate(0)
482
+ gate_list = [s, t]
483
+ id_set = {GateIdentity(s, s, s, s)}
484
+ assert bfs_identity_search(gate_list, 1, max_depth=4) == id_set
485
+
486
+
487
+ def test_bfs_identity_search_xfail():
488
+ s = PhaseGate(0)
489
+ t = TGate(0)
490
+ gate_list = [Dagger(s), t]
491
+ id_set = {GateIdentity(Dagger(s), t, t)}
492
+ assert bfs_identity_search(gate_list, 1, max_depth=3) == id_set
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_innerproduct.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Integer)
2
+
3
+ from sympy.physics.quantum.innerproduct import InnerProduct
4
+ from sympy.physics.quantum.dagger import Dagger
5
+ from sympy.physics.quantum.state import Bra, Ket, StateBase
6
+
7
+
8
+ def test_innerproduct():
9
+ k = Ket('k')
10
+ b = Bra('b')
11
+ ip = InnerProduct(b, k)
12
+ assert isinstance(ip, InnerProduct)
13
+ assert ip.bra == b
14
+ assert ip.ket == k
15
+ assert b*k == InnerProduct(b, k)
16
+ assert k*(b*k)*b == k*InnerProduct(b, k)*b
17
+ assert InnerProduct(b, k).subs(b, Dagger(k)) == Dagger(k)*k
18
+
19
+
20
+ def test_innerproduct_dagger():
21
+ k = Ket('k')
22
+ b = Bra('b')
23
+ ip = b*k
24
+ assert Dagger(ip) == Dagger(k)*Dagger(b)
25
+
26
+
27
+ class FooState(StateBase):
28
+ pass
29
+
30
+
31
+ class FooKet(Ket, FooState):
32
+
33
+ @classmethod
34
+ def dual_class(self):
35
+ return FooBra
36
+
37
+ def _eval_innerproduct_FooBra(self, bra):
38
+ return Integer(1)
39
+
40
+ def _eval_innerproduct_BarBra(self, bra):
41
+ return I
42
+
43
+
44
+ class FooBra(Bra, FooState):
45
+ @classmethod
46
+ def dual_class(self):
47
+ return FooKet
48
+
49
+
50
+ class BarState(StateBase):
51
+ pass
52
+
53
+
54
+ class BarKet(Ket, BarState):
55
+ @classmethod
56
+ def dual_class(self):
57
+ return BarBra
58
+
59
+
60
+ class BarBra(Bra, BarState):
61
+ @classmethod
62
+ def dual_class(self):
63
+ return BarKet
64
+
65
+
66
+ def test_doit():
67
+ f = FooKet('foo')
68
+ b = BarBra('bar')
69
+ assert InnerProduct(b, f).doit() == I
70
+ assert InnerProduct(Dagger(f), Dagger(b)).doit() == -I
71
+ assert InnerProduct(Dagger(f), f).doit() == Integer(1)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_piab.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for piab.py"""
2
+
3
+ from sympy.core.numbers import pi
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.sets.sets import Interval
9
+ from sympy.functions.special.tensor_functions import KroneckerDelta
10
+ from sympy.physics.quantum import L2, qapply, hbar, represent
11
+ from sympy.physics.quantum.piab import PIABHamiltonian, PIABKet, PIABBra, m, L
12
+
13
+ i, j, n, x = symbols('i j n x')
14
+
15
+
16
+ def test_H():
17
+ assert PIABHamiltonian('H').hilbert_space == \
18
+ L2(Interval(S.NegativeInfinity, S.Infinity))
19
+ assert qapply(PIABHamiltonian('H')*PIABKet(n)) == \
20
+ (n**2*pi**2*hbar**2)/(2*m*L**2)*PIABKet(n)
21
+
22
+
23
+ def test_states():
24
+ assert PIABKet(n).dual_class() == PIABBra
25
+ assert PIABKet(n).hilbert_space == \
26
+ L2(Interval(S.NegativeInfinity, S.Infinity))
27
+ assert represent(PIABKet(n)) == sqrt(2/L)*sin(n*pi*x/L)
28
+ assert (PIABBra(i)*PIABKet(j)).doit() == KroneckerDelta(i, j)
29
+ assert PIABBra(n).dual_class() == PIABKet
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_qft.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi)
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.functions.elementary.exponential import exp
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.matrices.dense import Matrix
6
+
7
+ from sympy.physics.quantum.qft import QFT, IQFT, RkGate
8
+ from sympy.physics.quantum.gate import (ZGate, SwapGate, HadamardGate, CGate,
9
+ PhaseGate, TGate)
10
+ from sympy.physics.quantum.qubit import Qubit
11
+ from sympy.physics.quantum.qapply import qapply
12
+ from sympy.physics.quantum.represent import represent
13
+
14
+ from sympy.functions.elementary.complexes import sign
15
+
16
+
17
+ def test_RkGate():
18
+ x = Symbol('x')
19
+ assert RkGate(1, x).k == x
20
+ assert RkGate(1, x).targets == (1,)
21
+ assert RkGate(1, 1) == ZGate(1)
22
+ assert RkGate(2, 2) == PhaseGate(2)
23
+ assert RkGate(3, 3) == TGate(3)
24
+
25
+ assert represent(
26
+ RkGate(0, x), nqubits=1) == Matrix([[1, 0], [0, exp(sign(x)*2*pi*I/(2**abs(x)))]])
27
+
28
+
29
+ def test_quantum_fourier():
30
+ assert QFT(0, 3).decompose() == \
31
+ SwapGate(0, 2)*HadamardGate(0)*CGate((0,), PhaseGate(1)) * \
32
+ HadamardGate(1)*CGate((0,), TGate(2))*CGate((1,), PhaseGate(2)) * \
33
+ HadamardGate(2)
34
+
35
+ assert IQFT(0, 3).decompose() == \
36
+ HadamardGate(2)*CGate((1,), RkGate(2, -2))*CGate((0,), RkGate(2, -3)) * \
37
+ HadamardGate(1)*CGate((0,), RkGate(1, -2))*HadamardGate(0)*SwapGate(0, 2)
38
+
39
+ assert represent(QFT(0, 3), nqubits=3) == \
40
+ Matrix([[exp(2*pi*I/8)**(i*j % 8)/sqrt(8) for i in range(8)] for j in range(8)])
41
+
42
+ assert QFT(0, 4).decompose() # non-trivial decomposition
43
+ assert qapply(QFT(0, 3).decompose()*Qubit(0, 0, 0)).expand() == qapply(
44
+ HadamardGate(0)*HadamardGate(1)*HadamardGate(2)*Qubit(0, 0, 0)
45
+ ).expand()
46
+
47
+
48
+ def test_qft_represent():
49
+ c = QFT(0, 3)
50
+ a = represent(c, nqubits=3)
51
+ b = represent(c.decompose(), nqubits=3)
52
+ assert a.evalf(n=10) == b.evalf(n=10)
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Float, I, Integer)
2
+ from sympy.matrices.dense import Matrix
3
+ from sympy.external import import_module
4
+ from sympy.testing.pytest import skip
5
+
6
+ from sympy.physics.quantum.dagger import Dagger
7
+ from sympy.physics.quantum.represent import (represent, rep_innerproduct,
8
+ rep_expectation, enumerate_states)
9
+ from sympy.physics.quantum.state import Bra, Ket
10
+ from sympy.physics.quantum.operator import Operator, OuterProduct
11
+ from sympy.physics.quantum.tensorproduct import TensorProduct
12
+ from sympy.physics.quantum.tensorproduct import matrix_tensor_product
13
+ from sympy.physics.quantum.commutator import Commutator
14
+ from sympy.physics.quantum.anticommutator import AntiCommutator
15
+ from sympy.physics.quantum.innerproduct import InnerProduct
16
+ from sympy.physics.quantum.matrixutils import (numpy_ndarray,
17
+ scipy_sparse_matrix, to_numpy,
18
+ to_scipy_sparse, to_sympy)
19
+ from sympy.physics.quantum.cartesian import XKet, XOp, XBra
20
+ from sympy.physics.quantum.qapply import qapply
21
+ from sympy.physics.quantum.operatorset import operators_to_state
22
+ from sympy.testing.pytest import raises
23
+
24
+ Amat = Matrix([[1, I], [-I, 1]])
25
+ Bmat = Matrix([[1, 2], [3, 4]])
26
+ Avec = Matrix([[1], [I]])
27
+
28
+
29
+ class AKet(Ket):
30
+
31
+ @classmethod
32
+ def dual_class(self):
33
+ return ABra
34
+
35
+ def _represent_default_basis(self, **options):
36
+ return self._represent_AOp(None, **options)
37
+
38
+ def _represent_AOp(self, basis, **options):
39
+ return Avec
40
+
41
+
42
+ class ABra(Bra):
43
+
44
+ @classmethod
45
+ def dual_class(self):
46
+ return AKet
47
+
48
+
49
+ class AOp(Operator):
50
+
51
+ def _represent_default_basis(self, **options):
52
+ return self._represent_AOp(None, **options)
53
+
54
+ def _represent_AOp(self, basis, **options):
55
+ return Amat
56
+
57
+
58
+ class BOp(Operator):
59
+
60
+ def _represent_default_basis(self, **options):
61
+ return self._represent_AOp(None, **options)
62
+
63
+ def _represent_AOp(self, basis, **options):
64
+ return Bmat
65
+
66
+
67
+ k = AKet('a')
68
+ b = ABra('a')
69
+ A = AOp('A')
70
+ B = BOp('B')
71
+
72
+ _tests = [
73
+ # Bra
74
+ (b, Dagger(Avec)),
75
+ (Dagger(b), Avec),
76
+ # Ket
77
+ (k, Avec),
78
+ (Dagger(k), Dagger(Avec)),
79
+ # Operator
80
+ (A, Amat),
81
+ (Dagger(A), Dagger(Amat)),
82
+ # OuterProduct
83
+ (OuterProduct(k, b), Avec*Avec.H),
84
+ # TensorProduct
85
+ (TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)),
86
+ # Pow
87
+ (A**2, Amat**2),
88
+ # Add/Mul
89
+ (A*B + 2*A, Amat*Bmat + 2*Amat),
90
+ # Commutator
91
+ (Commutator(A, B), Amat*Bmat - Bmat*Amat),
92
+ # AntiCommutator
93
+ (AntiCommutator(A, B), Amat*Bmat + Bmat*Amat),
94
+ # InnerProduct
95
+ (InnerProduct(b, k), (Avec.H*Avec)[0])
96
+ ]
97
+
98
+
99
+ def test_format_sympy():
100
+ for test in _tests:
101
+ lhs = represent(test[0], basis=A, format='sympy')
102
+ rhs = to_sympy(test[1])
103
+ assert lhs == rhs
104
+
105
+
106
+ def test_scalar_sympy():
107
+ assert represent(Integer(1)) == Integer(1)
108
+ assert represent(Float(1.0)) == Float(1.0)
109
+ assert represent(1.0 + I) == 1.0 + I
110
+
111
+
112
+ np = import_module('numpy')
113
+
114
+
115
+ def test_format_numpy():
116
+ if not np:
117
+ skip("numpy not installed.")
118
+
119
+ for test in _tests:
120
+ lhs = represent(test[0], basis=A, format='numpy')
121
+ rhs = to_numpy(test[1])
122
+ if isinstance(lhs, numpy_ndarray):
123
+ assert (lhs == rhs).all()
124
+ else:
125
+ assert lhs == rhs
126
+
127
+
128
+ def test_scalar_numpy():
129
+ if not np:
130
+ skip("numpy not installed.")
131
+
132
+ assert represent(Integer(1), format='numpy') == 1
133
+ assert represent(Float(1.0), format='numpy') == 1.0
134
+ assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j
135
+
136
+
137
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
138
+
139
+
140
+ def test_format_scipy_sparse():
141
+ if not np:
142
+ skip("numpy not installed.")
143
+ if not scipy:
144
+ skip("scipy not installed.")
145
+
146
+ for test in _tests:
147
+ lhs = represent(test[0], basis=A, format='scipy.sparse')
148
+ rhs = to_scipy_sparse(test[1])
149
+ if isinstance(lhs, scipy_sparse_matrix):
150
+ assert np.linalg.norm((lhs - rhs).todense()) == 0.0
151
+ else:
152
+ assert lhs == rhs
153
+
154
+
155
+ def test_scalar_scipy_sparse():
156
+ if not np:
157
+ skip("numpy not installed.")
158
+ if not scipy:
159
+ skip("scipy not installed.")
160
+
161
+ assert represent(Integer(1), format='scipy.sparse') == 1
162
+ assert represent(Float(1.0), format='scipy.sparse') == 1.0
163
+ assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j
164
+
165
+ x_ket = XKet('x')
166
+ x_bra = XBra('x')
167
+ x_op = XOp('X')
168
+
169
+
170
+ def test_innerprod_represent():
171
+ assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit()
172
+ assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit()
173
+ raises(TypeError, lambda: rep_innerproduct(x_op))
174
+
175
+
176
+ def test_operator_represent():
177
+ basis_kets = enumerate_states(operators_to_state(x_op), 1, 2)
178
+ assert rep_expectation(
179
+ x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0])
180
+
181
+
182
+ def test_enumerate_states():
183
+ test = XKet("foo")
184
+ assert enumerate_states(test, 1, 1) == [XKet("foo_1")]
185
+ assert enumerate_states(
186
+ test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_state.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.function import diff
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.numbers import (I, Integer, Rational, oo, pi)
5
+ from sympy.core.power import Pow
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import (Symbol, symbols)
8
+ from sympy.core.sympify import sympify
9
+ from sympy.functions.elementary.complexes import conjugate
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.functions.elementary.trigonometric import sin
12
+ from sympy.testing.pytest import raises
13
+
14
+ from sympy.physics.quantum.dagger import Dagger
15
+ from sympy.physics.quantum.qexpr import QExpr
16
+ from sympy.physics.quantum.state import (
17
+ Ket, Bra, TimeDepKet, TimeDepBra,
18
+ KetBase, BraBase, StateBase, Wavefunction,
19
+ OrthogonalKet, OrthogonalBra
20
+ )
21
+ from sympy.physics.quantum.hilbert import HilbertSpace
22
+
23
+ x, y, t = symbols('x,y,t')
24
+
25
+
26
+ class CustomKet(Ket):
27
+ @classmethod
28
+ def default_args(self):
29
+ return ("test",)
30
+
31
+
32
+ class CustomKetMultipleLabels(Ket):
33
+ @classmethod
34
+ def default_args(self):
35
+ return ("r", "theta", "phi")
36
+
37
+
38
+ class CustomTimeDepKet(TimeDepKet):
39
+ @classmethod
40
+ def default_args(self):
41
+ return ("test", "t")
42
+
43
+
44
+ class CustomTimeDepKetMultipleLabels(TimeDepKet):
45
+ @classmethod
46
+ def default_args(self):
47
+ return ("r", "theta", "phi", "t")
48
+
49
+
50
+ def test_ket():
51
+ k = Ket('0')
52
+
53
+ assert isinstance(k, Ket)
54
+ assert isinstance(k, KetBase)
55
+ assert isinstance(k, StateBase)
56
+ assert isinstance(k, QExpr)
57
+
58
+ assert k.label == (Symbol('0'),)
59
+ assert k.hilbert_space == HilbertSpace()
60
+ assert k.is_commutative is False
61
+
62
+ # Make sure this doesn't get converted to the number pi.
63
+ k = Ket('pi')
64
+ assert k.label == (Symbol('pi'),)
65
+
66
+ k = Ket(x, y)
67
+ assert k.label == (x, y)
68
+ assert k.hilbert_space == HilbertSpace()
69
+ assert k.is_commutative is False
70
+
71
+ assert k.dual_class() == Bra
72
+ assert k.dual == Bra(x, y)
73
+ assert k.subs(x, y) == Ket(y, y)
74
+
75
+ k = CustomKet()
76
+ assert k == CustomKet("test")
77
+
78
+ k = CustomKetMultipleLabels()
79
+ assert k == CustomKetMultipleLabels("r", "theta", "phi")
80
+
81
+ assert Ket() == Ket('psi')
82
+
83
+
84
+ def test_bra():
85
+ b = Bra('0')
86
+
87
+ assert isinstance(b, Bra)
88
+ assert isinstance(b, BraBase)
89
+ assert isinstance(b, StateBase)
90
+ assert isinstance(b, QExpr)
91
+
92
+ assert b.label == (Symbol('0'),)
93
+ assert b.hilbert_space == HilbertSpace()
94
+ assert b.is_commutative is False
95
+
96
+ # Make sure this doesn't get converted to the number pi.
97
+ b = Bra('pi')
98
+ assert b.label == (Symbol('pi'),)
99
+
100
+ b = Bra(x, y)
101
+ assert b.label == (x, y)
102
+ assert b.hilbert_space == HilbertSpace()
103
+ assert b.is_commutative is False
104
+
105
+ assert b.dual_class() == Ket
106
+ assert b.dual == Ket(x, y)
107
+ assert b.subs(x, y) == Bra(y, y)
108
+
109
+ assert Bra() == Bra('psi')
110
+
111
+
112
+ def test_ops():
113
+ k0 = Ket(0)
114
+ k1 = Ket(1)
115
+ k = 2*I*k0 - (x/sqrt(2))*k1
116
+ assert k == Add(Mul(2, I, k0),
117
+ Mul(Rational(-1, 2), x, Pow(2, S.Half), k1))
118
+
119
+
120
+ def test_time_dep_ket():
121
+ k = TimeDepKet(0, t)
122
+
123
+ assert isinstance(k, TimeDepKet)
124
+ assert isinstance(k, KetBase)
125
+ assert isinstance(k, StateBase)
126
+ assert isinstance(k, QExpr)
127
+
128
+ assert k.label == (Integer(0),)
129
+ assert k.args == (Integer(0), t)
130
+ assert k.time == t
131
+
132
+ assert k.dual_class() == TimeDepBra
133
+ assert k.dual == TimeDepBra(0, t)
134
+
135
+ assert k.subs(t, 2) == TimeDepKet(0, 2)
136
+
137
+ k = TimeDepKet(x, 0.5)
138
+ assert k.label == (x,)
139
+ assert k.args == (x, sympify(0.5))
140
+
141
+ k = CustomTimeDepKet()
142
+ assert k.label == (Symbol("test"),)
143
+ assert k.time == Symbol("t")
144
+ assert k == CustomTimeDepKet("test", "t")
145
+
146
+ k = CustomTimeDepKetMultipleLabels()
147
+ assert k.label == (Symbol("r"), Symbol("theta"), Symbol("phi"))
148
+ assert k.time == Symbol("t")
149
+ assert k == CustomTimeDepKetMultipleLabels("r", "theta", "phi", "t")
150
+
151
+ assert TimeDepKet() == TimeDepKet("psi", "t")
152
+
153
+
154
+ def test_time_dep_bra():
155
+ b = TimeDepBra(0, t)
156
+
157
+ assert isinstance(b, TimeDepBra)
158
+ assert isinstance(b, BraBase)
159
+ assert isinstance(b, StateBase)
160
+ assert isinstance(b, QExpr)
161
+
162
+ assert b.label == (Integer(0),)
163
+ assert b.args == (Integer(0), t)
164
+ assert b.time == t
165
+
166
+ assert b.dual_class() == TimeDepKet
167
+ assert b.dual == TimeDepKet(0, t)
168
+
169
+ k = TimeDepBra(x, 0.5)
170
+ assert k.label == (x,)
171
+ assert k.args == (x, sympify(0.5))
172
+
173
+ assert TimeDepBra() == TimeDepBra("psi", "t")
174
+
175
+
176
+ def test_bra_ket_dagger():
177
+ x = symbols('x', complex=True)
178
+ k = Ket('k')
179
+ b = Bra('b')
180
+ assert Dagger(k) == Bra('k')
181
+ assert Dagger(b) == Ket('b')
182
+ assert Dagger(k).is_commutative is False
183
+
184
+ k2 = Ket('k2')
185
+ e = 2*I*k + x*k2
186
+ assert Dagger(e) == conjugate(x)*Dagger(k2) - 2*I*Dagger(k)
187
+
188
+
189
+ def test_wavefunction():
190
+ x, y = symbols('x y', real=True)
191
+ L = symbols('L', positive=True)
192
+ n = symbols('n', integer=True, positive=True)
193
+
194
+ f = Wavefunction(x**2, x)
195
+ p = f.prob()
196
+ lims = f.limits
197
+
198
+ assert f.is_normalized is False
199
+ assert f.norm is oo
200
+ assert f(10) == 100
201
+ assert p(10) == 10000
202
+ assert lims[x] == (-oo, oo)
203
+ assert diff(f, x) == Wavefunction(2*x, x)
204
+ raises(NotImplementedError, lambda: f.normalize())
205
+ assert conjugate(f) == Wavefunction(conjugate(f.expr), x)
206
+ assert conjugate(f) == Dagger(f)
207
+
208
+ g = Wavefunction(x**2*y + y**2*x, (x, 0, 1), (y, 0, 2))
209
+ lims_g = g.limits
210
+
211
+ assert lims_g[x] == (0, 1)
212
+ assert lims_g[y] == (0, 2)
213
+ assert g.is_normalized is False
214
+ assert g.norm == sqrt(42)/3
215
+ assert g(2, 4) == 0
216
+ assert g(1, 1) == 2
217
+ assert diff(diff(g, x), y) == Wavefunction(2*x + 2*y, (x, 0, 1), (y, 0, 2))
218
+ assert conjugate(g) == Wavefunction(conjugate(g.expr), *g.args[1:])
219
+ assert conjugate(g) == Dagger(g)
220
+
221
+ h = Wavefunction(sqrt(5)*x**2, (x, 0, 1))
222
+ assert h.is_normalized is True
223
+ assert h.normalize() == h
224
+ assert conjugate(h) == Wavefunction(conjugate(h.expr), (x, 0, 1))
225
+ assert conjugate(h) == Dagger(h)
226
+
227
+ piab = Wavefunction(sin(n*pi*x/L), (x, 0, L))
228
+ assert piab.norm == sqrt(L/2)
229
+ assert piab(L + 1) == 0
230
+ assert piab(0.5) == sin(0.5*n*pi/L)
231
+ assert piab(0.5, n=1, L=1) == sin(0.5*pi)
232
+ assert piab.normalize() == \
233
+ Wavefunction(sqrt(2)/sqrt(L)*sin(n*pi*x/L), (x, 0, L))
234
+ assert conjugate(piab) == Wavefunction(conjugate(piab.expr), (x, 0, L))
235
+ assert conjugate(piab) == Dagger(piab)
236
+
237
+ k = Wavefunction(x**2, 'x')
238
+ assert type(k.variables[0]) == Symbol
239
+
240
+ def test_orthogonal_states():
241
+ braket = OrthogonalBra(x) * OrthogonalKet(x)
242
+ assert braket.doit() == 1
243
+
244
+ braket = OrthogonalBra(x) * OrthogonalKet(x+1)
245
+ assert braket.doit() == 0
246
+
247
+ braket = OrthogonalBra(x) * OrthogonalKet(y)
248
+ assert braket.doit() == braket
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/dimensions.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/__pycache__/quantities.cpython-310.pyc ADDED
Binary file (5.29 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (6.03 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc ADDED
Binary file (6.12 kB). View file