ZTWHHH commited on
Commit
5449352
·
verified ·
1 Parent(s): 318fe9a

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. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc +0 -0
  3. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_gmpy.cpython-310.pyc +0 -0
  4. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc +0 -0
  5. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_ntheory.cpython-310.pyc +0 -0
  6. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc +0 -0
  7. janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc +0 -0
  8. janus/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py +307 -0
  9. janus/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py +335 -0
  10. janus/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py +176 -0
  11. janus/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py +35 -0
  12. janus/lib/python3.10/site-packages/sympy/physics/matrices.py +176 -0
  13. janus/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
  14. janus/lib/python3.10/site-packages/sympy/physics/quantum/gate.py +1309 -0
  15. janus/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py +653 -0
  16. janus/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py +853 -0
  17. janus/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py +272 -0
  18. janus/lib/python3.10/site-packages/sympy/physics/quantum/piab.py +72 -0
  19. janus/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py +212 -0
  20. janus/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py +413 -0
  21. janus/lib/python3.10/site-packages/sympy/physics/quantum/sho1d.py +679 -0
  22. janus/lib/python3.10/site-packages/sympy/physics/quantum/shor.py +173 -0
  23. janus/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py +425 -0
  24. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py +0 -0
  25. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc +0 -0
  26. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc +0 -0
  27. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc +0 -0
  28. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc +0 -0
  29. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc +0 -0
  30. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc +0 -0
  31. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc +0 -0
  32. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qexpr.cpython-310.pyc +0 -0
  33. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc +0 -0
  34. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc +0 -0
  35. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cartesian.py +104 -0
  36. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py +183 -0
  37. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_dagger.py +102 -0
  38. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py +62 -0
  39. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_gate.py +360 -0
  40. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_hilbert.py +110 -0
  41. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_identitysearch.py +492 -0
  42. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_innerproduct.py +71 -0
  43. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_operatorset.py +68 -0
  44. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_pauli.py +159 -0
  45. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_piab.py +29 -0
  46. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_printing.py +900 -0
  47. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py +186 -0
  48. janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_spin.py +0 -0
  49. janus/lib/python3.10/site-packages/sympy/physics/quantum/trace.py +230 -0
  50. janus/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -444,3 +444,4 @@ janus/lib/python3.10/site-packages/transformers/models/oneformer/__pycache__/mod
444
  janus/lib/python3.10/site-packages/transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
445
  infer_4_33_0/bin/python filter=lfs diff=lfs merge=lfs -text
446
  janus/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
 
 
444
  janus/lib/python3.10/site-packages/transformers/models/perceiver/__pycache__/modeling_perceiver.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
445
  infer_4_33_0/bin/python filter=lfs diff=lfs merge=lfs -text
446
  janus/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -text
447
+ janus/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_codegen.cpython-310.pyc ADDED
Binary file (9.61 kB). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_gmpy.cpython-310.pyc ADDED
Binary file (881 Bytes). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_importtools.cpython-310.pyc ADDED
Binary file (1.45 kB). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_ntheory.cpython-310.pyc ADDED
Binary file (9.04 kB). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_numpy.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/__pycache__/test_scipy.cpython-310.pyc ADDED
Binary file (1.03 kB). View file
 
janus/lib/python3.10/site-packages/sympy/external/tests/test_ntheory.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import permutations
2
+
3
+ from sympy.external.ntheory import (bit_scan1, remove, bit_scan0, is_fermat_prp,
4
+ is_euler_prp, is_strong_prp, gcdext, _lucas_sequence,
5
+ is_fibonacci_prp, is_lucas_prp, is_selfridge_prp,
6
+ is_strong_lucas_prp, is_strong_selfridge_prp,
7
+ is_bpsw_prp, is_strong_bpsw_prp)
8
+ from sympy.testing.pytest import raises
9
+
10
+
11
+ def test_bit_scan1():
12
+ assert bit_scan1(0) is None
13
+ assert bit_scan1(1) == 0
14
+ assert bit_scan1(-1) == 0
15
+ assert bit_scan1(2) == 1
16
+ assert bit_scan1(7) == 0
17
+ assert bit_scan1(-7) == 0
18
+ for i in range(100):
19
+ assert bit_scan1(1 << i) == i
20
+ assert bit_scan1((1 << i) * 31337) == i
21
+ for i in range(500):
22
+ n = (1 << 500) + (1 << i)
23
+ assert bit_scan1(n) == i
24
+ assert bit_scan1(1 << 1000001) == 1000001
25
+ assert bit_scan1((1 << 273956)*7**37) == 273956
26
+ # issue 12709
27
+ for i in range(1, 10):
28
+ big = 1 << i
29
+ assert bit_scan1(-big) == bit_scan1(big)
30
+
31
+
32
+ def test_bit_scan0():
33
+ assert bit_scan0(-1) is None
34
+ assert bit_scan0(0) == 0
35
+ assert bit_scan0(1) == 1
36
+ assert bit_scan0(-2) == 0
37
+
38
+
39
+ def test_remove():
40
+ raises(ValueError, lambda: remove(1, 1))
41
+ assert remove(0, 3) == (0, 0)
42
+ for f in range(2, 10):
43
+ for y in range(2, 1000):
44
+ for z in [1, 17, 101, 1009]:
45
+ assert remove(z*f**y, f) == (z, y)
46
+
47
+
48
+ def test_gcdext():
49
+ assert gcdext(0, 0) == (0, 0, 0)
50
+ assert gcdext(3, 0) == (3, 1, 0)
51
+ assert gcdext(0, 4) == (4, 0, 1)
52
+
53
+ for n in range(1, 10):
54
+ assert gcdext(n, 1) == gcdext(-n, 1) == (1, 0, 1)
55
+ assert gcdext(n, -1) == gcdext(-n, -1) == (1, 0, -1)
56
+ assert gcdext(n, n) == gcdext(-n, n) == (n, 0, 1)
57
+ assert gcdext(n, -n) == gcdext(-n, -n) == (n, 0, -1)
58
+
59
+ for n in range(2, 10):
60
+ assert gcdext(1, n) == gcdext(1, -n) == (1, 1, 0)
61
+ assert gcdext(-1, n) == gcdext(-1, -n) == (1, -1, 0)
62
+
63
+ for a, b in permutations([2**5, 3, 5, 7**2, 11], 2):
64
+ g, x, y = gcdext(a, b)
65
+ assert g == a*x + b*y == 1
66
+
67
+
68
+ def test_is_fermat_prp():
69
+ # invalid input
70
+ raises(ValueError, lambda: is_fermat_prp(0, 10))
71
+ raises(ValueError, lambda: is_fermat_prp(5, 1))
72
+
73
+ # n = 1
74
+ assert not is_fermat_prp(1, 3)
75
+
76
+ # n is prime
77
+ assert is_fermat_prp(2, 4)
78
+ assert is_fermat_prp(3, 2)
79
+ assert is_fermat_prp(11, 3)
80
+ assert is_fermat_prp(2**31-1, 5)
81
+
82
+ # A001567
83
+ pseudorpime = [341, 561, 645, 1105, 1387, 1729, 1905, 2047,
84
+ 2465, 2701, 2821, 3277, 4033, 4369, 4371, 4681]
85
+ for n in pseudorpime:
86
+ assert is_fermat_prp(n, 2)
87
+
88
+ # A020136
89
+ pseudorpime = [15, 85, 91, 341, 435, 451, 561, 645, 703, 1105,
90
+ 1247, 1271, 1387, 1581, 1695, 1729, 1891, 1905]
91
+ for n in pseudorpime:
92
+ assert is_fermat_prp(n, 4)
93
+
94
+
95
+ def test_is_euler_prp():
96
+ # invalid input
97
+ raises(ValueError, lambda: is_euler_prp(0, 10))
98
+ raises(ValueError, lambda: is_euler_prp(5, 1))
99
+
100
+ # n = 1
101
+ assert not is_euler_prp(1, 3)
102
+
103
+ # n is prime
104
+ assert is_euler_prp(2, 4)
105
+ assert is_euler_prp(3, 2)
106
+ assert is_euler_prp(11, 3)
107
+ assert is_euler_prp(2**31-1, 5)
108
+
109
+ # A047713
110
+ pseudorpime = [561, 1105, 1729, 1905, 2047, 2465, 3277, 4033,
111
+ 4681, 6601, 8321, 8481, 10585, 12801, 15841]
112
+ for n in pseudorpime:
113
+ assert is_euler_prp(n, 2)
114
+
115
+ # A048950
116
+ pseudorpime = [121, 703, 1729, 1891, 2821, 3281, 7381, 8401,
117
+ 8911, 10585, 12403, 15457, 15841, 16531, 18721]
118
+ for n in pseudorpime:
119
+ assert is_euler_prp(n, 3)
120
+
121
+
122
+ def test_is_strong_prp():
123
+ # invalid input
124
+ raises(ValueError, lambda: is_strong_prp(0, 10))
125
+ raises(ValueError, lambda: is_strong_prp(5, 1))
126
+
127
+ # n = 1
128
+ assert not is_strong_prp(1, 3)
129
+
130
+ # n is prime
131
+ assert is_strong_prp(2, 4)
132
+ assert is_strong_prp(3, 2)
133
+ assert is_strong_prp(11, 3)
134
+ assert is_strong_prp(2**31-1, 5)
135
+
136
+ # A001262
137
+ pseudorpime = [2047, 3277, 4033, 4681, 8321, 15841, 29341,
138
+ 42799, 49141, 52633, 65281, 74665, 80581]
139
+ for n in pseudorpime:
140
+ assert is_strong_prp(n, 2)
141
+
142
+ # A020229
143
+ pseudorpime = [121, 703, 1891, 3281, 8401, 8911, 10585, 12403,
144
+ 16531, 18721, 19345, 23521, 31621, 44287, 47197]
145
+ for n in pseudorpime:
146
+ assert is_strong_prp(n, 3)
147
+
148
+
149
+ def test_lucas_sequence():
150
+ def lucas_u(P, Q, length):
151
+ array = [0] * length
152
+ array[1] = 1
153
+ for k in range(2, length):
154
+ array[k] = P * array[k - 1] - Q * array[k - 2]
155
+ return array
156
+
157
+ def lucas_v(P, Q, length):
158
+ array = [0] * length
159
+ array[0] = 2
160
+ array[1] = P
161
+ for k in range(2, length):
162
+ array[k] = P * array[k - 1] - Q * array[k - 2]
163
+ return array
164
+
165
+ length = 20
166
+ for P in range(-10, 10):
167
+ for Q in range(-10, 10):
168
+ D = P**2 - 4*Q
169
+ if D == 0:
170
+ continue
171
+ us = lucas_u(P, Q, length)
172
+ vs = lucas_v(P, Q, length)
173
+ for n in range(3, 100, 2):
174
+ for k in range(length):
175
+ U, V, Qk = _lucas_sequence(n, P, Q, k)
176
+ assert U == us[k] % n
177
+ assert V == vs[k] % n
178
+ assert pow(Q, k, n) == Qk
179
+
180
+
181
+ def test_is_fibonacci_prp():
182
+ # invalid input
183
+ raises(ValueError, lambda: is_fibonacci_prp(3, 2, 1))
184
+ raises(ValueError, lambda: is_fibonacci_prp(3, -5, 1))
185
+ raises(ValueError, lambda: is_fibonacci_prp(3, 5, 2))
186
+ raises(ValueError, lambda: is_fibonacci_prp(0, 5, -1))
187
+
188
+ # n = 1
189
+ assert not is_fibonacci_prp(1, 3, 1)
190
+
191
+ # n is prime
192
+ assert is_fibonacci_prp(2, 5, 1)
193
+ assert is_fibonacci_prp(3, 6, -1)
194
+ assert is_fibonacci_prp(11, 7, 1)
195
+ assert is_fibonacci_prp(2**31-1, 8, -1)
196
+
197
+ # A005845
198
+ pseudorpime = [705, 2465, 2737, 3745, 4181, 5777, 6721,
199
+ 10877, 13201, 15251, 24465, 29281, 34561]
200
+ for n in pseudorpime:
201
+ assert is_fibonacci_prp(n, 1, -1)
202
+
203
+
204
+ def test_is_lucas_prp():
205
+ # invalid input
206
+ raises(ValueError, lambda: is_lucas_prp(3, 2, 1))
207
+ raises(ValueError, lambda: is_lucas_prp(0, 5, -1))
208
+ raises(ValueError, lambda: is_lucas_prp(15, 3, 1))
209
+
210
+ # n = 1
211
+ assert not is_lucas_prp(1, 3, 1)
212
+
213
+ # n is prime
214
+ assert is_lucas_prp(2, 5, 2)
215
+ assert is_lucas_prp(3, 6, -1)
216
+ assert is_lucas_prp(11, 7, 5)
217
+ assert is_lucas_prp(2**31-1, 8, -3)
218
+
219
+ # A081264
220
+ pseudorpime = [323, 377, 1891, 3827, 4181, 5777, 6601, 6721,
221
+ 8149, 10877, 11663, 13201, 13981, 15251, 17119]
222
+ for n in pseudorpime:
223
+ assert is_lucas_prp(n, 1, -1)
224
+
225
+
226
+ def test_is_selfridge_prp():
227
+ # invalid input
228
+ raises(ValueError, lambda: is_selfridge_prp(0))
229
+
230
+ # n = 1
231
+ assert not is_selfridge_prp(1)
232
+
233
+ # n is prime
234
+ assert is_selfridge_prp(2)
235
+ assert is_selfridge_prp(3)
236
+ assert is_selfridge_prp(11)
237
+ assert is_selfridge_prp(2**31-1)
238
+
239
+ # A217120
240
+ pseudorpime = [323, 377, 1159, 1829, 3827, 5459, 5777, 9071,
241
+ 9179, 10877, 11419, 11663, 13919, 14839, 16109]
242
+ for n in pseudorpime:
243
+ assert is_selfridge_prp(n)
244
+
245
+
246
+ def test_is_strong_lucas_prp():
247
+ # invalid input
248
+ raises(ValueError, lambda: is_strong_lucas_prp(3, 2, 1))
249
+ raises(ValueError, lambda: is_strong_lucas_prp(0, 5, -1))
250
+ raises(ValueError, lambda: is_strong_lucas_prp(15, 3, 1))
251
+
252
+ # n = 1
253
+ assert not is_strong_lucas_prp(1, 3, 1)
254
+
255
+ # n is prime
256
+ assert is_strong_lucas_prp(2, 5, 2)
257
+ assert is_strong_lucas_prp(3, 6, -1)
258
+ assert is_strong_lucas_prp(11, 7, 5)
259
+ assert is_strong_lucas_prp(2**31-1, 8, -3)
260
+
261
+
262
+ def test_is_strong_selfridge_prp():
263
+ # invalid input
264
+ raises(ValueError, lambda: is_strong_selfridge_prp(0))
265
+
266
+ # n = 1
267
+ assert not is_strong_selfridge_prp(1)
268
+
269
+ # n is prime
270
+ assert is_strong_selfridge_prp(2)
271
+ assert is_strong_selfridge_prp(3)
272
+ assert is_strong_selfridge_prp(11)
273
+ assert is_strong_selfridge_prp(2**31-1)
274
+
275
+ # A217255
276
+ pseudorpime = [5459, 5777, 10877, 16109, 18971, 22499, 24569,
277
+ 25199, 40309, 58519, 75077, 97439, 100127, 113573]
278
+ for n in pseudorpime:
279
+ assert is_strong_selfridge_prp(n)
280
+
281
+
282
+ def test_is_bpsw_prp():
283
+ # invalid input
284
+ raises(ValueError, lambda: is_bpsw_prp(0))
285
+
286
+ # n = 1
287
+ assert not is_bpsw_prp(1)
288
+
289
+ # n is prime
290
+ assert is_bpsw_prp(2)
291
+ assert is_bpsw_prp(3)
292
+ assert is_bpsw_prp(11)
293
+ assert is_bpsw_prp(2**31-1)
294
+
295
+
296
+ def test_is_strong_bpsw_prp():
297
+ # invalid input
298
+ raises(ValueError, lambda: is_strong_bpsw_prp(0))
299
+
300
+ # n = 1
301
+ assert not is_strong_bpsw_prp(1)
302
+
303
+ # n is prime
304
+ assert is_strong_bpsw_prp(2)
305
+ assert is_strong_bpsw_prp(3)
306
+ assert is_strong_bpsw_prp(11)
307
+ assert is_strong_bpsw_prp(2**31-1)
janus/lib/python3.10/site-packages/sympy/external/tests/test_numpy.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This testfile tests SymPy <-> NumPy compatibility
2
+
3
+ # Don't test any SymPy features here. Just pure interaction with NumPy.
4
+ # Always write regular SymPy tests for anything, that can be tested in pure
5
+ # Python (without numpy). Here we test everything, that a user may need when
6
+ # using SymPy with NumPy
7
+ from sympy.external.importtools import version_tuple
8
+ from sympy.external import import_module
9
+
10
+ numpy = import_module('numpy')
11
+ if numpy:
12
+ array, matrix, ndarray = numpy.array, numpy.matrix, numpy.ndarray
13
+ else:
14
+ #bin/test will not execute any tests now
15
+ disabled = True
16
+
17
+
18
+ from sympy.core.numbers import (Float, Integer, Rational)
19
+ from sympy.core.symbol import (Symbol, symbols)
20
+ from sympy.functions.elementary.trigonometric import sin
21
+ from sympy.matrices.dense import (Matrix, list2numpy, matrix2numpy, symarray)
22
+ from sympy.utilities.lambdify import lambdify
23
+ import sympy
24
+
25
+ import mpmath
26
+ from sympy.abc import x, y, z
27
+ from sympy.utilities.decorator import conserve_mpmath_dps
28
+ from sympy.utilities.exceptions import ignore_warnings
29
+ from sympy.testing.pytest import raises
30
+
31
+
32
+ # first, systematically check, that all operations are implemented and don't
33
+ # raise an exception
34
+
35
+
36
+ def test_systematic_basic():
37
+ def s(sympy_object, numpy_array):
38
+ _ = [sympy_object + numpy_array,
39
+ numpy_array + sympy_object,
40
+ sympy_object - numpy_array,
41
+ numpy_array - sympy_object,
42
+ sympy_object * numpy_array,
43
+ numpy_array * sympy_object,
44
+ sympy_object / numpy_array,
45
+ numpy_array / sympy_object,
46
+ sympy_object ** numpy_array,
47
+ numpy_array ** sympy_object]
48
+ x = Symbol("x")
49
+ y = Symbol("y")
50
+ sympy_objs = [
51
+ Rational(2, 3),
52
+ Float("1.3"),
53
+ x,
54
+ y,
55
+ pow(x, y)*y,
56
+ Integer(5),
57
+ Float(5.5),
58
+ ]
59
+ numpy_objs = [
60
+ array([1]),
61
+ array([3, 8, -1]),
62
+ array([x, x**2, Rational(5)]),
63
+ array([x/y*sin(y), 5, Rational(5)]),
64
+ ]
65
+ for x in sympy_objs:
66
+ for y in numpy_objs:
67
+ s(x, y)
68
+
69
+
70
+ # now some random tests, that test particular problems and that also
71
+ # check that the results of the operations are correct
72
+
73
+ def test_basics():
74
+ one = Rational(1)
75
+ zero = Rational(0)
76
+ assert array(1) == array(one)
77
+ assert array([one]) == array([one])
78
+ assert array([x]) == array([x])
79
+ assert array(x) == array(Symbol("x"))
80
+ assert array(one + x) == array(1 + x)
81
+
82
+ X = array([one, zero, zero])
83
+ assert (X == array([one, zero, zero])).all()
84
+ assert (X == array([one, 0, 0])).all()
85
+
86
+
87
+ def test_arrays():
88
+ one = Rational(1)
89
+ zero = Rational(0)
90
+ X = array([one, zero, zero])
91
+ Y = one*X
92
+ X = array([Symbol("a") + Rational(1, 2)])
93
+ Y = X + X
94
+ assert Y == array([1 + 2*Symbol("a")])
95
+ Y = Y + 1
96
+ assert Y == array([2 + 2*Symbol("a")])
97
+ Y = X - X
98
+ assert Y == array([0])
99
+
100
+
101
+ def test_conversion1():
102
+ a = list2numpy([x**2, x])
103
+ #looks like an array?
104
+ assert isinstance(a, ndarray)
105
+ assert a[0] == x**2
106
+ assert a[1] == x
107
+ assert len(a) == 2
108
+ #yes, it's the array
109
+
110
+
111
+ def test_conversion2():
112
+ a = 2*list2numpy([x**2, x])
113
+ b = list2numpy([2*x**2, 2*x])
114
+ assert (a == b).all()
115
+
116
+ one = Rational(1)
117
+ zero = Rational(0)
118
+ X = list2numpy([one, zero, zero])
119
+ Y = one*X
120
+ X = list2numpy([Symbol("a") + Rational(1, 2)])
121
+ Y = X + X
122
+ assert Y == array([1 + 2*Symbol("a")])
123
+ Y = Y + 1
124
+ assert Y == array([2 + 2*Symbol("a")])
125
+ Y = X - X
126
+ assert Y == array([0])
127
+
128
+
129
+ def test_list2numpy():
130
+ assert (array([x**2, x]) == list2numpy([x**2, x])).all()
131
+
132
+
133
+ def test_Matrix1():
134
+ m = Matrix([[x, x**2], [5, 2/x]])
135
+ assert (array(m.subs(x, 2)) == array([[2, 4], [5, 1]])).all()
136
+ m = Matrix([[sin(x), x**2], [5, 2/x]])
137
+ assert (array(m.subs(x, 2)) == array([[sin(2), 4], [5, 1]])).all()
138
+
139
+
140
+ def test_Matrix2():
141
+ m = Matrix([[x, x**2], [5, 2/x]])
142
+ with ignore_warnings(PendingDeprecationWarning):
143
+ assert (matrix(m.subs(x, 2)) == matrix([[2, 4], [5, 1]])).all()
144
+ m = Matrix([[sin(x), x**2], [5, 2/x]])
145
+ with ignore_warnings(PendingDeprecationWarning):
146
+ assert (matrix(m.subs(x, 2)) == matrix([[sin(2), 4], [5, 1]])).all()
147
+
148
+
149
+ def test_Matrix3():
150
+ a = array([[2, 4], [5, 1]])
151
+ assert Matrix(a) == Matrix([[2, 4], [5, 1]])
152
+ assert Matrix(a) != Matrix([[2, 4], [5, 2]])
153
+ a = array([[sin(2), 4], [5, 1]])
154
+ assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
155
+ assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
156
+
157
+
158
+ def test_Matrix4():
159
+ with ignore_warnings(PendingDeprecationWarning):
160
+ a = matrix([[2, 4], [5, 1]])
161
+ assert Matrix(a) == Matrix([[2, 4], [5, 1]])
162
+ assert Matrix(a) != Matrix([[2, 4], [5, 2]])
163
+ with ignore_warnings(PendingDeprecationWarning):
164
+ a = matrix([[sin(2), 4], [5, 1]])
165
+ assert Matrix(a) == Matrix([[sin(2), 4], [5, 1]])
166
+ assert Matrix(a) != Matrix([[sin(0), 4], [5, 1]])
167
+
168
+
169
+ def test_Matrix_sum():
170
+ M = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
171
+ with ignore_warnings(PendingDeprecationWarning):
172
+ m = matrix([[2, 3, 4], [x, 5, 6], [x, y, z**2]])
173
+ assert M + m == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
174
+ assert m + M == Matrix([[3, 5, 7], [2*x, y + 5, x + 6], [2*y + x, y - 50, z*x + z**2]])
175
+ assert M + m == M.add(m)
176
+
177
+
178
+ def test_Matrix_mul():
179
+ M = Matrix([[1, 2, 3], [x, y, x]])
180
+ with ignore_warnings(PendingDeprecationWarning):
181
+ m = matrix([[2, 4], [x, 6], [x, z**2]])
182
+ assert M*m == Matrix([
183
+ [ 2 + 5*x, 16 + 3*z**2],
184
+ [2*x + x*y + x**2, 4*x + 6*y + x*z**2],
185
+ ])
186
+
187
+ assert m*M == Matrix([
188
+ [ 2 + 4*x, 4 + 4*y, 6 + 4*x],
189
+ [ 7*x, 2*x + 6*y, 9*x],
190
+ [x + x*z**2, 2*x + y*z**2, 3*x + x*z**2],
191
+ ])
192
+ a = array([2])
193
+ assert a[0] * M == 2 * M
194
+ assert M * a[0] == 2 * M
195
+
196
+
197
+ def test_Matrix_array():
198
+ class matarray:
199
+ def __array__(self, dtype=object, copy=None):
200
+ if copy is not None and not copy:
201
+ raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
202
+ from numpy import array
203
+ return array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
204
+ matarr = matarray()
205
+ assert Matrix(matarr) == Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
206
+
207
+
208
+ def test_matrix2numpy():
209
+ a = matrix2numpy(Matrix([[1, x**2], [3*sin(x), 0]]))
210
+ assert isinstance(a, ndarray)
211
+ assert a.shape == (2, 2)
212
+ assert a[0, 0] == 1
213
+ assert a[0, 1] == x**2
214
+ assert a[1, 0] == 3*sin(x)
215
+ assert a[1, 1] == 0
216
+
217
+
218
+ def test_matrix2numpy_conversion():
219
+ a = Matrix([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
220
+ b = array([[1, 2, sin(x)], [x**2, x, Rational(1, 2)]])
221
+ assert (matrix2numpy(a) == b).all()
222
+ assert matrix2numpy(a).dtype == numpy.dtype('object')
223
+
224
+ c = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='int8')
225
+ d = matrix2numpy(Matrix([[1, 2], [10, 20]]), dtype='float64')
226
+ assert c.dtype == numpy.dtype('int8')
227
+ assert d.dtype == numpy.dtype('float64')
228
+
229
+
230
+ def test_issue_3728():
231
+ assert (Rational(1, 2)*array([2*x, 0]) == array([x, 0])).all()
232
+ assert (Rational(1, 2) + array(
233
+ [2*x, 0]) == array([2*x + Rational(1, 2), Rational(1, 2)])).all()
234
+ assert (Float("0.5")*array([2*x, 0]) == array([Float("1.0")*x, 0])).all()
235
+ assert (Float("0.5") + array(
236
+ [2*x, 0]) == array([2*x + Float("0.5"), Float("0.5")])).all()
237
+
238
+
239
+ @conserve_mpmath_dps
240
+ def test_lambdify():
241
+ mpmath.mp.dps = 16
242
+ sin02 = mpmath.mpf("0.198669330795061215459412627")
243
+ f = lambdify(x, sin(x), "numpy")
244
+ prec = 1e-15
245
+ assert -prec < f(0.2) - sin02 < prec
246
+
247
+ # if this succeeds, it can't be a numpy function
248
+
249
+ if version_tuple(numpy.__version__) >= version_tuple('1.17'):
250
+ with raises(TypeError):
251
+ f(x)
252
+ else:
253
+ with raises(AttributeError):
254
+ f(x)
255
+
256
+
257
+ def test_lambdify_matrix():
258
+ f = lambdify(x, Matrix([[x, 2*x], [1, 2]]), [{'ImmutableMatrix': numpy.array}, "numpy"])
259
+ assert (f(1) == array([[1, 2], [1, 2]])).all()
260
+
261
+
262
+ def test_lambdify_matrix_multi_input():
263
+ M = sympy.Matrix([[x**2, x*y, x*z],
264
+ [y*x, y**2, y*z],
265
+ [z*x, z*y, z**2]])
266
+ f = lambdify((x, y, z), M, [{'ImmutableMatrix': numpy.array}, "numpy"])
267
+
268
+ xh, yh, zh = 1.0, 2.0, 3.0
269
+ expected = array([[xh**2, xh*yh, xh*zh],
270
+ [yh*xh, yh**2, yh*zh],
271
+ [zh*xh, zh*yh, zh**2]])
272
+ actual = f(xh, yh, zh)
273
+ assert numpy.allclose(actual, expected)
274
+
275
+
276
+ def test_lambdify_matrix_vec_input():
277
+ X = sympy.DeferredVector('X')
278
+ M = Matrix([
279
+ [X[0]**2, X[0]*X[1], X[0]*X[2]],
280
+ [X[1]*X[0], X[1]**2, X[1]*X[2]],
281
+ [X[2]*X[0], X[2]*X[1], X[2]**2]])
282
+ f = lambdify(X, M, [{'ImmutableMatrix': numpy.array}, "numpy"])
283
+
284
+ Xh = array([1.0, 2.0, 3.0])
285
+ expected = array([[Xh[0]**2, Xh[0]*Xh[1], Xh[0]*Xh[2]],
286
+ [Xh[1]*Xh[0], Xh[1]**2, Xh[1]*Xh[2]],
287
+ [Xh[2]*Xh[0], Xh[2]*Xh[1], Xh[2]**2]])
288
+ actual = f(Xh)
289
+ assert numpy.allclose(actual, expected)
290
+
291
+
292
+ def test_lambdify_transl():
293
+ from sympy.utilities.lambdify import NUMPY_TRANSLATIONS
294
+ for sym, mat in NUMPY_TRANSLATIONS.items():
295
+ assert sym in sympy.__dict__
296
+ assert mat in numpy.__dict__
297
+
298
+
299
+ def test_symarray():
300
+ """Test creation of numpy arrays of SymPy symbols."""
301
+
302
+ import numpy as np
303
+ import numpy.testing as npt
304
+
305
+ syms = symbols('_0,_1,_2')
306
+ s1 = symarray("", 3)
307
+ s2 = symarray("", 3)
308
+ npt.assert_array_equal(s1, np.array(syms, dtype=object))
309
+ assert s1[0] == s2[0]
310
+
311
+ a = symarray('a', 3)
312
+ b = symarray('b', 3)
313
+ assert not(a[0] == b[0])
314
+
315
+ asyms = symbols('a_0,a_1,a_2')
316
+ npt.assert_array_equal(a, np.array(asyms, dtype=object))
317
+
318
+ # Multidimensional checks
319
+ a2d = symarray('a', (2, 3))
320
+ assert a2d.shape == (2, 3)
321
+ a00, a12 = symbols('a_0_0,a_1_2')
322
+ assert a2d[0, 0] == a00
323
+ assert a2d[1, 2] == a12
324
+
325
+ a3d = symarray('a', (2, 3, 2))
326
+ assert a3d.shape == (2, 3, 2)
327
+ a000, a120, a121 = symbols('a_0_0_0,a_1_2_0,a_1_2_1')
328
+ assert a3d[0, 0, 0] == a000
329
+ assert a3d[1, 2, 0] == a120
330
+ assert a3d[1, 2, 1] == a121
331
+
332
+
333
+ def test_vectorize():
334
+ assert (numpy.vectorize(
335
+ sin)([1, 2, 3]) == numpy.array([sin(1), sin(2), sin(3)])).all()
janus/lib/python3.10/site-packages/sympy/external/tests/test_pythonmpq.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_pythonmpq.py
3
+
4
+ Test the PythonMPQ class for consistency with gmpy2's mpq type. If gmpy2 is
5
+ installed run the same tests for both.
6
+ """
7
+ from fractions import Fraction
8
+ from decimal import Decimal
9
+ import pickle
10
+ from typing import Callable, List, Tuple, Type
11
+
12
+ from sympy.testing.pytest import raises
13
+
14
+ from sympy.external.pythonmpq import PythonMPQ
15
+
16
+ #
17
+ # If gmpy2 is installed then run the tests for both mpq and PythonMPQ.
18
+ # That should ensure consistency between the implementation here and mpq.
19
+ #
20
+ rational_types: List[Tuple[Callable, Type, Callable, Type]]
21
+ rational_types = [(PythonMPQ, PythonMPQ, int, int)]
22
+ try:
23
+ from gmpy2 import mpq, mpz
24
+ rational_types.append((mpq, type(mpq(1)), mpz, type(mpz(1))))
25
+ except ImportError:
26
+ pass
27
+
28
+
29
+ def test_PythonMPQ():
30
+ #
31
+ # Test PythonMPQ and also mpq if gmpy/gmpy2 is installed.
32
+ #
33
+ for Q, TQ, Z, TZ in rational_types:
34
+
35
+ def check_Q(q):
36
+ assert isinstance(q, TQ)
37
+ assert isinstance(q.numerator, TZ)
38
+ assert isinstance(q.denominator, TZ)
39
+ return q.numerator, q.denominator
40
+
41
+ # Check construction from different types
42
+ assert check_Q(Q(3)) == (3, 1)
43
+ assert check_Q(Q(3, 5)) == (3, 5)
44
+ assert check_Q(Q(Q(3, 5))) == (3, 5)
45
+ assert check_Q(Q(0.5)) == (1, 2)
46
+ assert check_Q(Q('0.5')) == (1, 2)
47
+ assert check_Q(Q(Fraction(3, 5))) == (3, 5)
48
+
49
+ # https://github.com/aleaxit/gmpy/issues/327
50
+ if Q is PythonMPQ:
51
+ assert check_Q(Q(Decimal('0.6'))) == (3, 5)
52
+
53
+ # Invalid types
54
+ raises(TypeError, lambda: Q([]))
55
+ raises(TypeError, lambda: Q([], []))
56
+
57
+ # Check normalisation of signs
58
+ assert check_Q(Q(2, 3)) == (2, 3)
59
+ assert check_Q(Q(-2, 3)) == (-2, 3)
60
+ assert check_Q(Q(2, -3)) == (-2, 3)
61
+ assert check_Q(Q(-2, -3)) == (2, 3)
62
+
63
+ # Check gcd calculation
64
+ assert check_Q(Q(12, 8)) == (3, 2)
65
+
66
+ # __int__/__float__
67
+ assert int(Q(5, 3)) == 1
68
+ assert int(Q(-5, 3)) == -1
69
+ assert float(Q(5, 2)) == 2.5
70
+ assert float(Q(-5, 2)) == -2.5
71
+
72
+ # __str__/__repr__
73
+ assert str(Q(2, 1)) == "2"
74
+ assert str(Q(1, 2)) == "1/2"
75
+ if Q is PythonMPQ:
76
+ assert repr(Q(2, 1)) == "MPQ(2,1)"
77
+ assert repr(Q(1, 2)) == "MPQ(1,2)"
78
+ else:
79
+ assert repr(Q(2, 1)) == "mpq(2,1)"
80
+ assert repr(Q(1, 2)) == "mpq(1,2)"
81
+
82
+ # __bool__
83
+ assert bool(Q(1, 2)) is True
84
+ assert bool(Q(0)) is False
85
+
86
+ # __eq__/__ne__
87
+ assert (Q(2, 3) == Q(2, 3)) is True
88
+ assert (Q(2, 3) == Q(2, 5)) is False
89
+ assert (Q(2, 3) != Q(2, 3)) is False
90
+ assert (Q(2, 3) != Q(2, 5)) is True
91
+
92
+ # __hash__
93
+ assert hash(Q(3, 5)) == hash(Fraction(3, 5))
94
+
95
+ # __reduce__
96
+ q = Q(2, 3)
97
+ assert pickle.loads(pickle.dumps(q)) == q
98
+
99
+ # __ge__/__gt__/__le__/__lt__
100
+ assert (Q(1, 3) < Q(2, 3)) is True
101
+ assert (Q(2, 3) < Q(2, 3)) is False
102
+ assert (Q(2, 3) < Q(1, 3)) is False
103
+ assert (Q(-2, 3) < Q(1, 3)) is True
104
+ assert (Q(1, 3) < Q(-2, 3)) is False
105
+
106
+ assert (Q(1, 3) <= Q(2, 3)) is True
107
+ assert (Q(2, 3) <= Q(2, 3)) is True
108
+ assert (Q(2, 3) <= Q(1, 3)) is False
109
+ assert (Q(-2, 3) <= Q(1, 3)) is True
110
+ assert (Q(1, 3) <= Q(-2, 3)) is False
111
+
112
+ assert (Q(1, 3) > Q(2, 3)) is False
113
+ assert (Q(2, 3) > Q(2, 3)) is False
114
+ assert (Q(2, 3) > Q(1, 3)) is True
115
+ assert (Q(-2, 3) > Q(1, 3)) is False
116
+ assert (Q(1, 3) > Q(-2, 3)) is True
117
+
118
+ assert (Q(1, 3) >= Q(2, 3)) is False
119
+ assert (Q(2, 3) >= Q(2, 3)) is True
120
+ assert (Q(2, 3) >= Q(1, 3)) is True
121
+ assert (Q(-2, 3) >= Q(1, 3)) is False
122
+ assert (Q(1, 3) >= Q(-2, 3)) is True
123
+
124
+ # __abs__/__pos__/__neg__
125
+ assert abs(Q(2, 3)) == abs(Q(-2, 3)) == Q(2, 3)
126
+ assert +Q(2, 3) == Q(2, 3)
127
+ assert -Q(2, 3) == Q(-2, 3)
128
+
129
+ # __add__/__radd__
130
+ assert Q(2, 3) + Q(5, 7) == Q(29, 21)
131
+ assert Q(2, 3) + 1 == Q(5, 3)
132
+ assert 1 + Q(2, 3) == Q(5, 3)
133
+ raises(TypeError, lambda: [] + Q(1))
134
+ raises(TypeError, lambda: Q(1) + [])
135
+
136
+ # __sub__/__rsub__
137
+ assert Q(2, 3) - Q(5, 7) == Q(-1, 21)
138
+ assert Q(2, 3) - 1 == Q(-1, 3)
139
+ assert 1 - Q(2, 3) == Q(1, 3)
140
+ raises(TypeError, lambda: [] - Q(1))
141
+ raises(TypeError, lambda: Q(1) - [])
142
+
143
+ # __mul__/__rmul__
144
+ assert Q(2, 3) * Q(5, 7) == Q(10, 21)
145
+ assert Q(2, 3) * 1 == Q(2, 3)
146
+ assert 1 * Q(2, 3) == Q(2, 3)
147
+ raises(TypeError, lambda: [] * Q(1))
148
+ raises(TypeError, lambda: Q(1) * [])
149
+
150
+ # __pow__/__rpow__
151
+ assert Q(2, 3) ** 2 == Q(4, 9)
152
+ assert Q(2, 3) ** 1 == Q(2, 3)
153
+ assert Q(-2, 3) ** 2 == Q(4, 9)
154
+ assert Q(-2, 3) ** -1 == Q(-3, 2)
155
+ if Q is PythonMPQ:
156
+ raises(TypeError, lambda: 1 ** Q(2, 3))
157
+ raises(TypeError, lambda: Q(1, 4) ** Q(1, 2))
158
+ raises(TypeError, lambda: [] ** Q(1))
159
+ raises(TypeError, lambda: Q(1) ** [])
160
+
161
+ # __div__/__rdiv__
162
+ assert Q(2, 3) / Q(5, 7) == Q(14, 15)
163
+ assert Q(2, 3) / 1 == Q(2, 3)
164
+ assert 1 / Q(2, 3) == Q(3, 2)
165
+ raises(TypeError, lambda: [] / Q(1))
166
+ raises(TypeError, lambda: Q(1) / [])
167
+ raises(ZeroDivisionError, lambda: Q(1, 2) / Q(0))
168
+
169
+ # __divmod__
170
+ if Q is PythonMPQ:
171
+ raises(TypeError, lambda: Q(2, 3) // Q(1, 3))
172
+ raises(TypeError, lambda: Q(2, 3) % Q(1, 3))
173
+ raises(TypeError, lambda: 1 // Q(1, 3))
174
+ raises(TypeError, lambda: 1 % Q(1, 3))
175
+ raises(TypeError, lambda: Q(2, 3) // 1)
176
+ raises(TypeError, lambda: Q(2, 3) % 1)
janus/lib/python3.10/site-packages/sympy/external/tests/test_scipy.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This testfile tests SymPy <-> SciPy compatibility
2
+
3
+ # Don't test any SymPy features here. Just pure interaction with SciPy.
4
+ # Always write regular SymPy tests for anything, that can be tested in pure
5
+ # Python (without scipy). Here we test everything, that a user may need when
6
+ # using SymPy with SciPy
7
+
8
+ from sympy.external import import_module
9
+
10
+ scipy = import_module('scipy')
11
+ if not scipy:
12
+ #bin/test will not execute any tests now
13
+ disabled = True
14
+
15
+ from sympy.functions.special.bessel import jn_zeros
16
+
17
+
18
+ def eq(a, b, tol=1e-6):
19
+ for x, y in zip(a, b):
20
+ if not (abs(x - y) < tol):
21
+ return False
22
+ return True
23
+
24
+
25
+ def test_jn_zeros():
26
+ assert eq(jn_zeros(0, 4, method="scipy"),
27
+ [3.141592, 6.283185, 9.424777, 12.566370])
28
+ assert eq(jn_zeros(1, 4, method="scipy"),
29
+ [4.493409, 7.725251, 10.904121, 14.066193])
30
+ assert eq(jn_zeros(2, 4, method="scipy"),
31
+ [5.763459, 9.095011, 12.322940, 15.514603])
32
+ assert eq(jn_zeros(3, 4, method="scipy"),
33
+ [6.987932, 10.417118, 13.698023, 16.923621])
34
+ assert eq(jn_zeros(4, 4, method="scipy"),
35
+ [8.182561, 11.704907, 15.039664, 18.301255])
janus/lib/python3.10/site-packages/sympy/physics/matrices.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Known matrices related to physics"""
2
+
3
+ from sympy.core.numbers import I
4
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
5
+ from sympy.utilities.decorator import deprecated
6
+
7
+
8
+ def msigma(i):
9
+ r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3`.
10
+
11
+ References
12
+ ==========
13
+
14
+ .. [1] https://en.wikipedia.org/wiki/Pauli_matrices
15
+
16
+ Examples
17
+ ========
18
+
19
+ >>> from sympy.physics.matrices import msigma
20
+ >>> msigma(1)
21
+ Matrix([
22
+ [0, 1],
23
+ [1, 0]])
24
+ """
25
+ if i == 1:
26
+ mat = (
27
+ (0, 1),
28
+ (1, 0)
29
+ )
30
+ elif i == 2:
31
+ mat = (
32
+ (0, -I),
33
+ (I, 0)
34
+ )
35
+ elif i == 3:
36
+ mat = (
37
+ (1, 0),
38
+ (0, -1)
39
+ )
40
+ else:
41
+ raise IndexError("Invalid Pauli index")
42
+ return Matrix(mat)
43
+
44
+
45
+ def pat_matrix(m, dx, dy, dz):
46
+ """Returns the Parallel Axis Theorem matrix to translate the inertia
47
+ matrix a distance of `(dx, dy, dz)` for a body of mass m.
48
+
49
+ Examples
50
+ ========
51
+
52
+ To translate a body having a mass of 2 units a distance of 1 unit along
53
+ the `x`-axis we get:
54
+
55
+ >>> from sympy.physics.matrices import pat_matrix
56
+ >>> pat_matrix(2, 1, 0, 0)
57
+ Matrix([
58
+ [0, 0, 0],
59
+ [0, 2, 0],
60
+ [0, 0, 2]])
61
+
62
+ """
63
+ dxdy = -dx*dy
64
+ dydz = -dy*dz
65
+ dzdx = -dz*dx
66
+ dxdx = dx**2
67
+ dydy = dy**2
68
+ dzdz = dz**2
69
+ mat = ((dydy + dzdz, dxdy, dzdx),
70
+ (dxdy, dxdx + dzdz, dydz),
71
+ (dzdx, dydz, dydy + dxdx))
72
+ return m*Matrix(mat)
73
+
74
+
75
+ def mgamma(mu, lower=False):
76
+ r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard
77
+ (Dirac) representation.
78
+
79
+ Explanation
80
+ ===========
81
+
82
+ If you want `\gamma_\mu`, use ``gamma(mu, True)``.
83
+
84
+ We use a convention:
85
+
86
+ `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3`
87
+
88
+ `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5`
89
+
90
+ References
91
+ ==========
92
+
93
+ .. [1] https://en.wikipedia.org/wiki/Gamma_matrices
94
+
95
+ Examples
96
+ ========
97
+
98
+ >>> from sympy.physics.matrices import mgamma
99
+ >>> mgamma(1)
100
+ Matrix([
101
+ [ 0, 0, 0, 1],
102
+ [ 0, 0, 1, 0],
103
+ [ 0, -1, 0, 0],
104
+ [-1, 0, 0, 0]])
105
+ """
106
+ if mu not in (0, 1, 2, 3, 5):
107
+ raise IndexError("Invalid Dirac index")
108
+ if mu == 0:
109
+ mat = (
110
+ (1, 0, 0, 0),
111
+ (0, 1, 0, 0),
112
+ (0, 0, -1, 0),
113
+ (0, 0, 0, -1)
114
+ )
115
+ elif mu == 1:
116
+ mat = (
117
+ (0, 0, 0, 1),
118
+ (0, 0, 1, 0),
119
+ (0, -1, 0, 0),
120
+ (-1, 0, 0, 0)
121
+ )
122
+ elif mu == 2:
123
+ mat = (
124
+ (0, 0, 0, -I),
125
+ (0, 0, I, 0),
126
+ (0, I, 0, 0),
127
+ (-I, 0, 0, 0)
128
+ )
129
+ elif mu == 3:
130
+ mat = (
131
+ (0, 0, 1, 0),
132
+ (0, 0, 0, -1),
133
+ (-1, 0, 0, 0),
134
+ (0, 1, 0, 0)
135
+ )
136
+ elif mu == 5:
137
+ mat = (
138
+ (0, 0, 1, 0),
139
+ (0, 0, 0, 1),
140
+ (1, 0, 0, 0),
141
+ (0, 1, 0, 0)
142
+ )
143
+ m = Matrix(mat)
144
+ if lower:
145
+ if mu in (1, 2, 3, 5):
146
+ m = -m
147
+ return m
148
+
149
+ #Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field
150
+ #Theory
151
+ minkowski_tensor = Matrix( (
152
+ (1, 0, 0, 0),
153
+ (0, -1, 0, 0),
154
+ (0, 0, -1, 0),
155
+ (0, 0, 0, -1)
156
+ ))
157
+
158
+
159
+ @deprecated(
160
+ """
161
+ The sympy.physics.matrices.mdft method is deprecated. Use
162
+ sympy.DFT(n).as_explicit() instead.
163
+ """,
164
+ deprecated_since_version="1.9",
165
+ active_deprecations_target="deprecated-physics-mdft",
166
+ )
167
+ def mdft(n):
168
+ r"""
169
+ .. deprecated:: 1.9
170
+
171
+ Use DFT from sympy.matrices.expressions.fourier instead.
172
+
173
+ To get identical behavior to ``mdft(n)``, use ``DFT(n).as_explicit()``.
174
+ """
175
+ from sympy.matrices.expressions.fourier import DFT
176
+ return DFT(n).as_mutable()
janus/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The commutator: [A,B] = A*B - B*A."""
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.power import Pow
7
+ from sympy.core.singleton import S
8
+ from sympy.printing.pretty.stringpict import prettyForm
9
+
10
+ from sympy.physics.quantum.dagger import Dagger
11
+ from sympy.physics.quantum.operator import Operator
12
+
13
+
14
+ __all__ = [
15
+ 'Commutator'
16
+ ]
17
+
18
+ #-----------------------------------------------------------------------------
19
+ # Commutator
20
+ #-----------------------------------------------------------------------------
21
+
22
+
23
+ class Commutator(Expr):
24
+ """The standard commutator, in an unevaluated state.
25
+
26
+ Explanation
27
+ ===========
28
+
29
+ Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
30
+ class returns the commutator in an unevaluated form. To evaluate the
31
+ commutator, use the ``.doit()`` method.
32
+
33
+ Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
34
+ arguments of the commutator are put into canonical order using ``__cmp__``.
35
+ If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
36
+
37
+ Parameters
38
+ ==========
39
+
40
+ A : Expr
41
+ The first argument of the commutator [A,B].
42
+ B : Expr
43
+ The second argument of the commutator [A,B].
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy.physics.quantum import Commutator, Dagger, Operator
49
+ >>> from sympy.abc import x, y
50
+ >>> A = Operator('A')
51
+ >>> B = Operator('B')
52
+ >>> C = Operator('C')
53
+
54
+ Create a commutator and use ``.doit()`` to evaluate it:
55
+
56
+ >>> comm = Commutator(A, B)
57
+ >>> comm
58
+ [A,B]
59
+ >>> comm.doit()
60
+ A*B - B*A
61
+
62
+ The commutator orders it arguments in canonical order:
63
+
64
+ >>> comm = Commutator(B, A); comm
65
+ -[A,B]
66
+
67
+ Commutative constants are factored out:
68
+
69
+ >>> Commutator(3*x*A, x*y*B)
70
+ 3*x**2*y*[A,B]
71
+
72
+ Using ``.expand(commutator=True)``, the standard commutator expansion rules
73
+ can be applied:
74
+
75
+ >>> Commutator(A+B, C).expand(commutator=True)
76
+ [A,C] + [B,C]
77
+ >>> Commutator(A, B+C).expand(commutator=True)
78
+ [A,B] + [A,C]
79
+ >>> Commutator(A*B, C).expand(commutator=True)
80
+ [A,C]*B + A*[B,C]
81
+ >>> Commutator(A, B*C).expand(commutator=True)
82
+ [A,B]*C + B*[A,C]
83
+
84
+ Adjoint operations applied to the commutator are properly applied to the
85
+ arguments:
86
+
87
+ >>> Dagger(Commutator(A, B))
88
+ -[Dagger(A),Dagger(B)]
89
+
90
+ References
91
+ ==========
92
+
93
+ .. [1] https://en.wikipedia.org/wiki/Commutator
94
+ """
95
+ is_commutative = False
96
+
97
+ def __new__(cls, A, B):
98
+ r = cls.eval(A, B)
99
+ if r is not None:
100
+ return r
101
+ obj = Expr.__new__(cls, A, B)
102
+ return obj
103
+
104
+ @classmethod
105
+ def eval(cls, a, b):
106
+ if not (a and b):
107
+ return S.Zero
108
+ if a == b:
109
+ return S.Zero
110
+ if a.is_commutative or b.is_commutative:
111
+ return S.Zero
112
+
113
+ # [xA,yB] -> xy*[A,B]
114
+ ca, nca = a.args_cnc()
115
+ cb, ncb = b.args_cnc()
116
+ c_part = ca + cb
117
+ if c_part:
118
+ return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
119
+
120
+ # Canonical ordering of arguments
121
+ # The Commutator [A, B] is in canonical form if A < B.
122
+ if a.compare(b) == 1:
123
+ return S.NegativeOne*cls(b, a)
124
+
125
+ def _expand_pow(self, A, B, sign):
126
+ exp = A.exp
127
+ if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
128
+ # nothing to do
129
+ return self
130
+ base = A.base
131
+ if exp.is_negative:
132
+ base = A.base**-1
133
+ exp = -exp
134
+ comm = Commutator(base, B).expand(commutator=True)
135
+
136
+ result = base**(exp - 1) * comm
137
+ for i in range(1, exp):
138
+ result += base**(exp - 1 - i) * comm * base**i
139
+ return sign*result.expand()
140
+
141
+ def _eval_expand_commutator(self, **hints):
142
+ A = self.args[0]
143
+ B = self.args[1]
144
+
145
+ if isinstance(A, Add):
146
+ # [A + B, C] -> [A, C] + [B, C]
147
+ sargs = []
148
+ for term in A.args:
149
+ comm = Commutator(term, B)
150
+ if isinstance(comm, Commutator):
151
+ comm = comm._eval_expand_commutator()
152
+ sargs.append(comm)
153
+ return Add(*sargs)
154
+ elif isinstance(B, Add):
155
+ # [A, B + C] -> [A, B] + [A, C]
156
+ sargs = []
157
+ for term in B.args:
158
+ comm = Commutator(A, term)
159
+ if isinstance(comm, Commutator):
160
+ comm = comm._eval_expand_commutator()
161
+ sargs.append(comm)
162
+ return Add(*sargs)
163
+ elif isinstance(A, Mul):
164
+ # [A*B, C] -> A*[B, C] + [A, C]*B
165
+ a = A.args[0]
166
+ b = Mul(*A.args[1:])
167
+ c = B
168
+ comm1 = Commutator(b, c)
169
+ comm2 = Commutator(a, c)
170
+ if isinstance(comm1, Commutator):
171
+ comm1 = comm1._eval_expand_commutator()
172
+ if isinstance(comm2, Commutator):
173
+ comm2 = comm2._eval_expand_commutator()
174
+ first = Mul(a, comm1)
175
+ second = Mul(comm2, b)
176
+ return Add(first, second)
177
+ elif isinstance(B, Mul):
178
+ # [A, B*C] -> [A, B]*C + B*[A, C]
179
+ a = A
180
+ b = B.args[0]
181
+ c = Mul(*B.args[1:])
182
+ comm1 = Commutator(a, b)
183
+ comm2 = Commutator(a, c)
184
+ if isinstance(comm1, Commutator):
185
+ comm1 = comm1._eval_expand_commutator()
186
+ if isinstance(comm2, Commutator):
187
+ comm2 = comm2._eval_expand_commutator()
188
+ first = Mul(comm1, c)
189
+ second = Mul(b, comm2)
190
+ return Add(first, second)
191
+ elif isinstance(A, Pow):
192
+ # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
193
+ return self._expand_pow(A, B, 1)
194
+ elif isinstance(B, Pow):
195
+ # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
196
+ return self._expand_pow(B, A, -1)
197
+
198
+ # No changes, so return self
199
+ return self
200
+
201
+ def doit(self, **hints):
202
+ """ Evaluate commutator """
203
+ A = self.args[0]
204
+ B = self.args[1]
205
+ if isinstance(A, Operator) and isinstance(B, Operator):
206
+ try:
207
+ comm = A._eval_commutator(B, **hints)
208
+ except NotImplementedError:
209
+ try:
210
+ comm = -1*B._eval_commutator(A, **hints)
211
+ except NotImplementedError:
212
+ comm = None
213
+ if comm is not None:
214
+ return comm.doit(**hints)
215
+ return (A*B - B*A).doit(**hints)
216
+
217
+ def _eval_adjoint(self):
218
+ return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
219
+
220
+ def _sympyrepr(self, printer, *args):
221
+ return "%s(%s,%s)" % (
222
+ self.__class__.__name__, printer._print(
223
+ self.args[0]), printer._print(self.args[1])
224
+ )
225
+
226
+ def _sympystr(self, printer, *args):
227
+ return "[%s,%s]" % (
228
+ printer._print(self.args[0]), printer._print(self.args[1]))
229
+
230
+ def _pretty(self, printer, *args):
231
+ pform = printer._print(self.args[0], *args)
232
+ pform = prettyForm(*pform.right(prettyForm(',')))
233
+ pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
234
+ pform = prettyForm(*pform.parens(left='[', right=']'))
235
+ return pform
236
+
237
+ def _latex(self, printer, *args):
238
+ return "\\left[%s,%s\\right]" % tuple([
239
+ printer._print(arg, *args) for arg in self.args])
janus/lib/python3.10/site-packages/sympy/physics/quantum/gate.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An implementation of gates that act on qubits.
2
+
3
+ Gates are unitary operators that act on the space of qubits.
4
+
5
+ Medium Term Todo:
6
+
7
+ * Optimize Gate._apply_operators_Qubit to remove the creation of many
8
+ intermediate Qubit objects.
9
+ * Add commutation relationships to all operators and use this in gate_sort.
10
+ * Fix gate_sort and gate_simp.
11
+ * Get multi-target UGates plotting properly.
12
+ * Get UGate to work with either sympy/numpy matrices and output either
13
+ format. This should also use the matrix slots.
14
+ """
15
+
16
+ from itertools import chain
17
+ import random
18
+
19
+ from sympy.core.add import Add
20
+ from sympy.core.containers import Tuple
21
+ from sympy.core.mul import Mul
22
+ from sympy.core.numbers import (I, Integer)
23
+ from sympy.core.power import Pow
24
+ from sympy.core.numbers import Number
25
+ from sympy.core.singleton import S as _S
26
+ from sympy.core.sorting import default_sort_key
27
+ from sympy.core.sympify import _sympify
28
+ from sympy.functions.elementary.miscellaneous import sqrt
29
+ from sympy.printing.pretty.stringpict import prettyForm, stringPict
30
+
31
+ from sympy.physics.quantum.anticommutator import AntiCommutator
32
+ from sympy.physics.quantum.commutator import Commutator
33
+ from sympy.physics.quantum.qexpr import QuantumError
34
+ from sympy.physics.quantum.hilbert import ComplexSpace
35
+ from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
36
+ HermitianOperator)
37
+ from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
38
+ from sympy.physics.quantum.matrixcache import matrix_cache
39
+
40
+ from sympy.matrices.matrixbase import MatrixBase
41
+
42
+ from sympy.utilities.iterables import is_sequence
43
+
44
+ __all__ = [
45
+ 'Gate',
46
+ 'CGate',
47
+ 'UGate',
48
+ 'OneQubitGate',
49
+ 'TwoQubitGate',
50
+ 'IdentityGate',
51
+ 'HadamardGate',
52
+ 'XGate',
53
+ 'YGate',
54
+ 'ZGate',
55
+ 'TGate',
56
+ 'PhaseGate',
57
+ 'SwapGate',
58
+ 'CNotGate',
59
+ # Aliased gate names
60
+ 'CNOT',
61
+ 'SWAP',
62
+ 'H',
63
+ 'X',
64
+ 'Y',
65
+ 'Z',
66
+ 'T',
67
+ 'S',
68
+ 'Phase',
69
+ 'normalized',
70
+ 'gate_sort',
71
+ 'gate_simp',
72
+ 'random_circuit',
73
+ 'CPHASE',
74
+ 'CGateS',
75
+ ]
76
+
77
+ #-----------------------------------------------------------------------------
78
+ # Gate Super-Classes
79
+ #-----------------------------------------------------------------------------
80
+
81
+ _normalized = True
82
+
83
+
84
+ def _max(*args, **kwargs):
85
+ if "key" not in kwargs:
86
+ kwargs["key"] = default_sort_key
87
+ return max(*args, **kwargs)
88
+
89
+
90
+ def _min(*args, **kwargs):
91
+ if "key" not in kwargs:
92
+ kwargs["key"] = default_sort_key
93
+ return min(*args, **kwargs)
94
+
95
+
96
+ def normalized(normalize):
97
+ r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
98
+
99
+ This is a global setting that can be used to simplify the look of various
100
+ expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
101
+
102
+ Parameters
103
+ ----------
104
+ normalize : bool
105
+ Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
106
+ When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
107
+ Hadamard gate will not have this factor.
108
+ """
109
+ global _normalized
110
+ _normalized = normalize
111
+
112
+
113
+ def _validate_targets_controls(tandc):
114
+ tandc = list(tandc)
115
+ # Check for integers
116
+ for bit in tandc:
117
+ if not bit.is_Integer and not bit.is_Symbol:
118
+ raise TypeError('Integer expected, got: %r' % tandc[bit])
119
+ # Detect duplicates
120
+ if len(set(tandc)) != len(tandc):
121
+ raise QuantumError(
122
+ 'Target/control qubits in a gate cannot be duplicated'
123
+ )
124
+
125
+
126
+ class Gate(UnitaryOperator):
127
+ """Non-controlled unitary gate operator that acts on qubits.
128
+
129
+ This is a general abstract gate that needs to be subclassed to do anything
130
+ useful.
131
+
132
+ Parameters
133
+ ----------
134
+ label : tuple, int
135
+ A list of the target qubits (as ints) that the gate will apply to.
136
+
137
+ Examples
138
+ ========
139
+
140
+
141
+ """
142
+
143
+ _label_separator = ','
144
+
145
+ gate_name = 'G'
146
+ gate_name_latex = 'G'
147
+
148
+ #-------------------------------------------------------------------------
149
+ # Initialization/creation
150
+ #-------------------------------------------------------------------------
151
+
152
+ @classmethod
153
+ def _eval_args(cls, args):
154
+ args = Tuple(*UnitaryOperator._eval_args(args))
155
+ _validate_targets_controls(args)
156
+ return args
157
+
158
+ @classmethod
159
+ def _eval_hilbert_space(cls, args):
160
+ """This returns the smallest possible Hilbert space."""
161
+ return ComplexSpace(2)**(_max(args) + 1)
162
+
163
+ #-------------------------------------------------------------------------
164
+ # Properties
165
+ #-------------------------------------------------------------------------
166
+
167
+ @property
168
+ def nqubits(self):
169
+ """The total number of qubits this gate acts on.
170
+
171
+ For controlled gate subclasses this includes both target and control
172
+ qubits, so that, for examples the CNOT gate acts on 2 qubits.
173
+ """
174
+ return len(self.targets)
175
+
176
+ @property
177
+ def min_qubits(self):
178
+ """The minimum number of qubits this gate needs to act on."""
179
+ return _max(self.targets) + 1
180
+
181
+ @property
182
+ def targets(self):
183
+ """A tuple of target qubits."""
184
+ return self.label
185
+
186
+ @property
187
+ def gate_name_plot(self):
188
+ return r'$%s$' % self.gate_name_latex
189
+
190
+ #-------------------------------------------------------------------------
191
+ # Gate methods
192
+ #-------------------------------------------------------------------------
193
+
194
+ def get_target_matrix(self, format='sympy'):
195
+ """The matrix representation of the target part of the gate.
196
+
197
+ Parameters
198
+ ----------
199
+ format : str
200
+ The format string ('sympy','numpy', etc.)
201
+ """
202
+ raise NotImplementedError(
203
+ 'get_target_matrix is not implemented in Gate.')
204
+
205
+ #-------------------------------------------------------------------------
206
+ # Apply
207
+ #-------------------------------------------------------------------------
208
+
209
+ def _apply_operator_IntQubit(self, qubits, **options):
210
+ """Redirect an apply from IntQubit to Qubit"""
211
+ return self._apply_operator_Qubit(qubits, **options)
212
+
213
+ def _apply_operator_Qubit(self, qubits, **options):
214
+ """Apply this gate to a Qubit."""
215
+
216
+ # Check number of qubits this gate acts on.
217
+ if qubits.nqubits < self.min_qubits:
218
+ raise QuantumError(
219
+ 'Gate needs a minimum of %r qubits to act on, got: %r' %
220
+ (self.min_qubits, qubits.nqubits)
221
+ )
222
+
223
+ # If the controls are not met, just return
224
+ if isinstance(self, CGate):
225
+ if not self.eval_controls(qubits):
226
+ return qubits
227
+
228
+ targets = self.targets
229
+ target_matrix = self.get_target_matrix(format='sympy')
230
+
231
+ # Find which column of the target matrix this applies to.
232
+ column_index = 0
233
+ n = 1
234
+ for target in targets:
235
+ column_index += n*qubits[target]
236
+ n = n << 1
237
+ column = target_matrix[:, int(column_index)]
238
+
239
+ # Now apply each column element to the qubit.
240
+ result = 0
241
+ for index in range(column.rows):
242
+ # TODO: This can be optimized to reduce the number of Qubit
243
+ # creations. We should simply manipulate the raw list of qubit
244
+ # values and then build the new Qubit object once.
245
+ # Make a copy of the incoming qubits.
246
+ new_qubit = qubits.__class__(*qubits.args)
247
+ # Flip the bits that need to be flipped.
248
+ for bit, target in enumerate(targets):
249
+ if new_qubit[target] != (index >> bit) & 1:
250
+ new_qubit = new_qubit.flip(target)
251
+ # The value in that row and column times the flipped-bit qubit
252
+ # is the result for that part.
253
+ result += column[index]*new_qubit
254
+ return result
255
+
256
+ #-------------------------------------------------------------------------
257
+ # Represent
258
+ #-------------------------------------------------------------------------
259
+
260
+ def _represent_default_basis(self, **options):
261
+ return self._represent_ZGate(None, **options)
262
+
263
+ def _represent_ZGate(self, basis, **options):
264
+ format = options.get('format', 'sympy')
265
+ nqubits = options.get('nqubits', 0)
266
+ if nqubits == 0:
267
+ raise QuantumError(
268
+ 'The number of qubits must be given as nqubits.')
269
+
270
+ # Make sure we have enough qubits for the gate.
271
+ if nqubits < self.min_qubits:
272
+ raise QuantumError(
273
+ 'The number of qubits %r is too small for the gate.' % nqubits
274
+ )
275
+
276
+ target_matrix = self.get_target_matrix(format)
277
+ targets = self.targets
278
+ if isinstance(self, CGate):
279
+ controls = self.controls
280
+ else:
281
+ controls = []
282
+ m = represent_zbasis(
283
+ controls, targets, target_matrix, nqubits, format
284
+ )
285
+ return m
286
+
287
+ #-------------------------------------------------------------------------
288
+ # Print methods
289
+ #-------------------------------------------------------------------------
290
+
291
+ def _sympystr(self, printer, *args):
292
+ label = self._print_label(printer, *args)
293
+ return '%s(%s)' % (self.gate_name, label)
294
+
295
+ def _pretty(self, printer, *args):
296
+ a = stringPict(self.gate_name)
297
+ b = self._print_label_pretty(printer, *args)
298
+ return self._print_subscript_pretty(a, b)
299
+
300
+ def _latex(self, printer, *args):
301
+ label = self._print_label(printer, *args)
302
+ return '%s_{%s}' % (self.gate_name_latex, label)
303
+
304
+ def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
305
+ raise NotImplementedError('plot_gate is not implemented.')
306
+
307
+
308
+ class CGate(Gate):
309
+ """A general unitary gate with control qubits.
310
+
311
+ A general control gate applies a target gate to a set of targets if all
312
+ of the control qubits have a particular values (set by
313
+ ``CGate.control_value``).
314
+
315
+ Parameters
316
+ ----------
317
+ label : tuple
318
+ The label in this case has the form (controls, gate), where controls
319
+ is a tuple/list of control qubits (as ints) and gate is a ``Gate``
320
+ instance that is the target operator.
321
+
322
+ Examples
323
+ ========
324
+
325
+ """
326
+
327
+ gate_name = 'C'
328
+ gate_name_latex = 'C'
329
+
330
+ # The values this class controls for.
331
+ control_value = _S.One
332
+
333
+ simplify_cgate = False
334
+
335
+ #-------------------------------------------------------------------------
336
+ # Initialization
337
+ #-------------------------------------------------------------------------
338
+
339
+ @classmethod
340
+ def _eval_args(cls, args):
341
+ # _eval_args has the right logic for the controls argument.
342
+ controls = args[0]
343
+ gate = args[1]
344
+ if not is_sequence(controls):
345
+ controls = (controls,)
346
+ controls = UnitaryOperator._eval_args(controls)
347
+ _validate_targets_controls(chain(controls, gate.targets))
348
+ return (Tuple(*controls), gate)
349
+
350
+ @classmethod
351
+ def _eval_hilbert_space(cls, args):
352
+ """This returns the smallest possible Hilbert space."""
353
+ return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
354
+
355
+ #-------------------------------------------------------------------------
356
+ # Properties
357
+ #-------------------------------------------------------------------------
358
+
359
+ @property
360
+ def nqubits(self):
361
+ """The total number of qubits this gate acts on.
362
+
363
+ For controlled gate subclasses this includes both target and control
364
+ qubits, so that, for examples the CNOT gate acts on 2 qubits.
365
+ """
366
+ return len(self.targets) + len(self.controls)
367
+
368
+ @property
369
+ def min_qubits(self):
370
+ """The minimum number of qubits this gate needs to act on."""
371
+ return _max(_max(self.controls), _max(self.targets)) + 1
372
+
373
+ @property
374
+ def targets(self):
375
+ """A tuple of target qubits."""
376
+ return self.gate.targets
377
+
378
+ @property
379
+ def controls(self):
380
+ """A tuple of control qubits."""
381
+ return tuple(self.label[0])
382
+
383
+ @property
384
+ def gate(self):
385
+ """The non-controlled gate that will be applied to the targets."""
386
+ return self.label[1]
387
+
388
+ #-------------------------------------------------------------------------
389
+ # Gate methods
390
+ #-------------------------------------------------------------------------
391
+
392
+ def get_target_matrix(self, format='sympy'):
393
+ return self.gate.get_target_matrix(format)
394
+
395
+ def eval_controls(self, qubit):
396
+ """Return True/False to indicate if the controls are satisfied."""
397
+ return all(qubit[bit] == self.control_value for bit in self.controls)
398
+
399
+ def decompose(self, **options):
400
+ """Decompose the controlled gate into CNOT and single qubits gates."""
401
+ if len(self.controls) == 1:
402
+ c = self.controls[0]
403
+ t = self.gate.targets[0]
404
+ if isinstance(self.gate, YGate):
405
+ g1 = PhaseGate(t)
406
+ g2 = CNotGate(c, t)
407
+ g3 = PhaseGate(t)
408
+ g4 = ZGate(t)
409
+ return g1*g2*g3*g4
410
+ if isinstance(self.gate, ZGate):
411
+ g1 = HadamardGate(t)
412
+ g2 = CNotGate(c, t)
413
+ g3 = HadamardGate(t)
414
+ return g1*g2*g3
415
+ else:
416
+ return self
417
+
418
+ #-------------------------------------------------------------------------
419
+ # Print methods
420
+ #-------------------------------------------------------------------------
421
+
422
+ def _print_label(self, printer, *args):
423
+ controls = self._print_sequence(self.controls, ',', printer, *args)
424
+ gate = printer._print(self.gate, *args)
425
+ return '(%s),%s' % (controls, gate)
426
+
427
+ def _pretty(self, printer, *args):
428
+ controls = self._print_sequence_pretty(
429
+ self.controls, ',', printer, *args)
430
+ gate = printer._print(self.gate)
431
+ gate_name = stringPict(self.gate_name)
432
+ first = self._print_subscript_pretty(gate_name, controls)
433
+ gate = self._print_parens_pretty(gate)
434
+ final = prettyForm(*first.right(gate))
435
+ return final
436
+
437
+ def _latex(self, printer, *args):
438
+ controls = self._print_sequence(self.controls, ',', printer, *args)
439
+ gate = printer._print(self.gate, *args)
440
+ return r'%s_{%s}{\left(%s\right)}' % \
441
+ (self.gate_name_latex, controls, gate)
442
+
443
+ def plot_gate(self, circ_plot, gate_idx):
444
+ """
445
+ Plot the controlled gate. If *simplify_cgate* is true, simplify
446
+ C-X and C-Z gates into their more familiar forms.
447
+ """
448
+ min_wire = int(_min(chain(self.controls, self.targets)))
449
+ max_wire = int(_max(chain(self.controls, self.targets)))
450
+ circ_plot.control_line(gate_idx, min_wire, max_wire)
451
+ for c in self.controls:
452
+ circ_plot.control_point(gate_idx, int(c))
453
+ if self.simplify_cgate:
454
+ if self.gate.gate_name == 'X':
455
+ self.gate.plot_gate_plus(circ_plot, gate_idx)
456
+ elif self.gate.gate_name == 'Z':
457
+ circ_plot.control_point(gate_idx, self.targets[0])
458
+ else:
459
+ self.gate.plot_gate(circ_plot, gate_idx)
460
+ else:
461
+ self.gate.plot_gate(circ_plot, gate_idx)
462
+
463
+ #-------------------------------------------------------------------------
464
+ # Miscellaneous
465
+ #-------------------------------------------------------------------------
466
+
467
+ def _eval_dagger(self):
468
+ if isinstance(self.gate, HermitianOperator):
469
+ return self
470
+ else:
471
+ return Gate._eval_dagger(self)
472
+
473
+ def _eval_inverse(self):
474
+ if isinstance(self.gate, HermitianOperator):
475
+ return self
476
+ else:
477
+ return Gate._eval_inverse(self)
478
+
479
+ def _eval_power(self, exp):
480
+ if isinstance(self.gate, HermitianOperator):
481
+ if exp == -1:
482
+ return Gate._eval_power(self, exp)
483
+ elif abs(exp) % 2 == 0:
484
+ return self*(Gate._eval_inverse(self))
485
+ else:
486
+ return self
487
+ else:
488
+ return Gate._eval_power(self, exp)
489
+
490
+ class CGateS(CGate):
491
+ """Version of CGate that allows gate simplifications.
492
+ I.e. cnot looks like an oplus, cphase has dots, etc.
493
+ """
494
+ simplify_cgate=True
495
+
496
+
497
+ class UGate(Gate):
498
+ """General gate specified by a set of targets and a target matrix.
499
+
500
+ Parameters
501
+ ----------
502
+ label : tuple
503
+ A tuple of the form (targets, U), where targets is a tuple of the
504
+ target qubits and U is a unitary matrix with dimension of
505
+ len(targets).
506
+ """
507
+ gate_name = 'U'
508
+ gate_name_latex = 'U'
509
+
510
+ #-------------------------------------------------------------------------
511
+ # Initialization
512
+ #-------------------------------------------------------------------------
513
+
514
+ @classmethod
515
+ def _eval_args(cls, args):
516
+ targets = args[0]
517
+ if not is_sequence(targets):
518
+ targets = (targets,)
519
+ targets = Gate._eval_args(targets)
520
+ _validate_targets_controls(targets)
521
+ mat = args[1]
522
+ if not isinstance(mat, MatrixBase):
523
+ raise TypeError('Matrix expected, got: %r' % mat)
524
+ #make sure this matrix is of a Basic type
525
+ mat = _sympify(mat)
526
+ dim = 2**len(targets)
527
+ if not all(dim == shape for shape in mat.shape):
528
+ raise IndexError(
529
+ 'Number of targets must match the matrix size: %r %r' %
530
+ (targets, mat)
531
+ )
532
+ return (targets, mat)
533
+
534
+ @classmethod
535
+ def _eval_hilbert_space(cls, args):
536
+ """This returns the smallest possible Hilbert space."""
537
+ return ComplexSpace(2)**(_max(args[0]) + 1)
538
+
539
+ #-------------------------------------------------------------------------
540
+ # Properties
541
+ #-------------------------------------------------------------------------
542
+
543
+ @property
544
+ def targets(self):
545
+ """A tuple of target qubits."""
546
+ return tuple(self.label[0])
547
+
548
+ #-------------------------------------------------------------------------
549
+ # Gate methods
550
+ #-------------------------------------------------------------------------
551
+
552
+ def get_target_matrix(self, format='sympy'):
553
+ """The matrix rep. of the target part of the gate.
554
+
555
+ Parameters
556
+ ----------
557
+ format : str
558
+ The format string ('sympy','numpy', etc.)
559
+ """
560
+ return self.label[1]
561
+
562
+ #-------------------------------------------------------------------------
563
+ # Print methods
564
+ #-------------------------------------------------------------------------
565
+ def _pretty(self, printer, *args):
566
+ targets = self._print_sequence_pretty(
567
+ self.targets, ',', printer, *args)
568
+ gate_name = stringPict(self.gate_name)
569
+ return self._print_subscript_pretty(gate_name, targets)
570
+
571
+ def _latex(self, printer, *args):
572
+ targets = self._print_sequence(self.targets, ',', printer, *args)
573
+ return r'%s_{%s}' % (self.gate_name_latex, targets)
574
+
575
+ def plot_gate(self, circ_plot, gate_idx):
576
+ circ_plot.one_qubit_box(
577
+ self.gate_name_plot,
578
+ gate_idx, int(self.targets[0])
579
+ )
580
+
581
+
582
+ class OneQubitGate(Gate):
583
+ """A single qubit unitary gate base class."""
584
+
585
+ nqubits = _S.One
586
+
587
+ def plot_gate(self, circ_plot, gate_idx):
588
+ circ_plot.one_qubit_box(
589
+ self.gate_name_plot,
590
+ gate_idx, int(self.targets[0])
591
+ )
592
+
593
+ def _eval_commutator(self, other, **hints):
594
+ if isinstance(other, OneQubitGate):
595
+ if self.targets != other.targets or self.__class__ == other.__class__:
596
+ return _S.Zero
597
+ return Operator._eval_commutator(self, other, **hints)
598
+
599
+ def _eval_anticommutator(self, other, **hints):
600
+ if isinstance(other, OneQubitGate):
601
+ if self.targets != other.targets or self.__class__ == other.__class__:
602
+ return Integer(2)*self*other
603
+ return Operator._eval_anticommutator(self, other, **hints)
604
+
605
+
606
+ class TwoQubitGate(Gate):
607
+ """A two qubit unitary gate base class."""
608
+
609
+ nqubits = Integer(2)
610
+
611
+ #-----------------------------------------------------------------------------
612
+ # Single Qubit Gates
613
+ #-----------------------------------------------------------------------------
614
+
615
+
616
+ class IdentityGate(OneQubitGate):
617
+ """The single qubit identity gate.
618
+
619
+ Parameters
620
+ ----------
621
+ target : int
622
+ The target qubit this gate will apply to.
623
+
624
+ Examples
625
+ ========
626
+
627
+ """
628
+ is_hermitian = True
629
+ gate_name = '1'
630
+ gate_name_latex = '1'
631
+
632
+ # Short cut version of gate._apply_operator_Qubit
633
+ def _apply_operator_Qubit(self, qubits, **options):
634
+ # Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
635
+ if qubits.nqubits < self.min_qubits:
636
+ raise QuantumError(
637
+ 'Gate needs a minimum of %r qubits to act on, got: %r' %
638
+ (self.min_qubits, qubits.nqubits)
639
+ )
640
+ return qubits # no computation required for IdentityGate
641
+
642
+ def get_target_matrix(self, format='sympy'):
643
+ return matrix_cache.get_matrix('eye2', format)
644
+
645
+ def _eval_commutator(self, other, **hints):
646
+ return _S.Zero
647
+
648
+ def _eval_anticommutator(self, other, **hints):
649
+ return Integer(2)*other
650
+
651
+
652
+ class HadamardGate(HermitianOperator, OneQubitGate):
653
+ """The single qubit Hadamard gate.
654
+
655
+ Parameters
656
+ ----------
657
+ target : int
658
+ The target qubit this gate will apply to.
659
+
660
+ Examples
661
+ ========
662
+
663
+ >>> from sympy import sqrt
664
+ >>> from sympy.physics.quantum.qubit import Qubit
665
+ >>> from sympy.physics.quantum.gate import HadamardGate
666
+ >>> from sympy.physics.quantum.qapply import qapply
667
+ >>> qapply(HadamardGate(0)*Qubit('1'))
668
+ sqrt(2)*|0>/2 - sqrt(2)*|1>/2
669
+ >>> # Hadamard on bell state, applied on 2 qubits.
670
+ >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
671
+ >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
672
+ sqrt(2)*|00>/2 + sqrt(2)*|11>/2
673
+
674
+ """
675
+ gate_name = 'H'
676
+ gate_name_latex = 'H'
677
+
678
+ def get_target_matrix(self, format='sympy'):
679
+ if _normalized:
680
+ return matrix_cache.get_matrix('H', format)
681
+ else:
682
+ return matrix_cache.get_matrix('Hsqrt2', format)
683
+
684
+ def _eval_commutator_XGate(self, other, **hints):
685
+ return I*sqrt(2)*YGate(self.targets[0])
686
+
687
+ def _eval_commutator_YGate(self, other, **hints):
688
+ return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
689
+
690
+ def _eval_commutator_ZGate(self, other, **hints):
691
+ return -I*sqrt(2)*YGate(self.targets[0])
692
+
693
+ def _eval_anticommutator_XGate(self, other, **hints):
694
+ return sqrt(2)*IdentityGate(self.targets[0])
695
+
696
+ def _eval_anticommutator_YGate(self, other, **hints):
697
+ return _S.Zero
698
+
699
+ def _eval_anticommutator_ZGate(self, other, **hints):
700
+ return sqrt(2)*IdentityGate(self.targets[0])
701
+
702
+
703
+ class XGate(HermitianOperator, OneQubitGate):
704
+ """The single qubit X, or NOT, gate.
705
+
706
+ Parameters
707
+ ----------
708
+ target : int
709
+ The target qubit this gate will apply to.
710
+
711
+ Examples
712
+ ========
713
+
714
+ """
715
+ gate_name = 'X'
716
+ gate_name_latex = 'X'
717
+
718
+ def get_target_matrix(self, format='sympy'):
719
+ return matrix_cache.get_matrix('X', format)
720
+
721
+ def plot_gate(self, circ_plot, gate_idx):
722
+ OneQubitGate.plot_gate(self,circ_plot,gate_idx)
723
+
724
+ def plot_gate_plus(self, circ_plot, gate_idx):
725
+ circ_plot.not_point(
726
+ gate_idx, int(self.label[0])
727
+ )
728
+
729
+ def _eval_commutator_YGate(self, other, **hints):
730
+ return Integer(2)*I*ZGate(self.targets[0])
731
+
732
+ def _eval_anticommutator_XGate(self, other, **hints):
733
+ return Integer(2)*IdentityGate(self.targets[0])
734
+
735
+ def _eval_anticommutator_YGate(self, other, **hints):
736
+ return _S.Zero
737
+
738
+ def _eval_anticommutator_ZGate(self, other, **hints):
739
+ return _S.Zero
740
+
741
+
742
+ class YGate(HermitianOperator, OneQubitGate):
743
+ """The single qubit Y gate.
744
+
745
+ Parameters
746
+ ----------
747
+ target : int
748
+ The target qubit this gate will apply to.
749
+
750
+ Examples
751
+ ========
752
+
753
+ """
754
+ gate_name = 'Y'
755
+ gate_name_latex = 'Y'
756
+
757
+ def get_target_matrix(self, format='sympy'):
758
+ return matrix_cache.get_matrix('Y', format)
759
+
760
+ def _eval_commutator_ZGate(self, other, **hints):
761
+ return Integer(2)*I*XGate(self.targets[0])
762
+
763
+ def _eval_anticommutator_YGate(self, other, **hints):
764
+ return Integer(2)*IdentityGate(self.targets[0])
765
+
766
+ def _eval_anticommutator_ZGate(self, other, **hints):
767
+ return _S.Zero
768
+
769
+
770
+ class ZGate(HermitianOperator, OneQubitGate):
771
+ """The single qubit Z gate.
772
+
773
+ Parameters
774
+ ----------
775
+ target : int
776
+ The target qubit this gate will apply to.
777
+
778
+ Examples
779
+ ========
780
+
781
+ """
782
+ gate_name = 'Z'
783
+ gate_name_latex = 'Z'
784
+
785
+ def get_target_matrix(self, format='sympy'):
786
+ return matrix_cache.get_matrix('Z', format)
787
+
788
+ def _eval_commutator_XGate(self, other, **hints):
789
+ return Integer(2)*I*YGate(self.targets[0])
790
+
791
+ def _eval_anticommutator_YGate(self, other, **hints):
792
+ return _S.Zero
793
+
794
+
795
+ class PhaseGate(OneQubitGate):
796
+ """The single qubit phase, or S, gate.
797
+
798
+ This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
799
+ does nothing if the state is ``|0>``.
800
+
801
+ Parameters
802
+ ----------
803
+ target : int
804
+ The target qubit this gate will apply to.
805
+
806
+ Examples
807
+ ========
808
+
809
+ """
810
+ is_hermitian = False
811
+ gate_name = 'S'
812
+ gate_name_latex = 'S'
813
+
814
+ def get_target_matrix(self, format='sympy'):
815
+ return matrix_cache.get_matrix('S', format)
816
+
817
+ def _eval_commutator_ZGate(self, other, **hints):
818
+ return _S.Zero
819
+
820
+ def _eval_commutator_TGate(self, other, **hints):
821
+ return _S.Zero
822
+
823
+
824
+ class TGate(OneQubitGate):
825
+ """The single qubit pi/8 gate.
826
+
827
+ This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
828
+ does nothing if the state is ``|0>``.
829
+
830
+ Parameters
831
+ ----------
832
+ target : int
833
+ The target qubit this gate will apply to.
834
+
835
+ Examples
836
+ ========
837
+
838
+ """
839
+ is_hermitian = False
840
+ gate_name = 'T'
841
+ gate_name_latex = 'T'
842
+
843
+ def get_target_matrix(self, format='sympy'):
844
+ return matrix_cache.get_matrix('T', format)
845
+
846
+ def _eval_commutator_ZGate(self, other, **hints):
847
+ return _S.Zero
848
+
849
+ def _eval_commutator_PhaseGate(self, other, **hints):
850
+ return _S.Zero
851
+
852
+
853
+ # Aliases for gate names.
854
+ H = HadamardGate
855
+ X = XGate
856
+ Y = YGate
857
+ Z = ZGate
858
+ T = TGate
859
+ Phase = S = PhaseGate
860
+
861
+
862
+ #-----------------------------------------------------------------------------
863
+ # 2 Qubit Gates
864
+ #-----------------------------------------------------------------------------
865
+
866
+
867
+ class CNotGate(HermitianOperator, CGate, TwoQubitGate):
868
+ """Two qubit controlled-NOT.
869
+
870
+ This gate performs the NOT or X gate on the target qubit if the control
871
+ qubits all have the value 1.
872
+
873
+ Parameters
874
+ ----------
875
+ label : tuple
876
+ A tuple of the form (control, target).
877
+
878
+ Examples
879
+ ========
880
+
881
+ >>> from sympy.physics.quantum.gate import CNOT
882
+ >>> from sympy.physics.quantum.qapply import qapply
883
+ >>> from sympy.physics.quantum.qubit import Qubit
884
+ >>> c = CNOT(1,0)
885
+ >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
886
+ |11>
887
+
888
+ """
889
+ gate_name = 'CNOT'
890
+ gate_name_latex = r'\text{CNOT}'
891
+ simplify_cgate = True
892
+
893
+ #-------------------------------------------------------------------------
894
+ # Initialization
895
+ #-------------------------------------------------------------------------
896
+
897
+ @classmethod
898
+ def _eval_args(cls, args):
899
+ args = Gate._eval_args(args)
900
+ return args
901
+
902
+ @classmethod
903
+ def _eval_hilbert_space(cls, args):
904
+ """This returns the smallest possible Hilbert space."""
905
+ return ComplexSpace(2)**(_max(args) + 1)
906
+
907
+ #-------------------------------------------------------------------------
908
+ # Properties
909
+ #-------------------------------------------------------------------------
910
+
911
+ @property
912
+ def min_qubits(self):
913
+ """The minimum number of qubits this gate needs to act on."""
914
+ return _max(self.label) + 1
915
+
916
+ @property
917
+ def targets(self):
918
+ """A tuple of target qubits."""
919
+ return (self.label[1],)
920
+
921
+ @property
922
+ def controls(self):
923
+ """A tuple of control qubits."""
924
+ return (self.label[0],)
925
+
926
+ @property
927
+ def gate(self):
928
+ """The non-controlled gate that will be applied to the targets."""
929
+ return XGate(self.label[1])
930
+
931
+ #-------------------------------------------------------------------------
932
+ # Properties
933
+ #-------------------------------------------------------------------------
934
+
935
+ # The default printing of Gate works better than those of CGate, so we
936
+ # go around the overridden methods in CGate.
937
+
938
+ def _print_label(self, printer, *args):
939
+ return Gate._print_label(self, printer, *args)
940
+
941
+ def _pretty(self, printer, *args):
942
+ return Gate._pretty(self, printer, *args)
943
+
944
+ def _latex(self, printer, *args):
945
+ return Gate._latex(self, printer, *args)
946
+
947
+ #-------------------------------------------------------------------------
948
+ # Commutator/AntiCommutator
949
+ #-------------------------------------------------------------------------
950
+
951
+ def _eval_commutator_ZGate(self, other, **hints):
952
+ """[CNOT(i, j), Z(i)] == 0."""
953
+ if self.controls[0] == other.targets[0]:
954
+ return _S.Zero
955
+ else:
956
+ raise NotImplementedError('Commutator not implemented: %r' % other)
957
+
958
+ def _eval_commutator_TGate(self, other, **hints):
959
+ """[CNOT(i, j), T(i)] == 0."""
960
+ return self._eval_commutator_ZGate(other, **hints)
961
+
962
+ def _eval_commutator_PhaseGate(self, other, **hints):
963
+ """[CNOT(i, j), S(i)] == 0."""
964
+ return self._eval_commutator_ZGate(other, **hints)
965
+
966
+ def _eval_commutator_XGate(self, other, **hints):
967
+ """[CNOT(i, j), X(j)] == 0."""
968
+ if self.targets[0] == other.targets[0]:
969
+ return _S.Zero
970
+ else:
971
+ raise NotImplementedError('Commutator not implemented: %r' % other)
972
+
973
+ def _eval_commutator_CNotGate(self, other, **hints):
974
+ """[CNOT(i, j), CNOT(i,k)] == 0."""
975
+ if self.controls[0] == other.controls[0]:
976
+ return _S.Zero
977
+ else:
978
+ raise NotImplementedError('Commutator not implemented: %r' % other)
979
+
980
+
981
+ class SwapGate(TwoQubitGate):
982
+ """Two qubit SWAP gate.
983
+
984
+ This gate swap the values of the two qubits.
985
+
986
+ Parameters
987
+ ----------
988
+ label : tuple
989
+ A tuple of the form (target1, target2).
990
+
991
+ Examples
992
+ ========
993
+
994
+ """
995
+ is_hermitian = True
996
+ gate_name = 'SWAP'
997
+ gate_name_latex = r'\text{SWAP}'
998
+
999
+ def get_target_matrix(self, format='sympy'):
1000
+ return matrix_cache.get_matrix('SWAP', format)
1001
+
1002
+ def decompose(self, **options):
1003
+ """Decompose the SWAP gate into CNOT gates."""
1004
+ i, j = self.targets[0], self.targets[1]
1005
+ g1 = CNotGate(i, j)
1006
+ g2 = CNotGate(j, i)
1007
+ return g1*g2*g1
1008
+
1009
+ def plot_gate(self, circ_plot, gate_idx):
1010
+ min_wire = int(_min(self.targets))
1011
+ max_wire = int(_max(self.targets))
1012
+ circ_plot.control_line(gate_idx, min_wire, max_wire)
1013
+ circ_plot.swap_point(gate_idx, min_wire)
1014
+ circ_plot.swap_point(gate_idx, max_wire)
1015
+
1016
+ def _represent_ZGate(self, basis, **options):
1017
+ """Represent the SWAP gate in the computational basis.
1018
+
1019
+ The following representation is used to compute this:
1020
+
1021
+ SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
1022
+ """
1023
+ format = options.get('format', 'sympy')
1024
+ targets = [int(t) for t in self.targets]
1025
+ min_target = _min(targets)
1026
+ max_target = _max(targets)
1027
+ nqubits = options.get('nqubits', self.min_qubits)
1028
+
1029
+ op01 = matrix_cache.get_matrix('op01', format)
1030
+ op10 = matrix_cache.get_matrix('op10', format)
1031
+ op11 = matrix_cache.get_matrix('op11', format)
1032
+ op00 = matrix_cache.get_matrix('op00', format)
1033
+ eye2 = matrix_cache.get_matrix('eye2', format)
1034
+
1035
+ result = None
1036
+ for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
1037
+ product = nqubits*[eye2]
1038
+ product[nqubits - min_target - 1] = i
1039
+ product[nqubits - max_target - 1] = j
1040
+ new_result = matrix_tensor_product(*product)
1041
+ if result is None:
1042
+ result = new_result
1043
+ else:
1044
+ result = result + new_result
1045
+
1046
+ return result
1047
+
1048
+
1049
+ # Aliases for gate names.
1050
+ CNOT = CNotGate
1051
+ SWAP = SwapGate
1052
+ def CPHASE(a,b): return CGateS((a,),Z(b))
1053
+
1054
+
1055
+ #-----------------------------------------------------------------------------
1056
+ # Represent
1057
+ #-----------------------------------------------------------------------------
1058
+
1059
+
1060
+ def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
1061
+ """Represent a gate with controls, targets and target_matrix.
1062
+
1063
+ This function does the low-level work of representing gates as matrices
1064
+ in the standard computational basis (ZGate). Currently, we support two
1065
+ main cases:
1066
+
1067
+ 1. One target qubit and no control qubits.
1068
+ 2. One target qubits and multiple control qubits.
1069
+
1070
+ For the base of multiple controls, we use the following expression [1]:
1071
+
1072
+ 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
1073
+
1074
+ Parameters
1075
+ ----------
1076
+ controls : list, tuple
1077
+ A sequence of control qubits.
1078
+ targets : list, tuple
1079
+ A sequence of target qubits.
1080
+ target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
1081
+ The matrix form of the transformation to be performed on the target
1082
+ qubits. The format of this matrix must match that passed into
1083
+ the `format` argument.
1084
+ nqubits : int
1085
+ The total number of qubits used for the representation.
1086
+ format : str
1087
+ The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
1088
+
1089
+ Examples
1090
+ ========
1091
+
1092
+ References
1093
+ ----------
1094
+ [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
1095
+ """
1096
+ controls = [int(x) for x in controls]
1097
+ targets = [int(x) for x in targets]
1098
+ nqubits = int(nqubits)
1099
+
1100
+ # This checks for the format as well.
1101
+ op11 = matrix_cache.get_matrix('op11', format)
1102
+ eye2 = matrix_cache.get_matrix('eye2', format)
1103
+
1104
+ # Plain single qubit case
1105
+ if len(controls) == 0 and len(targets) == 1:
1106
+ product = []
1107
+ bit = targets[0]
1108
+ # Fill product with [I1,Gate,I2] such that the unitaries,
1109
+ # I, cause the gate to be applied to the correct Qubit
1110
+ if bit != nqubits - 1:
1111
+ product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
1112
+ product.append(target_matrix)
1113
+ if bit != 0:
1114
+ product.append(matrix_eye(2**bit, format=format))
1115
+ return matrix_tensor_product(*product)
1116
+
1117
+ # Single target, multiple controls.
1118
+ elif len(targets) == 1 and len(controls) >= 1:
1119
+ target = targets[0]
1120
+
1121
+ # Build the non-trivial part.
1122
+ product2 = []
1123
+ for i in range(nqubits):
1124
+ product2.append(matrix_eye(2, format=format))
1125
+ for control in controls:
1126
+ product2[nqubits - 1 - control] = op11
1127
+ product2[nqubits - 1 - target] = target_matrix - eye2
1128
+
1129
+ return matrix_eye(2**nqubits, format=format) + \
1130
+ matrix_tensor_product(*product2)
1131
+
1132
+ # Multi-target, multi-control is not yet implemented.
1133
+ else:
1134
+ raise NotImplementedError(
1135
+ 'The representation of multi-target, multi-control gates '
1136
+ 'is not implemented.'
1137
+ )
1138
+
1139
+
1140
+ #-----------------------------------------------------------------------------
1141
+ # Gate manipulation functions.
1142
+ #-----------------------------------------------------------------------------
1143
+
1144
+
1145
+ def gate_simp(circuit):
1146
+ """Simplifies gates symbolically
1147
+
1148
+ It first sorts gates using gate_sort. It then applies basic
1149
+ simplification rules to the circuit, e.g., XGate**2 = Identity
1150
+ """
1151
+
1152
+ # Bubble sort out gates that commute.
1153
+ circuit = gate_sort(circuit)
1154
+
1155
+ # Do simplifications by subing a simplification into the first element
1156
+ # which can be simplified. We recursively call gate_simp with new circuit
1157
+ # as input more simplifications exist.
1158
+ if isinstance(circuit, Add):
1159
+ return sum(gate_simp(t) for t in circuit.args)
1160
+ elif isinstance(circuit, Mul):
1161
+ circuit_args = circuit.args
1162
+ elif isinstance(circuit, Pow):
1163
+ b, e = circuit.as_base_exp()
1164
+ circuit_args = (gate_simp(b)**e,)
1165
+ else:
1166
+ return circuit
1167
+
1168
+ # Iterate through each element in circuit, simplify if possible.
1169
+ for i in range(len(circuit_args)):
1170
+ # H,X,Y or Z squared is 1.
1171
+ # T**2 = S, S**2 = Z
1172
+ if isinstance(circuit_args[i], Pow):
1173
+ if isinstance(circuit_args[i].base,
1174
+ (HadamardGate, XGate, YGate, ZGate)) \
1175
+ and isinstance(circuit_args[i].exp, Number):
1176
+ # Build a new circuit taking replacing the
1177
+ # H,X,Y,Z squared with one.
1178
+ newargs = (circuit_args[:i] +
1179
+ (circuit_args[i].base**(circuit_args[i].exp % 2),) +
1180
+ circuit_args[i + 1:])
1181
+ # Recursively simplify the new circuit.
1182
+ circuit = gate_simp(Mul(*newargs))
1183
+ break
1184
+ elif isinstance(circuit_args[i].base, PhaseGate):
1185
+ # Build a new circuit taking old circuit but splicing
1186
+ # in simplification.
1187
+ newargs = circuit_args[:i]
1188
+ # Replace PhaseGate**2 with ZGate.
1189
+ newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
1190
+ (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
1191
+ (circuit_args[i].exp % 2))
1192
+ # Append the last elements.
1193
+ newargs = newargs + circuit_args[i + 1:]
1194
+ # Recursively simplify the new circuit.
1195
+ circuit = gate_simp(Mul(*newargs))
1196
+ break
1197
+ elif isinstance(circuit_args[i].base, TGate):
1198
+ # Build a new circuit taking all the old elements.
1199
+ newargs = circuit_args[:i]
1200
+
1201
+ # Put an Phasegate in place of any TGate**2.
1202
+ newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
1203
+ Integer(circuit_args[i].exp/2), circuit_args[i].base**
1204
+ (circuit_args[i].exp % 2))
1205
+
1206
+ # Append the last elements.
1207
+ newargs = newargs + circuit_args[i + 1:]
1208
+ # Recursively simplify the new circuit.
1209
+ circuit = gate_simp(Mul(*newargs))
1210
+ break
1211
+ return circuit
1212
+
1213
+
1214
+ def gate_sort(circuit):
1215
+ """Sorts the gates while keeping track of commutation relations
1216
+
1217
+ This function uses a bubble sort to rearrange the order of gate
1218
+ application. Keeps track of Quantum computations special commutation
1219
+ relations (e.g. things that apply to the same Qubit do not commute with
1220
+ each other)
1221
+
1222
+ circuit is the Mul of gates that are to be sorted.
1223
+ """
1224
+ # Make sure we have an Add or Mul.
1225
+ if isinstance(circuit, Add):
1226
+ return sum(gate_sort(t) for t in circuit.args)
1227
+ if isinstance(circuit, Pow):
1228
+ return gate_sort(circuit.base)**circuit.exp
1229
+ elif isinstance(circuit, Gate):
1230
+ return circuit
1231
+ if not isinstance(circuit, Mul):
1232
+ return circuit
1233
+
1234
+ changes = True
1235
+ while changes:
1236
+ changes = False
1237
+ circ_array = circuit.args
1238
+ for i in range(len(circ_array) - 1):
1239
+ # Go through each element and switch ones that are in wrong order
1240
+ if isinstance(circ_array[i], (Gate, Pow)) and \
1241
+ isinstance(circ_array[i + 1], (Gate, Pow)):
1242
+ # If we have a Pow object, look at only the base
1243
+ first_base, first_exp = circ_array[i].as_base_exp()
1244
+ second_base, second_exp = circ_array[i + 1].as_base_exp()
1245
+
1246
+ # Use SymPy's hash based sorting. This is not mathematical
1247
+ # sorting, but is rather based on comparing hashes of objects.
1248
+ # See Basic.compare for details.
1249
+ if first_base.compare(second_base) > 0:
1250
+ if Commutator(first_base, second_base).doit() == 0:
1251
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1252
+ (circuit.args[i],) + circuit.args[i + 2:])
1253
+ circuit = Mul(*new_args)
1254
+ changes = True
1255
+ break
1256
+ if AntiCommutator(first_base, second_base).doit() == 0:
1257
+ new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
1258
+ (circuit.args[i],) + circuit.args[i + 2:])
1259
+ sign = _S.NegativeOne**(first_exp*second_exp)
1260
+ circuit = sign*Mul(*new_args)
1261
+ changes = True
1262
+ break
1263
+ return circuit
1264
+
1265
+
1266
+ #-----------------------------------------------------------------------------
1267
+ # Utility functions
1268
+ #-----------------------------------------------------------------------------
1269
+
1270
+
1271
+ def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
1272
+ """Return a random circuit of ngates and nqubits.
1273
+
1274
+ This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
1275
+ gates.
1276
+
1277
+ Parameters
1278
+ ----------
1279
+ ngates : int
1280
+ The number of gates in the circuit.
1281
+ nqubits : int
1282
+ The number of qubits in the circuit.
1283
+ gate_space : tuple
1284
+ A tuple of the gate classes that will be used in the circuit.
1285
+ Repeating gate classes multiple times in this tuple will increase
1286
+ the frequency they appear in the random circuit.
1287
+ """
1288
+ qubit_space = range(nqubits)
1289
+ result = []
1290
+ for i in range(ngates):
1291
+ g = random.choice(gate_space)
1292
+ if g == CNotGate or g == SwapGate:
1293
+ qubits = random.sample(qubit_space, 2)
1294
+ g = g(*qubits)
1295
+ else:
1296
+ qubit = random.choice(qubit_space)
1297
+ g = g(qubit)
1298
+ result.append(g)
1299
+ return Mul(*result)
1300
+
1301
+
1302
+ def zx_basis_transform(self, format='sympy'):
1303
+ """Transformation matrix from Z to X basis."""
1304
+ return matrix_cache.get_matrix('ZX', format)
1305
+
1306
+
1307
+ def zy_basis_transform(self, format='sympy'):
1308
+ """Transformation matrix from Z to Y basis."""
1309
+ return matrix_cache.get_matrix('ZY', format)
janus/lib/python3.10/site-packages/sympy/physics/quantum/hilbert.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hilbert spaces for quantum mechanics.
2
+
3
+ Authors:
4
+ * Brian Granger
5
+ * Matt Curry
6
+ """
7
+
8
+ from functools import reduce
9
+
10
+ from sympy.core.basic import Basic
11
+ from sympy.core.singleton import S
12
+ from sympy.core.sympify import sympify
13
+ from sympy.sets.sets import Interval
14
+ from sympy.printing.pretty.stringpict import prettyForm
15
+ from sympy.physics.quantum.qexpr import QuantumError
16
+
17
+
18
+ __all__ = [
19
+ 'HilbertSpaceError',
20
+ 'HilbertSpace',
21
+ 'TensorProductHilbertSpace',
22
+ 'TensorPowerHilbertSpace',
23
+ 'DirectSumHilbertSpace',
24
+ 'ComplexSpace',
25
+ 'L2',
26
+ 'FockSpace'
27
+ ]
28
+
29
+ #-----------------------------------------------------------------------------
30
+ # Main objects
31
+ #-----------------------------------------------------------------------------
32
+
33
+
34
+ class HilbertSpaceError(QuantumError):
35
+ pass
36
+
37
+ #-----------------------------------------------------------------------------
38
+ # Main objects
39
+ #-----------------------------------------------------------------------------
40
+
41
+
42
+ class HilbertSpace(Basic):
43
+ """An abstract Hilbert space for quantum mechanics.
44
+
45
+ In short, a Hilbert space is an abstract vector space that is complete
46
+ with inner products defined [1]_.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.physics.quantum.hilbert import HilbertSpace
52
+ >>> hs = HilbertSpace()
53
+ >>> hs
54
+ H
55
+
56
+ References
57
+ ==========
58
+
59
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space
60
+ """
61
+
62
+ def __new__(cls):
63
+ obj = Basic.__new__(cls)
64
+ return obj
65
+
66
+ @property
67
+ def dimension(self):
68
+ """Return the Hilbert dimension of the space."""
69
+ raise NotImplementedError('This Hilbert space has no dimension.')
70
+
71
+ def __add__(self, other):
72
+ return DirectSumHilbertSpace(self, other)
73
+
74
+ def __radd__(self, other):
75
+ return DirectSumHilbertSpace(other, self)
76
+
77
+ def __mul__(self, other):
78
+ return TensorProductHilbertSpace(self, other)
79
+
80
+ def __rmul__(self, other):
81
+ return TensorProductHilbertSpace(other, self)
82
+
83
+ def __pow__(self, other, mod=None):
84
+ if mod is not None:
85
+ raise ValueError('The third argument to __pow__ is not supported \
86
+ for Hilbert spaces.')
87
+ return TensorPowerHilbertSpace(self, other)
88
+
89
+ def __contains__(self, other):
90
+ """Is the operator or state in this Hilbert space.
91
+
92
+ This is checked by comparing the classes of the Hilbert spaces, not
93
+ the instances. This is to allow Hilbert Spaces with symbolic
94
+ dimensions.
95
+ """
96
+ if other.hilbert_space.__class__ == self.__class__:
97
+ return True
98
+ else:
99
+ return False
100
+
101
+ def _sympystr(self, printer, *args):
102
+ return 'H'
103
+
104
+ def _pretty(self, printer, *args):
105
+ ustr = '\N{LATIN CAPITAL LETTER H}'
106
+ return prettyForm(ustr)
107
+
108
+ def _latex(self, printer, *args):
109
+ return r'\mathcal{H}'
110
+
111
+
112
+ class ComplexSpace(HilbertSpace):
113
+ """Finite dimensional Hilbert space of complex vectors.
114
+
115
+ The elements of this Hilbert space are n-dimensional complex valued
116
+ vectors with the usual inner product that takes the complex conjugate
117
+ of the vector on the right.
118
+
119
+ A classic example of this type of Hilbert space is spin-1/2, which is
120
+ ``ComplexSpace(2)``. Generalizing to spin-s, the space is
121
+ ``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
122
+ direct product space ``ComplexSpace(2)**N``.
123
+
124
+ Examples
125
+ ========
126
+
127
+ >>> from sympy import symbols
128
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace
129
+ >>> c1 = ComplexSpace(2)
130
+ >>> c1
131
+ C(2)
132
+ >>> c1.dimension
133
+ 2
134
+
135
+ >>> n = symbols('n')
136
+ >>> c2 = ComplexSpace(n)
137
+ >>> c2
138
+ C(n)
139
+ >>> c2.dimension
140
+ n
141
+
142
+ """
143
+
144
+ def __new__(cls, dimension):
145
+ dimension = sympify(dimension)
146
+ r = cls.eval(dimension)
147
+ if isinstance(r, Basic):
148
+ return r
149
+ obj = Basic.__new__(cls, dimension)
150
+ return obj
151
+
152
+ @classmethod
153
+ def eval(cls, dimension):
154
+ if len(dimension.atoms()) == 1:
155
+ if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
156
+ or dimension.is_Symbol):
157
+ raise TypeError('The dimension of a ComplexSpace can only'
158
+ 'be a positive integer, oo, or a Symbol: %r'
159
+ % dimension)
160
+ else:
161
+ for dim in dimension.atoms():
162
+ if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
163
+ raise TypeError('The dimension of a ComplexSpace can only'
164
+ ' contain integers, oo, or a Symbol: %r'
165
+ % dim)
166
+
167
+ @property
168
+ def dimension(self):
169
+ return self.args[0]
170
+
171
+ def _sympyrepr(self, printer, *args):
172
+ return "%s(%s)" % (self.__class__.__name__,
173
+ printer._print(self.dimension, *args))
174
+
175
+ def _sympystr(self, printer, *args):
176
+ return "C(%s)" % printer._print(self.dimension, *args)
177
+
178
+ def _pretty(self, printer, *args):
179
+ ustr = '\N{LATIN CAPITAL LETTER C}'
180
+ pform_exp = printer._print(self.dimension, *args)
181
+ pform_base = prettyForm(ustr)
182
+ return pform_base**pform_exp
183
+
184
+ def _latex(self, printer, *args):
185
+ return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
186
+
187
+
188
+ class L2(HilbertSpace):
189
+ """The Hilbert space of square integrable functions on an interval.
190
+
191
+ An L2 object takes in a single SymPy Interval argument which represents
192
+ the interval its functions (vectors) are defined on.
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy import Interval, oo
198
+ >>> from sympy.physics.quantum.hilbert import L2
199
+ >>> hs = L2(Interval(0,oo))
200
+ >>> hs
201
+ L2(Interval(0, oo))
202
+ >>> hs.dimension
203
+ oo
204
+ >>> hs.interval
205
+ Interval(0, oo)
206
+
207
+ """
208
+
209
+ def __new__(cls, interval):
210
+ if not isinstance(interval, Interval):
211
+ raise TypeError('L2 interval must be an Interval instance: %r'
212
+ % interval)
213
+ obj = Basic.__new__(cls, interval)
214
+ return obj
215
+
216
+ @property
217
+ def dimension(self):
218
+ return S.Infinity
219
+
220
+ @property
221
+ def interval(self):
222
+ return self.args[0]
223
+
224
+ def _sympyrepr(self, printer, *args):
225
+ return "L2(%s)" % printer._print(self.interval, *args)
226
+
227
+ def _sympystr(self, printer, *args):
228
+ return "L2(%s)" % printer._print(self.interval, *args)
229
+
230
+ def _pretty(self, printer, *args):
231
+ pform_exp = prettyForm('2')
232
+ pform_base = prettyForm('L')
233
+ return pform_base**pform_exp
234
+
235
+ def _latex(self, printer, *args):
236
+ interval = printer._print(self.interval, *args)
237
+ return r'{\mathcal{L}^2}\left( %s \right)' % interval
238
+
239
+
240
+ class FockSpace(HilbertSpace):
241
+ """The Hilbert space for second quantization.
242
+
243
+ Technically, this Hilbert space is a infinite direct sum of direct
244
+ products of single particle Hilbert spaces [1]_. This is a mess, so we have
245
+ a class to represent it directly.
246
+
247
+ Examples
248
+ ========
249
+
250
+ >>> from sympy.physics.quantum.hilbert import FockSpace
251
+ >>> hs = FockSpace()
252
+ >>> hs
253
+ F
254
+ >>> hs.dimension
255
+ oo
256
+
257
+ References
258
+ ==========
259
+
260
+ .. [1] https://en.wikipedia.org/wiki/Fock_space
261
+ """
262
+
263
+ def __new__(cls):
264
+ obj = Basic.__new__(cls)
265
+ return obj
266
+
267
+ @property
268
+ def dimension(self):
269
+ return S.Infinity
270
+
271
+ def _sympyrepr(self, printer, *args):
272
+ return "FockSpace()"
273
+
274
+ def _sympystr(self, printer, *args):
275
+ return "F"
276
+
277
+ def _pretty(self, printer, *args):
278
+ ustr = '\N{LATIN CAPITAL LETTER F}'
279
+ return prettyForm(ustr)
280
+
281
+ def _latex(self, printer, *args):
282
+ return r'\mathcal{F}'
283
+
284
+
285
+ class TensorProductHilbertSpace(HilbertSpace):
286
+ """A tensor product of Hilbert spaces [1]_.
287
+
288
+ The tensor product between Hilbert spaces is represented by the
289
+ operator ``*`` Products of the same Hilbert space will be combined into
290
+ tensor powers.
291
+
292
+ A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
293
+ ``HilbertSpace`` objects as its arguments. In addition, multiplication of
294
+ ``HilbertSpace`` objects will automatically return this tensor product
295
+ object.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
301
+ >>> from sympy import symbols
302
+
303
+ >>> c = ComplexSpace(2)
304
+ >>> f = FockSpace()
305
+ >>> hs = c*f
306
+ >>> hs
307
+ C(2)*F
308
+ >>> hs.dimension
309
+ oo
310
+ >>> hs.spaces
311
+ (C(2), F)
312
+
313
+ >>> c1 = ComplexSpace(2)
314
+ >>> n = symbols('n')
315
+ >>> c2 = ComplexSpace(n)
316
+ >>> hs = c1*c2
317
+ >>> hs
318
+ C(2)*C(n)
319
+ >>> hs.dimension
320
+ 2*n
321
+
322
+ References
323
+ ==========
324
+
325
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
326
+ """
327
+
328
+ def __new__(cls, *args):
329
+ r = cls.eval(args)
330
+ if isinstance(r, Basic):
331
+ return r
332
+ obj = Basic.__new__(cls, *args)
333
+ return obj
334
+
335
+ @classmethod
336
+ def eval(cls, args):
337
+ """Evaluates the direct product."""
338
+ new_args = []
339
+ recall = False
340
+ #flatten arguments
341
+ for arg in args:
342
+ if isinstance(arg, TensorProductHilbertSpace):
343
+ new_args.extend(arg.args)
344
+ recall = True
345
+ elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
346
+ new_args.append(arg)
347
+ else:
348
+ raise TypeError('Hilbert spaces can only be multiplied by \
349
+ other Hilbert spaces: %r' % arg)
350
+ #combine like arguments into direct powers
351
+ comb_args = []
352
+ prev_arg = None
353
+ for new_arg in new_args:
354
+ if prev_arg is not None:
355
+ if isinstance(new_arg, TensorPowerHilbertSpace) and \
356
+ isinstance(prev_arg, TensorPowerHilbertSpace) and \
357
+ new_arg.base == prev_arg.base:
358
+ prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
359
+ elif isinstance(new_arg, TensorPowerHilbertSpace) and \
360
+ new_arg.base == prev_arg:
361
+ prev_arg = prev_arg**(new_arg.exp + 1)
362
+ elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
363
+ new_arg == prev_arg.base:
364
+ prev_arg = new_arg**(prev_arg.exp + 1)
365
+ elif new_arg == prev_arg:
366
+ prev_arg = new_arg**2
367
+ else:
368
+ comb_args.append(prev_arg)
369
+ prev_arg = new_arg
370
+ elif prev_arg is None:
371
+ prev_arg = new_arg
372
+ comb_args.append(prev_arg)
373
+ if recall:
374
+ return TensorProductHilbertSpace(*comb_args)
375
+ elif len(comb_args) == 1:
376
+ return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
377
+ else:
378
+ return None
379
+
380
+ @property
381
+ def dimension(self):
382
+ arg_list = [arg.dimension for arg in self.args]
383
+ if S.Infinity in arg_list:
384
+ return S.Infinity
385
+ else:
386
+ return reduce(lambda x, y: x*y, arg_list)
387
+
388
+ @property
389
+ def spaces(self):
390
+ """A tuple of the Hilbert spaces in this tensor product."""
391
+ return self.args
392
+
393
+ def _spaces_printer(self, printer, *args):
394
+ spaces_strs = []
395
+ for arg in self.args:
396
+ s = printer._print(arg, *args)
397
+ if isinstance(arg, DirectSumHilbertSpace):
398
+ s = '(%s)' % s
399
+ spaces_strs.append(s)
400
+ return spaces_strs
401
+
402
+ def _sympyrepr(self, printer, *args):
403
+ spaces_reprs = self._spaces_printer(printer, *args)
404
+ return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
405
+
406
+ def _sympystr(self, printer, *args):
407
+ spaces_strs = self._spaces_printer(printer, *args)
408
+ return '*'.join(spaces_strs)
409
+
410
+ def _pretty(self, printer, *args):
411
+ length = len(self.args)
412
+ pform = printer._print('', *args)
413
+ for i in range(length):
414
+ next_pform = printer._print(self.args[i], *args)
415
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
416
+ TensorProductHilbertSpace)):
417
+ next_pform = prettyForm(
418
+ *next_pform.parens(left='(', right=')')
419
+ )
420
+ pform = prettyForm(*pform.right(next_pform))
421
+ if i != length - 1:
422
+ if printer._use_unicode:
423
+ pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
424
+ else:
425
+ pform = prettyForm(*pform.right(' x '))
426
+ return pform
427
+
428
+ def _latex(self, printer, *args):
429
+ length = len(self.args)
430
+ s = ''
431
+ for i in range(length):
432
+ arg_s = printer._print(self.args[i], *args)
433
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
434
+ TensorProductHilbertSpace)):
435
+ arg_s = r'\left(%s\right)' % arg_s
436
+ s = s + arg_s
437
+ if i != length - 1:
438
+ s = s + r'\otimes '
439
+ return s
440
+
441
+
442
+ class DirectSumHilbertSpace(HilbertSpace):
443
+ """A direct sum of Hilbert spaces [1]_.
444
+
445
+ This class uses the ``+`` operator to represent direct sums between
446
+ different Hilbert spaces.
447
+
448
+ A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
449
+ ``HilbertSpace`` objects as its arguments. Also, addition of
450
+ ``HilbertSpace`` objects will automatically return a direct sum object.
451
+
452
+ Examples
453
+ ========
454
+
455
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
456
+
457
+ >>> c = ComplexSpace(2)
458
+ >>> f = FockSpace()
459
+ >>> hs = c+f
460
+ >>> hs
461
+ C(2)+F
462
+ >>> hs.dimension
463
+ oo
464
+ >>> list(hs.spaces)
465
+ [C(2), F]
466
+
467
+ References
468
+ ==========
469
+
470
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
471
+ """
472
+ def __new__(cls, *args):
473
+ r = cls.eval(args)
474
+ if isinstance(r, Basic):
475
+ return r
476
+ obj = Basic.__new__(cls, *args)
477
+ return obj
478
+
479
+ @classmethod
480
+ def eval(cls, args):
481
+ """Evaluates the direct product."""
482
+ new_args = []
483
+ recall = False
484
+ #flatten arguments
485
+ for arg in args:
486
+ if isinstance(arg, DirectSumHilbertSpace):
487
+ new_args.extend(arg.args)
488
+ recall = True
489
+ elif isinstance(arg, HilbertSpace):
490
+ new_args.append(arg)
491
+ else:
492
+ raise TypeError('Hilbert spaces can only be summed with other \
493
+ Hilbert spaces: %r' % arg)
494
+ if recall:
495
+ return DirectSumHilbertSpace(*new_args)
496
+ else:
497
+ return None
498
+
499
+ @property
500
+ def dimension(self):
501
+ arg_list = [arg.dimension for arg in self.args]
502
+ if S.Infinity in arg_list:
503
+ return S.Infinity
504
+ else:
505
+ return reduce(lambda x, y: x + y, arg_list)
506
+
507
+ @property
508
+ def spaces(self):
509
+ """A tuple of the Hilbert spaces in this direct sum."""
510
+ return self.args
511
+
512
+ def _sympyrepr(self, printer, *args):
513
+ spaces_reprs = [printer._print(arg, *args) for arg in self.args]
514
+ return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
515
+
516
+ def _sympystr(self, printer, *args):
517
+ spaces_strs = [printer._print(arg, *args) for arg in self.args]
518
+ return '+'.join(spaces_strs)
519
+
520
+ def _pretty(self, printer, *args):
521
+ length = len(self.args)
522
+ pform = printer._print('', *args)
523
+ for i in range(length):
524
+ next_pform = printer._print(self.args[i], *args)
525
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
526
+ TensorProductHilbertSpace)):
527
+ next_pform = prettyForm(
528
+ *next_pform.parens(left='(', right=')')
529
+ )
530
+ pform = prettyForm(*pform.right(next_pform))
531
+ if i != length - 1:
532
+ if printer._use_unicode:
533
+ pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
534
+ else:
535
+ pform = prettyForm(*pform.right(' + '))
536
+ return pform
537
+
538
+ def _latex(self, printer, *args):
539
+ length = len(self.args)
540
+ s = ''
541
+ for i in range(length):
542
+ arg_s = printer._print(self.args[i], *args)
543
+ if isinstance(self.args[i], (DirectSumHilbertSpace,
544
+ TensorProductHilbertSpace)):
545
+ arg_s = r'\left(%s\right)' % arg_s
546
+ s = s + arg_s
547
+ if i != length - 1:
548
+ s = s + r'\oplus '
549
+ return s
550
+
551
+
552
+ class TensorPowerHilbertSpace(HilbertSpace):
553
+ """An exponentiated Hilbert space [1]_.
554
+
555
+ Tensor powers (repeated tensor products) are represented by the
556
+ operator ``**`` Identical Hilbert spaces that are multiplied together
557
+ will be automatically combined into a single tensor power object.
558
+
559
+ Any Hilbert space, product, or sum may be raised to a tensor power. The
560
+ ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
561
+ tensor power (number).
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
567
+ >>> from sympy import symbols
568
+
569
+ >>> n = symbols('n')
570
+ >>> c = ComplexSpace(2)
571
+ >>> hs = c**n
572
+ >>> hs
573
+ C(2)**n
574
+ >>> hs.dimension
575
+ 2**n
576
+
577
+ >>> c = ComplexSpace(2)
578
+ >>> c*c
579
+ C(2)**2
580
+ >>> f = FockSpace()
581
+ >>> c*f*f
582
+ C(2)*F**2
583
+
584
+ References
585
+ ==========
586
+
587
+ .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
588
+ """
589
+
590
+ def __new__(cls, *args):
591
+ r = cls.eval(args)
592
+ if isinstance(r, Basic):
593
+ return r
594
+ return Basic.__new__(cls, *r)
595
+
596
+ @classmethod
597
+ def eval(cls, args):
598
+ new_args = args[0], sympify(args[1])
599
+ exp = new_args[1]
600
+ #simplify hs**1 -> hs
601
+ if exp is S.One:
602
+ return args[0]
603
+ #simplify hs**0 -> 1
604
+ if exp is S.Zero:
605
+ return S.One
606
+ #check (and allow) for hs**(x+42+y...) case
607
+ if len(exp.atoms()) == 1:
608
+ if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
609
+ raise ValueError('Hilbert spaces can only be raised to \
610
+ positive integers or Symbols: %r' % exp)
611
+ else:
612
+ for power in exp.atoms():
613
+ if not (power.is_Integer or power.is_Symbol):
614
+ raise ValueError('Tensor powers can only contain integers \
615
+ or Symbols: %r' % power)
616
+ return new_args
617
+
618
+ @property
619
+ def base(self):
620
+ return self.args[0]
621
+
622
+ @property
623
+ def exp(self):
624
+ return self.args[1]
625
+
626
+ @property
627
+ def dimension(self):
628
+ if self.base.dimension is S.Infinity:
629
+ return S.Infinity
630
+ else:
631
+ return self.base.dimension**self.exp
632
+
633
+ def _sympyrepr(self, printer, *args):
634
+ return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
635
+ *args), printer._print(self.exp, *args))
636
+
637
+ def _sympystr(self, printer, *args):
638
+ return "%s**%s" % (printer._print(self.base, *args),
639
+ printer._print(self.exp, *args))
640
+
641
+ def _pretty(self, printer, *args):
642
+ pform_exp = printer._print(self.exp, *args)
643
+ if printer._use_unicode:
644
+ pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
645
+ else:
646
+ pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
647
+ pform_base = printer._print(self.base, *args)
648
+ return pform_base**pform_exp
649
+
650
+ def _latex(self, printer, *args):
651
+ base = printer._print(self.base, *args)
652
+ exp = printer._print(self.exp, *args)
653
+ return r'{%s}^{\otimes %s}' % (base, exp)
janus/lib/python3.10/site-packages/sympy/physics/quantum/identitysearch.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from sympy.core.random import randint
3
+
4
+ from sympy.external import import_module
5
+ from sympy.core.basic import Basic
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.numbers import Number, equal_valued
8
+ from sympy.core.power import Pow
9
+ from sympy.core.singleton import S
10
+ from sympy.physics.quantum.represent import represent
11
+ from sympy.physics.quantum.dagger import Dagger
12
+
13
+ __all__ = [
14
+ # Public interfaces
15
+ 'generate_gate_rules',
16
+ 'generate_equivalent_ids',
17
+ 'GateIdentity',
18
+ 'bfs_identity_search',
19
+ 'random_identity_search',
20
+
21
+ # "Private" functions
22
+ 'is_scalar_sparse_matrix',
23
+ 'is_scalar_nonsparse_matrix',
24
+ 'is_degenerate',
25
+ 'is_reducible',
26
+ ]
27
+
28
+ np = import_module('numpy')
29
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
30
+
31
+
32
+ def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
33
+ """Checks if a given scipy.sparse matrix is a scalar matrix.
34
+
35
+ A scalar matrix is such that B = bI, where B is the scalar
36
+ matrix, b is some scalar multiple, and I is the identity
37
+ matrix. A scalar matrix would have only the element b along
38
+ it's main diagonal and zeroes elsewhere.
39
+
40
+ Parameters
41
+ ==========
42
+
43
+ circuit : Gate tuple
44
+ Sequence of quantum gates representing a quantum circuit
45
+ nqubits : int
46
+ Number of qubits in the circuit
47
+ identity_only : bool
48
+ Check for only identity matrices
49
+ eps : number
50
+ The tolerance value for zeroing out elements in the matrix.
51
+ Values in the range [-eps, +eps] will be changed to a zero.
52
+ """
53
+
54
+ if not np or not scipy:
55
+ pass
56
+
57
+ matrix = represent(Mul(*circuit), nqubits=nqubits,
58
+ format='scipy.sparse')
59
+
60
+ # In some cases, represent returns a 1D scalar value in place
61
+ # of a multi-dimensional scalar matrix
62
+ if (isinstance(matrix, int)):
63
+ return matrix == 1 if identity_only else True
64
+
65
+ # If represent returns a matrix, check if the matrix is diagonal
66
+ # and if every item along the diagonal is the same
67
+ else:
68
+ # Due to floating pointing operations, must zero out
69
+ # elements that are "very" small in the dense matrix
70
+ # See parameter for default value.
71
+
72
+ # Get the ndarray version of the dense matrix
73
+ dense_matrix = matrix.todense().getA()
74
+ # Since complex values can't be compared, must split
75
+ # the matrix into real and imaginary components
76
+ # Find the real values in between -eps and eps
77
+ bool_real = np.logical_and(dense_matrix.real > -eps,
78
+ dense_matrix.real < eps)
79
+ # Find the imaginary values between -eps and eps
80
+ bool_imag = np.logical_and(dense_matrix.imag > -eps,
81
+ dense_matrix.imag < eps)
82
+ # Replaces values between -eps and eps with 0
83
+ corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
84
+ corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
85
+ # Convert the matrix with real values into imaginary values
86
+ corrected_imag = corrected_imag * complex(1j)
87
+ # Recombine the real and imaginary components
88
+ corrected_dense = corrected_real + corrected_imag
89
+
90
+ # Check if it's diagonal
91
+ row_indices = corrected_dense.nonzero()[0]
92
+ col_indices = corrected_dense.nonzero()[1]
93
+ # Check if the rows indices and columns indices are the same
94
+ # If they match, then matrix only contains elements along diagonal
95
+ bool_indices = row_indices == col_indices
96
+ is_diagonal = bool_indices.all()
97
+
98
+ first_element = corrected_dense[0][0]
99
+ # If the first element is a zero, then can't rescale matrix
100
+ # and definitely not diagonal
101
+ if (first_element == 0.0 + 0.0j):
102
+ return False
103
+
104
+ # The dimensions of the dense matrix should still
105
+ # be 2^nqubits if there are elements all along the
106
+ # the main diagonal
107
+ trace_of_corrected = (corrected_dense/first_element).trace()
108
+ expected_trace = pow(2, nqubits)
109
+ has_correct_trace = trace_of_corrected == expected_trace
110
+
111
+ # If only looking for identity matrices
112
+ # first element must be a 1
113
+ real_is_one = abs(first_element.real - 1.0) < eps
114
+ imag_is_zero = abs(first_element.imag) < eps
115
+ is_one = real_is_one and imag_is_zero
116
+ is_identity = is_one if identity_only else True
117
+ return bool(is_diagonal and has_correct_trace and is_identity)
118
+
119
+
120
+ def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
121
+ """Checks if a given circuit, in matrix form, is equivalent to
122
+ a scalar value.
123
+
124
+ Parameters
125
+ ==========
126
+
127
+ circuit : Gate tuple
128
+ Sequence of quantum gates representing a quantum circuit
129
+ nqubits : int
130
+ Number of qubits in the circuit
131
+ identity_only : bool
132
+ Check for only identity matrices
133
+ eps : number
134
+ This argument is ignored. It is just for signature compatibility with
135
+ is_scalar_sparse_matrix.
136
+
137
+ Note: Used in situations when is_scalar_sparse_matrix has bugs
138
+ """
139
+
140
+ matrix = represent(Mul(*circuit), nqubits=nqubits)
141
+
142
+ # In some cases, represent returns a 1D scalar value in place
143
+ # of a multi-dimensional scalar matrix
144
+ if (isinstance(matrix, Number)):
145
+ return matrix == 1 if identity_only else True
146
+
147
+ # If represent returns a matrix, check if the matrix is diagonal
148
+ # and if every item along the diagonal is the same
149
+ else:
150
+ # Added up the diagonal elements
151
+ matrix_trace = matrix.trace()
152
+ # Divide the trace by the first element in the matrix
153
+ # if matrix is not required to be the identity matrix
154
+ adjusted_matrix_trace = (matrix_trace/matrix[0]
155
+ if not identity_only
156
+ else matrix_trace)
157
+
158
+ is_identity = equal_valued(matrix[0], 1) if identity_only else True
159
+
160
+ has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
161
+
162
+ # The matrix is scalar if it's diagonal and the adjusted trace
163
+ # value is equal to 2^nqubits
164
+ return bool(
165
+ matrix.is_diagonal() and has_correct_trace and is_identity)
166
+
167
+ if np and scipy:
168
+ is_scalar_matrix = is_scalar_sparse_matrix
169
+ else:
170
+ is_scalar_matrix = is_scalar_nonsparse_matrix
171
+
172
+
173
+ def _get_min_qubits(a_gate):
174
+ if isinstance(a_gate, Pow):
175
+ return a_gate.base.min_qubits
176
+ else:
177
+ return a_gate.min_qubits
178
+
179
+
180
+ def ll_op(left, right):
181
+ """Perform a LL operation.
182
+
183
+ A LL operation multiplies both left and right circuits
184
+ with the dagger of the left circuit's leftmost gate, and
185
+ the dagger is multiplied on the left side of both circuits.
186
+
187
+ If a LL is possible, it returns the new gate rule as a
188
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
189
+ and RHS is the right circuit of the new rule.
190
+ If a LL is not possible, None is returned.
191
+
192
+ Parameters
193
+ ==========
194
+
195
+ left : Gate tuple
196
+ The left circuit of a gate rule expression.
197
+ right : Gate tuple
198
+ The right circuit of a gate rule expression.
199
+
200
+ Examples
201
+ ========
202
+
203
+ Generate a new gate rule using a LL operation:
204
+
205
+ >>> from sympy.physics.quantum.identitysearch import ll_op
206
+ >>> from sympy.physics.quantum.gate import X, Y, Z
207
+ >>> x = X(0); y = Y(0); z = Z(0)
208
+ >>> ll_op((x, y, z), ())
209
+ ((Y(0), Z(0)), (X(0),))
210
+
211
+ >>> ll_op((y, z), (x,))
212
+ ((Z(0),), (Y(0), X(0)))
213
+ """
214
+
215
+ if (len(left) > 0):
216
+ ll_gate = left[0]
217
+ ll_gate_is_unitary = is_scalar_matrix(
218
+ (Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
219
+
220
+ if (len(left) > 0 and ll_gate_is_unitary):
221
+ # Get the new left side w/o the leftmost gate
222
+ new_left = left[1:len(left)]
223
+ # Add the leftmost gate to the left position on the right side
224
+ new_right = (Dagger(ll_gate),) + right
225
+ # Return the new gate rule
226
+ return (new_left, new_right)
227
+
228
+ return None
229
+
230
+
231
+ def lr_op(left, right):
232
+ """Perform a LR operation.
233
+
234
+ A LR operation multiplies both left and right circuits
235
+ with the dagger of the left circuit's rightmost gate, and
236
+ the dagger is multiplied on the right side of both circuits.
237
+
238
+ If a LR is possible, it returns the new gate rule as a
239
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
240
+ and RHS is the right circuit of the new rule.
241
+ If a LR is not possible, None is returned.
242
+
243
+ Parameters
244
+ ==========
245
+
246
+ left : Gate tuple
247
+ The left circuit of a gate rule expression.
248
+ right : Gate tuple
249
+ The right circuit of a gate rule expression.
250
+
251
+ Examples
252
+ ========
253
+
254
+ Generate a new gate rule using a LR operation:
255
+
256
+ >>> from sympy.physics.quantum.identitysearch import lr_op
257
+ >>> from sympy.physics.quantum.gate import X, Y, Z
258
+ >>> x = X(0); y = Y(0); z = Z(0)
259
+ >>> lr_op((x, y, z), ())
260
+ ((X(0), Y(0)), (Z(0),))
261
+
262
+ >>> lr_op((x, y), (z,))
263
+ ((X(0),), (Z(0), Y(0)))
264
+ """
265
+
266
+ if (len(left) > 0):
267
+ lr_gate = left[len(left) - 1]
268
+ lr_gate_is_unitary = is_scalar_matrix(
269
+ (Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
270
+
271
+ if (len(left) > 0 and lr_gate_is_unitary):
272
+ # Get the new left side w/o the rightmost gate
273
+ new_left = left[0:len(left) - 1]
274
+ # Add the rightmost gate to the right position on the right side
275
+ new_right = right + (Dagger(lr_gate),)
276
+ # Return the new gate rule
277
+ return (new_left, new_right)
278
+
279
+ return None
280
+
281
+
282
+ def rl_op(left, right):
283
+ """Perform a RL operation.
284
+
285
+ A RL operation multiplies both left and right circuits
286
+ with the dagger of the right circuit's leftmost gate, and
287
+ the dagger is multiplied on the left side of both circuits.
288
+
289
+ If a RL is possible, it returns the new gate rule as a
290
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
291
+ and RHS is the right circuit of the new rule.
292
+ If a RL is not possible, None is returned.
293
+
294
+ Parameters
295
+ ==========
296
+
297
+ left : Gate tuple
298
+ The left circuit of a gate rule expression.
299
+ right : Gate tuple
300
+ The right circuit of a gate rule expression.
301
+
302
+ Examples
303
+ ========
304
+
305
+ Generate a new gate rule using a RL operation:
306
+
307
+ >>> from sympy.physics.quantum.identitysearch import rl_op
308
+ >>> from sympy.physics.quantum.gate import X, Y, Z
309
+ >>> x = X(0); y = Y(0); z = Z(0)
310
+ >>> rl_op((x,), (y, z))
311
+ ((Y(0), X(0)), (Z(0),))
312
+
313
+ >>> rl_op((x, y), (z,))
314
+ ((Z(0), X(0), Y(0)), ())
315
+ """
316
+
317
+ if (len(right) > 0):
318
+ rl_gate = right[0]
319
+ rl_gate_is_unitary = is_scalar_matrix(
320
+ (Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
321
+
322
+ if (len(right) > 0 and rl_gate_is_unitary):
323
+ # Get the new right side w/o the leftmost gate
324
+ new_right = right[1:len(right)]
325
+ # Add the leftmost gate to the left position on the left side
326
+ new_left = (Dagger(rl_gate),) + left
327
+ # Return the new gate rule
328
+ return (new_left, new_right)
329
+
330
+ return None
331
+
332
+
333
+ def rr_op(left, right):
334
+ """Perform a RR operation.
335
+
336
+ A RR operation multiplies both left and right circuits
337
+ with the dagger of the right circuit's rightmost gate, and
338
+ the dagger is multiplied on the right side of both circuits.
339
+
340
+ If a RR is possible, it returns the new gate rule as a
341
+ 2-tuple (LHS, RHS), where LHS is the left circuit and
342
+ and RHS is the right circuit of the new rule.
343
+ If a RR is not possible, None is returned.
344
+
345
+ Parameters
346
+ ==========
347
+
348
+ left : Gate tuple
349
+ The left circuit of a gate rule expression.
350
+ right : Gate tuple
351
+ The right circuit of a gate rule expression.
352
+
353
+ Examples
354
+ ========
355
+
356
+ Generate a new gate rule using a RR operation:
357
+
358
+ >>> from sympy.physics.quantum.identitysearch import rr_op
359
+ >>> from sympy.physics.quantum.gate import X, Y, Z
360
+ >>> x = X(0); y = Y(0); z = Z(0)
361
+ >>> rr_op((x, y), (z,))
362
+ ((X(0), Y(0), Z(0)), ())
363
+
364
+ >>> rr_op((x,), (y, z))
365
+ ((X(0), Z(0)), (Y(0),))
366
+ """
367
+
368
+ if (len(right) > 0):
369
+ rr_gate = right[len(right) - 1]
370
+ rr_gate_is_unitary = is_scalar_matrix(
371
+ (Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
372
+
373
+ if (len(right) > 0 and rr_gate_is_unitary):
374
+ # Get the new right side w/o the rightmost gate
375
+ new_right = right[0:len(right) - 1]
376
+ # Add the rightmost gate to the right position on the right side
377
+ new_left = left + (Dagger(rr_gate),)
378
+ # Return the new gate rule
379
+ return (new_left, new_right)
380
+
381
+ return None
382
+
383
+
384
+ def generate_gate_rules(gate_seq, return_as_muls=False):
385
+ """Returns a set of gate rules. Each gate rules is represented
386
+ as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
387
+ scalar value.
388
+
389
+ This function uses the four operations (LL, LR, RL, RR)
390
+ to generate the gate rules.
391
+
392
+ A gate rule is an expression such as ABC = D or AB = CD, where
393
+ A, B, C, and D are gates. Each value on either side of the
394
+ equal sign represents a circuit. The four operations allow
395
+ one to find a set of equivalent circuits from a gate identity.
396
+ The letters denoting the operation tell the user what
397
+ activities to perform on each expression. The first letter
398
+ indicates which side of the equal sign to focus on. The
399
+ second letter indicates which gate to focus on given the
400
+ side. Once this information is determined, the inverse
401
+ of the gate is multiplied on both circuits to create a new
402
+ gate rule.
403
+
404
+ For example, given the identity, ABCD = 1, a LL operation
405
+ means look at the left value and multiply both left sides by the
406
+ inverse of the leftmost gate A. If A is Hermitian, the inverse
407
+ of A is still A. The resulting new rule is BCD = A.
408
+
409
+ The following is a summary of the four operations. Assume
410
+ that in the examples, all gates are Hermitian.
411
+
412
+ LL : left circuit, left multiply
413
+ ABCD = E -> AABCD = AE -> BCD = AE
414
+ LR : left circuit, right multiply
415
+ ABCD = E -> ABCDD = ED -> ABC = ED
416
+ RL : right circuit, left multiply
417
+ ABC = ED -> EABC = EED -> EABC = D
418
+ RR : right circuit, right multiply
419
+ AB = CD -> ABD = CDD -> ABD = C
420
+
421
+ The number of gate rules generated is n*(n+1), where n
422
+ is the number of gates in the sequence (unproven).
423
+
424
+ Parameters
425
+ ==========
426
+
427
+ gate_seq : Gate tuple, Mul, or Number
428
+ A variable length tuple or Mul of Gates whose product is equal to
429
+ a scalar matrix
430
+ return_as_muls : bool
431
+ True to return a set of Muls; False to return a set of tuples
432
+
433
+ Examples
434
+ ========
435
+
436
+ Find the gate rules of the current circuit using tuples:
437
+
438
+ >>> from sympy.physics.quantum.identitysearch import generate_gate_rules
439
+ >>> from sympy.physics.quantum.gate import X, Y, Z
440
+ >>> x = X(0); y = Y(0); z = Z(0)
441
+ >>> generate_gate_rules((x, x))
442
+ {((X(0),), (X(0),)), ((X(0), X(0)), ())}
443
+
444
+ >>> generate_gate_rules((x, y, z))
445
+ {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
446
+ ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
447
+ ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
448
+ ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
449
+ ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
450
+ ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
451
+
452
+ Find the gate rules of the current circuit using Muls:
453
+
454
+ >>> generate_gate_rules(x*x, return_as_muls=True)
455
+ {(1, 1)}
456
+
457
+ >>> generate_gate_rules(x*y*z, return_as_muls=True)
458
+ {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
459
+ (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
460
+ (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
461
+ (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
462
+ (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
463
+ (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
464
+ """
465
+
466
+ if isinstance(gate_seq, Number):
467
+ if return_as_muls:
468
+ return {(S.One, S.One)}
469
+ else:
470
+ return {((), ())}
471
+
472
+ elif isinstance(gate_seq, Mul):
473
+ gate_seq = gate_seq.args
474
+
475
+ # Each item in queue is a 3-tuple:
476
+ # i) first item is the left side of an equality
477
+ # ii) second item is the right side of an equality
478
+ # iii) third item is the number of operations performed
479
+ # The argument, gate_seq, will start on the left side, and
480
+ # the right side will be empty, implying the presence of an
481
+ # identity.
482
+ queue = deque()
483
+ # A set of gate rules
484
+ rules = set()
485
+ # Maximum number of operations to perform
486
+ max_ops = len(gate_seq)
487
+
488
+ def process_new_rule(new_rule, ops):
489
+ if new_rule is not None:
490
+ new_left, new_right = new_rule
491
+
492
+ if new_rule not in rules and (new_right, new_left) not in rules:
493
+ rules.add(new_rule)
494
+ # If haven't reached the max limit on operations
495
+ if ops + 1 < max_ops:
496
+ queue.append(new_rule + (ops + 1,))
497
+
498
+ queue.append((gate_seq, (), 0))
499
+ rules.add((gate_seq, ()))
500
+
501
+ while len(queue) > 0:
502
+ left, right, ops = queue.popleft()
503
+
504
+ # Do a LL
505
+ new_rule = ll_op(left, right)
506
+ process_new_rule(new_rule, ops)
507
+ # Do a LR
508
+ new_rule = lr_op(left, right)
509
+ process_new_rule(new_rule, ops)
510
+ # Do a RL
511
+ new_rule = rl_op(left, right)
512
+ process_new_rule(new_rule, ops)
513
+ # Do a RR
514
+ new_rule = rr_op(left, right)
515
+ process_new_rule(new_rule, ops)
516
+
517
+ if return_as_muls:
518
+ # Convert each rule as tuples into a rule as muls
519
+ mul_rules = set()
520
+ for rule in rules:
521
+ left, right = rule
522
+ mul_rules.add((Mul(*left), Mul(*right)))
523
+
524
+ rules = mul_rules
525
+
526
+ return rules
527
+
528
+
529
+ def generate_equivalent_ids(gate_seq, return_as_muls=False):
530
+ """Returns a set of equivalent gate identities.
531
+
532
+ A gate identity is a quantum circuit such that the product
533
+ of the gates in the circuit is equal to a scalar value.
534
+ For example, XYZ = i, where X, Y, Z are the Pauli gates and
535
+ i is the imaginary value, is considered a gate identity.
536
+
537
+ This function uses the four operations (LL, LR, RL, RR)
538
+ to generate the gate rules and, subsequently, to locate equivalent
539
+ gate identities.
540
+
541
+ Note that all equivalent identities are reachable in n operations
542
+ from the starting gate identity, where n is the number of gates
543
+ in the sequence.
544
+
545
+ The max number of gate identities is 2n, where n is the number
546
+ of gates in the sequence (unproven).
547
+
548
+ Parameters
549
+ ==========
550
+
551
+ gate_seq : Gate tuple, Mul, or Number
552
+ A variable length tuple or Mul of Gates whose product is equal to
553
+ a scalar matrix.
554
+ return_as_muls: bool
555
+ True to return as Muls; False to return as tuples
556
+
557
+ Examples
558
+ ========
559
+
560
+ Find equivalent gate identities from the current circuit with tuples:
561
+
562
+ >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
563
+ >>> from sympy.physics.quantum.gate import X, Y, Z
564
+ >>> x = X(0); y = Y(0); z = Z(0)
565
+ >>> generate_equivalent_ids((x, x))
566
+ {(X(0), X(0))}
567
+
568
+ >>> generate_equivalent_ids((x, y, z))
569
+ {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
570
+ (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
571
+
572
+ Find equivalent gate identities from the current circuit with Muls:
573
+
574
+ >>> generate_equivalent_ids(x*x, return_as_muls=True)
575
+ {1}
576
+
577
+ >>> generate_equivalent_ids(x*y*z, return_as_muls=True)
578
+ {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
579
+ Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
580
+ """
581
+
582
+ if isinstance(gate_seq, Number):
583
+ return {S.One}
584
+ elif isinstance(gate_seq, Mul):
585
+ gate_seq = gate_seq.args
586
+
587
+ # Filter through the gate rules and keep the rules
588
+ # with an empty tuple either on the left or right side
589
+
590
+ # A set of equivalent gate identities
591
+ eq_ids = set()
592
+
593
+ gate_rules = generate_gate_rules(gate_seq)
594
+ for rule in gate_rules:
595
+ l, r = rule
596
+ if l == ():
597
+ eq_ids.add(r)
598
+ elif r == ():
599
+ eq_ids.add(l)
600
+
601
+ if return_as_muls:
602
+ convert_to_mul = lambda id_seq: Mul(*id_seq)
603
+ eq_ids = set(map(convert_to_mul, eq_ids))
604
+
605
+ return eq_ids
606
+
607
+
608
+ class GateIdentity(Basic):
609
+ """Wrapper class for circuits that reduce to a scalar value.
610
+
611
+ A gate identity is a quantum circuit such that the product
612
+ of the gates in the circuit is equal to a scalar value.
613
+ For example, XYZ = i, where X, Y, Z are the Pauli gates and
614
+ i is the imaginary value, is considered a gate identity.
615
+
616
+ Parameters
617
+ ==========
618
+
619
+ args : Gate tuple
620
+ A variable length tuple of Gates that form an identity.
621
+
622
+ Examples
623
+ ========
624
+
625
+ Create a GateIdentity and look at its attributes:
626
+
627
+ >>> from sympy.physics.quantum.identitysearch import GateIdentity
628
+ >>> from sympy.physics.quantum.gate import X, Y, Z
629
+ >>> x = X(0); y = Y(0); z = Z(0)
630
+ >>> an_identity = GateIdentity(x, y, z)
631
+ >>> an_identity.circuit
632
+ X(0)*Y(0)*Z(0)
633
+
634
+ >>> an_identity.equivalent_ids
635
+ {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
636
+ (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
637
+ """
638
+
639
+ def __new__(cls, *args):
640
+ # args should be a tuple - a variable length argument list
641
+ obj = Basic.__new__(cls, *args)
642
+ obj._circuit = Mul(*args)
643
+ obj._rules = generate_gate_rules(args)
644
+ obj._eq_ids = generate_equivalent_ids(args)
645
+
646
+ return obj
647
+
648
+ @property
649
+ def circuit(self):
650
+ return self._circuit
651
+
652
+ @property
653
+ def gate_rules(self):
654
+ return self._rules
655
+
656
+ @property
657
+ def equivalent_ids(self):
658
+ return self._eq_ids
659
+
660
+ @property
661
+ def sequence(self):
662
+ return self.args
663
+
664
+ def __str__(self):
665
+ """Returns the string of gates in a tuple."""
666
+ return str(self.circuit)
667
+
668
+
669
+ def is_degenerate(identity_set, gate_identity):
670
+ """Checks if a gate identity is a permutation of another identity.
671
+
672
+ Parameters
673
+ ==========
674
+
675
+ identity_set : set
676
+ A Python set with GateIdentity objects.
677
+ gate_identity : GateIdentity
678
+ The GateIdentity to check for existence in the set.
679
+
680
+ Examples
681
+ ========
682
+
683
+ Check if the identity is a permutation of another identity:
684
+
685
+ >>> from sympy.physics.quantum.identitysearch import (
686
+ ... GateIdentity, is_degenerate)
687
+ >>> from sympy.physics.quantum.gate import X, Y, Z
688
+ >>> x = X(0); y = Y(0); z = Z(0)
689
+ >>> an_identity = GateIdentity(x, y, z)
690
+ >>> id_set = {an_identity}
691
+ >>> another_id = (y, z, x)
692
+ >>> is_degenerate(id_set, another_id)
693
+ True
694
+
695
+ >>> another_id = (x, x)
696
+ >>> is_degenerate(id_set, another_id)
697
+ False
698
+ """
699
+
700
+ # For now, just iteratively go through the set and check if the current
701
+ # gate_identity is a permutation of an identity in the set
702
+ for an_id in identity_set:
703
+ if (gate_identity in an_id.equivalent_ids):
704
+ return True
705
+ return False
706
+
707
+
708
+ def is_reducible(circuit, nqubits, begin, end):
709
+ """Determines if a circuit is reducible by checking
710
+ if its subcircuits are scalar values.
711
+
712
+ Parameters
713
+ ==========
714
+
715
+ circuit : Gate tuple
716
+ A tuple of Gates representing a circuit. The circuit to check
717
+ if a gate identity is contained in a subcircuit.
718
+ nqubits : int
719
+ The number of qubits the circuit operates on.
720
+ begin : int
721
+ The leftmost gate in the circuit to include in a subcircuit.
722
+ end : int
723
+ The rightmost gate in the circuit to include in a subcircuit.
724
+
725
+ Examples
726
+ ========
727
+
728
+ Check if the circuit can be reduced:
729
+
730
+ >>> from sympy.physics.quantum.identitysearch import is_reducible
731
+ >>> from sympy.physics.quantum.gate import X, Y, Z
732
+ >>> x = X(0); y = Y(0); z = Z(0)
733
+ >>> is_reducible((x, y, z), 1, 0, 3)
734
+ True
735
+
736
+ Check if an interval in the circuit can be reduced:
737
+
738
+ >>> is_reducible((x, y, z), 1, 1, 3)
739
+ False
740
+
741
+ >>> is_reducible((x, y, y), 1, 1, 3)
742
+ True
743
+ """
744
+
745
+ current_circuit = ()
746
+ # Start from the gate at "end" and go down to almost the gate at "begin"
747
+ for ndx in reversed(range(begin, end)):
748
+ next_gate = circuit[ndx]
749
+ current_circuit = (next_gate,) + current_circuit
750
+
751
+ # If a circuit as a matrix is equivalent to a scalar value
752
+ if (is_scalar_matrix(current_circuit, nqubits, False)):
753
+ return True
754
+
755
+ return False
756
+
757
+
758
+ def bfs_identity_search(gate_list, nqubits, max_depth=None,
759
+ identity_only=False):
760
+ """Constructs a set of gate identities from the list of possible gates.
761
+
762
+ Performs a breadth first search over the space of gate identities.
763
+ This allows the finding of the shortest gate identities first.
764
+
765
+ Parameters
766
+ ==========
767
+
768
+ gate_list : list, Gate
769
+ A list of Gates from which to search for gate identities.
770
+ nqubits : int
771
+ The number of qubits the quantum circuit operates on.
772
+ max_depth : int
773
+ The longest quantum circuit to construct from gate_list.
774
+ identity_only : bool
775
+ True to search for gate identities that reduce to identity;
776
+ False to search for gate identities that reduce to a scalar.
777
+
778
+ Examples
779
+ ========
780
+
781
+ Find a list of gate identities:
782
+
783
+ >>> from sympy.physics.quantum.identitysearch import bfs_identity_search
784
+ >>> from sympy.physics.quantum.gate import X, Y, Z
785
+ >>> x = X(0); y = Y(0); z = Z(0)
786
+ >>> bfs_identity_search([x], 1, max_depth=2)
787
+ {GateIdentity(X(0), X(0))}
788
+
789
+ >>> bfs_identity_search([x, y, z], 1)
790
+ {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
791
+ GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
792
+
793
+ Find a list of identities that only equal to 1:
794
+
795
+ >>> bfs_identity_search([x, y, z], 1, identity_only=True)
796
+ {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
797
+ GateIdentity(Z(0), Z(0))}
798
+ """
799
+
800
+ if max_depth is None or max_depth <= 0:
801
+ max_depth = len(gate_list)
802
+
803
+ id_only = identity_only
804
+
805
+ # Start with an empty sequence (implicitly contains an IdentityGate)
806
+ queue = deque([()])
807
+
808
+ # Create an empty set of gate identities
809
+ ids = set()
810
+
811
+ # Begin searching for gate identities in given space.
812
+ while (len(queue) > 0):
813
+ current_circuit = queue.popleft()
814
+
815
+ for next_gate in gate_list:
816
+ new_circuit = current_circuit + (next_gate,)
817
+
818
+ # Determines if a (strict) subcircuit is a scalar matrix
819
+ circuit_reducible = is_reducible(new_circuit, nqubits,
820
+ 1, len(new_circuit))
821
+
822
+ # In many cases when the matrix is a scalar value,
823
+ # the evaluated matrix will actually be an integer
824
+ if (is_scalar_matrix(new_circuit, nqubits, id_only) and
825
+ not is_degenerate(ids, new_circuit) and
826
+ not circuit_reducible):
827
+ ids.add(GateIdentity(*new_circuit))
828
+
829
+ elif (len(new_circuit) < max_depth and
830
+ not circuit_reducible):
831
+ queue.append(new_circuit)
832
+
833
+ return ids
834
+
835
+
836
+ def random_identity_search(gate_list, numgates, nqubits):
837
+ """Randomly selects numgates from gate_list and checks if it is
838
+ a gate identity.
839
+
840
+ If the circuit is a gate identity, the circuit is returned;
841
+ Otherwise, None is returned.
842
+ """
843
+
844
+ gate_size = len(gate_list)
845
+ circuit = ()
846
+
847
+ for i in range(numgates):
848
+ next_gate = gate_list[randint(0, gate_size - 1)]
849
+ circuit = circuit + (next_gate,)
850
+
851
+ is_scalar = is_scalar_matrix(circuit, nqubits, False)
852
+
853
+ return circuit if is_scalar else None
janus/lib/python3.10/site-packages/sympy/physics/quantum/matrixutils.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities to deal with sympy.Matrix, numpy and scipy.sparse."""
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.numbers import I
5
+ from sympy.core.singleton import S
6
+ from sympy.matrices.matrixbase import MatrixBase
7
+ from sympy.matrices import eye, zeros
8
+ from sympy.external import import_module
9
+
10
+ __all__ = [
11
+ 'numpy_ndarray',
12
+ 'scipy_sparse_matrix',
13
+ 'sympy_to_numpy',
14
+ 'sympy_to_scipy_sparse',
15
+ 'numpy_to_sympy',
16
+ 'scipy_sparse_to_sympy',
17
+ 'flatten_scalar',
18
+ 'matrix_dagger',
19
+ 'to_sympy',
20
+ 'to_numpy',
21
+ 'to_scipy_sparse',
22
+ 'matrix_tensor_product',
23
+ 'matrix_zeros'
24
+ ]
25
+
26
+ # Conditionally define the base classes for numpy and scipy.sparse arrays
27
+ # for use in isinstance tests.
28
+
29
+ np = import_module('numpy')
30
+ if not np:
31
+ class numpy_ndarray:
32
+ pass
33
+ else:
34
+ numpy_ndarray = np.ndarray # type: ignore
35
+
36
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
37
+ if not scipy:
38
+ class scipy_sparse_matrix:
39
+ pass
40
+ sparse = None
41
+ else:
42
+ sparse = scipy.sparse
43
+ scipy_sparse_matrix = sparse.spmatrix # type: ignore
44
+
45
+
46
+ def sympy_to_numpy(m, **options):
47
+ """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
48
+ if not np:
49
+ raise ImportError
50
+ dtype = options.get('dtype', 'complex')
51
+ if isinstance(m, MatrixBase):
52
+ return np.array(m.tolist(), dtype=dtype)
53
+ elif isinstance(m, Expr):
54
+ if m.is_Number or m.is_NumberSymbol or m == I:
55
+ return complex(m)
56
+ raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
57
+
58
+
59
+ def sympy_to_scipy_sparse(m, **options):
60
+ """Convert a SymPy Matrix/complex number to a numpy matrix or scalar."""
61
+ if not np or not sparse:
62
+ raise ImportError
63
+ dtype = options.get('dtype', 'complex')
64
+ if isinstance(m, MatrixBase):
65
+ return sparse.csr_matrix(np.array(m.tolist(), dtype=dtype))
66
+ elif isinstance(m, Expr):
67
+ if m.is_Number or m.is_NumberSymbol or m == I:
68
+ return complex(m)
69
+ raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m)
70
+
71
+
72
+ def scipy_sparse_to_sympy(m, **options):
73
+ """Convert a scipy.sparse matrix to a SymPy matrix."""
74
+ return MatrixBase(m.todense())
75
+
76
+
77
+ def numpy_to_sympy(m, **options):
78
+ """Convert a numpy matrix to a SymPy matrix."""
79
+ return MatrixBase(m)
80
+
81
+
82
+ def to_sympy(m, **options):
83
+ """Convert a numpy/scipy.sparse matrix to a SymPy matrix."""
84
+ if isinstance(m, MatrixBase):
85
+ return m
86
+ elif isinstance(m, numpy_ndarray):
87
+ return numpy_to_sympy(m)
88
+ elif isinstance(m, scipy_sparse_matrix):
89
+ return scipy_sparse_to_sympy(m)
90
+ elif isinstance(m, Expr):
91
+ return m
92
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
93
+
94
+
95
+ def to_numpy(m, **options):
96
+ """Convert a sympy/scipy.sparse matrix to a numpy matrix."""
97
+ dtype = options.get('dtype', 'complex')
98
+ if isinstance(m, (MatrixBase, Expr)):
99
+ return sympy_to_numpy(m, dtype=dtype)
100
+ elif isinstance(m, numpy_ndarray):
101
+ return m
102
+ elif isinstance(m, scipy_sparse_matrix):
103
+ return m.todense()
104
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
105
+
106
+
107
+ def to_scipy_sparse(m, **options):
108
+ """Convert a sympy/numpy matrix to a scipy.sparse matrix."""
109
+ dtype = options.get('dtype', 'complex')
110
+ if isinstance(m, (MatrixBase, Expr)):
111
+ return sympy_to_scipy_sparse(m, dtype=dtype)
112
+ elif isinstance(m, numpy_ndarray):
113
+ if not sparse:
114
+ raise ImportError
115
+ return sparse.csr_matrix(m)
116
+ elif isinstance(m, scipy_sparse_matrix):
117
+ return m
118
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m)
119
+
120
+
121
+ def flatten_scalar(e):
122
+ """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged."""
123
+ if isinstance(e, MatrixBase):
124
+ if e.shape == (1, 1):
125
+ e = e[0]
126
+ if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
127
+ if e.shape == (1, 1):
128
+ e = complex(e[0, 0])
129
+ return e
130
+
131
+
132
+ def matrix_dagger(e):
133
+ """Return the dagger of a sympy/numpy/scipy.sparse matrix."""
134
+ if isinstance(e, MatrixBase):
135
+ return e.H
136
+ elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)):
137
+ return e.conjugate().transpose()
138
+ raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e)
139
+
140
+
141
+ # TODO: Move this into sympy.matricies.
142
+ def _sympy_tensor_product(*matrices):
143
+ """Compute the kronecker product of a sequence of SymPy Matrices.
144
+ """
145
+ from sympy.matrices.expressions.kronecker import matrix_kronecker_product
146
+
147
+ return matrix_kronecker_product(*matrices)
148
+
149
+
150
+ def _numpy_tensor_product(*product):
151
+ """numpy version of tensor product of multiple arguments."""
152
+ if not np:
153
+ raise ImportError
154
+ answer = product[0]
155
+ for item in product[1:]:
156
+ answer = np.kron(answer, item)
157
+ return answer
158
+
159
+
160
+ def _scipy_sparse_tensor_product(*product):
161
+ """scipy.sparse version of tensor product of multiple arguments."""
162
+ if not sparse:
163
+ raise ImportError
164
+ answer = product[0]
165
+ for item in product[1:]:
166
+ answer = sparse.kron(answer, item)
167
+ # The final matrices will just be multiplied, so csr is a good final
168
+ # sparse format.
169
+ return sparse.csr_matrix(answer)
170
+
171
+
172
+ def matrix_tensor_product(*product):
173
+ """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices."""
174
+ if isinstance(product[0], MatrixBase):
175
+ return _sympy_tensor_product(*product)
176
+ elif isinstance(product[0], numpy_ndarray):
177
+ return _numpy_tensor_product(*product)
178
+ elif isinstance(product[0], scipy_sparse_matrix):
179
+ return _scipy_sparse_tensor_product(*product)
180
+
181
+
182
+ def _numpy_eye(n):
183
+ """numpy version of complex eye."""
184
+ if not np:
185
+ raise ImportError
186
+ return np.array(np.eye(n, dtype='complex'))
187
+
188
+
189
+ def _scipy_sparse_eye(n):
190
+ """scipy.sparse version of complex eye."""
191
+ if not sparse:
192
+ raise ImportError
193
+ return sparse.eye(n, n, dtype='complex')
194
+
195
+
196
+ def matrix_eye(n, **options):
197
+ """Get the version of eye and tensor_product for a given format."""
198
+ format = options.get('format', 'sympy')
199
+ if format == 'sympy':
200
+ return eye(n)
201
+ elif format == 'numpy':
202
+ return _numpy_eye(n)
203
+ elif format == 'scipy.sparse':
204
+ return _scipy_sparse_eye(n)
205
+ raise NotImplementedError('Invalid format: %r' % format)
206
+
207
+
208
+ def _numpy_zeros(m, n, **options):
209
+ """numpy version of zeros."""
210
+ dtype = options.get('dtype', 'float64')
211
+ if not np:
212
+ raise ImportError
213
+ return np.zeros((m, n), dtype=dtype)
214
+
215
+
216
+ def _scipy_sparse_zeros(m, n, **options):
217
+ """scipy.sparse version of zeros."""
218
+ spmatrix = options.get('spmatrix', 'csr')
219
+ dtype = options.get('dtype', 'float64')
220
+ if not sparse:
221
+ raise ImportError
222
+ if spmatrix == 'lil':
223
+ return sparse.lil_matrix((m, n), dtype=dtype)
224
+ elif spmatrix == 'csr':
225
+ return sparse.csr_matrix((m, n), dtype=dtype)
226
+
227
+
228
+ def matrix_zeros(m, n, **options):
229
+ """"Get a zeros matrix for a given format."""
230
+ format = options.get('format', 'sympy')
231
+ if format == 'sympy':
232
+ return zeros(m, n)
233
+ elif format == 'numpy':
234
+ return _numpy_zeros(m, n, **options)
235
+ elif format == 'scipy.sparse':
236
+ return _scipy_sparse_zeros(m, n, **options)
237
+ raise NotImplementedError('Invaild format: %r' % format)
238
+
239
+
240
+ def _numpy_matrix_to_zero(e):
241
+ """Convert a numpy zero matrix to the zero scalar."""
242
+ if not np:
243
+ raise ImportError
244
+ test = np.zeros_like(e)
245
+ if np.allclose(e, test):
246
+ return 0.0
247
+ else:
248
+ return e
249
+
250
+
251
+ def _scipy_sparse_matrix_to_zero(e):
252
+ """Convert a scipy.sparse zero matrix to the zero scalar."""
253
+ if not np:
254
+ raise ImportError
255
+ edense = e.todense()
256
+ test = np.zeros_like(edense)
257
+ if np.allclose(edense, test):
258
+ return 0.0
259
+ else:
260
+ return e
261
+
262
+
263
+ def matrix_to_zero(e):
264
+ """Convert a zero matrix to the scalar zero."""
265
+ if isinstance(e, MatrixBase):
266
+ if zeros(*e.shape) == e:
267
+ e = S.Zero
268
+ elif isinstance(e, numpy_ndarray):
269
+ e = _numpy_matrix_to_zero(e)
270
+ elif isinstance(e, scipy_sparse_matrix):
271
+ e = _scipy_sparse_matrix_to_zero(e)
272
+ return e
janus/lib/python3.10/site-packages/sympy/physics/quantum/piab.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """1D quantum particle in a box."""
2
+
3
+ from sympy.core.numbers import pi
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.trigonometric import sin
8
+ from sympy.sets.sets import Interval
9
+
10
+ from sympy.physics.quantum.operator import HermitianOperator
11
+ from sympy.physics.quantum.state import Ket, Bra
12
+ from sympy.physics.quantum.constants import hbar
13
+ from sympy.functions.special.tensor_functions import KroneckerDelta
14
+ from sympy.physics.quantum.hilbert import L2
15
+
16
+ m = Symbol('m')
17
+ L = Symbol('L')
18
+
19
+
20
+ __all__ = [
21
+ 'PIABHamiltonian',
22
+ 'PIABKet',
23
+ 'PIABBra'
24
+ ]
25
+
26
+
27
+ class PIABHamiltonian(HermitianOperator):
28
+ """Particle in a box Hamiltonian operator."""
29
+
30
+ @classmethod
31
+ def _eval_hilbert_space(cls, label):
32
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
33
+
34
+ def _apply_operator_PIABKet(self, ket, **options):
35
+ n = ket.label[0]
36
+ return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket
37
+
38
+
39
+ class PIABKet(Ket):
40
+ """Particle in a box eigenket."""
41
+
42
+ @classmethod
43
+ def _eval_hilbert_space(cls, args):
44
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
45
+
46
+ @classmethod
47
+ def dual_class(self):
48
+ return PIABBra
49
+
50
+ def _represent_default_basis(self, **options):
51
+ return self._represent_XOp(None, **options)
52
+
53
+ def _represent_XOp(self, basis, **options):
54
+ x = Symbol('x')
55
+ n = Symbol('n')
56
+ subs_info = options.get('subs', {})
57
+ return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)
58
+
59
+ def _eval_innerproduct_PIABBra(self, bra):
60
+ return KroneckerDelta(bra.label[0], self.label[0])
61
+
62
+
63
+ class PIABBra(Bra):
64
+ """Particle in a box eigenbra."""
65
+
66
+ @classmethod
67
+ def _eval_hilbert_space(cls, label):
68
+ return L2(Interval(S.NegativeInfinity, S.Infinity))
69
+
70
+ @classmethod
71
+ def dual_class(self):
72
+ return PIABKet
janus/lib/python3.10/site-packages/sympy/physics/quantum/qapply.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logic for applying operators to states.
2
+
3
+ Todo:
4
+ * Sometimes the final result needs to be expanded, we should do this by hand.
5
+ """
6
+
7
+ from sympy.core.add import Add
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.power import Pow
10
+ from sympy.core.singleton import S
11
+ from sympy.core.sympify import sympify
12
+
13
+ from sympy.physics.quantum.anticommutator import AntiCommutator
14
+ from sympy.physics.quantum.commutator import Commutator
15
+ from sympy.physics.quantum.dagger import Dagger
16
+ from sympy.physics.quantum.innerproduct import InnerProduct
17
+ from sympy.physics.quantum.operator import OuterProduct, Operator
18
+ from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
19
+ from sympy.physics.quantum.tensorproduct import TensorProduct
20
+
21
+ __all__ = [
22
+ 'qapply'
23
+ ]
24
+
25
+
26
+ #-----------------------------------------------------------------------------
27
+ # Main code
28
+ #-----------------------------------------------------------------------------
29
+
30
+ def qapply(e, **options):
31
+ """Apply operators to states in a quantum expression.
32
+
33
+ Parameters
34
+ ==========
35
+
36
+ e : Expr
37
+ The expression containing operators and states. This expression tree
38
+ will be walked to find operators acting on states symbolically.
39
+ options : dict
40
+ A dict of key/value pairs that determine how the operator actions
41
+ are carried out.
42
+
43
+ The following options are valid:
44
+
45
+ * ``dagger``: try to apply Dagger operators to the left
46
+ (default: False).
47
+ * ``ip_doit``: call ``.doit()`` in inner products when they are
48
+ encountered (default: True).
49
+
50
+ Returns
51
+ =======
52
+
53
+ e : Expr
54
+ The original expression, but with the operators applied to states.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.physics.quantum import qapply, Ket, Bra
60
+ >>> b = Bra('b')
61
+ >>> k = Ket('k')
62
+ >>> A = k * b
63
+ >>> A
64
+ |k><b|
65
+ >>> qapply(A * b.dual / (b * b.dual))
66
+ |k>
67
+ >>> qapply(k.dual * A / (k.dual * k), dagger=True)
68
+ <b|
69
+ >>> qapply(k.dual * A / (k.dual * k))
70
+ <k|*|k><b|/<k|k>
71
+ """
72
+ from sympy.physics.quantum.density import Density
73
+
74
+ dagger = options.get('dagger', False)
75
+
76
+ if e == 0:
77
+ return S.Zero
78
+
79
+ # This may be a bit aggressive but ensures that everything gets expanded
80
+ # to its simplest form before trying to apply operators. This includes
81
+ # things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and
82
+ # TensorProducts. The only problem with this is that if we can't apply
83
+ # all the Operators, we have just expanded everything.
84
+ # TODO: don't expand the scalars in front of each Mul.
85
+ e = e.expand(commutator=True, tensorproduct=True)
86
+
87
+ # If we just have a raw ket, return it.
88
+ if isinstance(e, KetBase):
89
+ return e
90
+
91
+ # We have an Add(a, b, c, ...) and compute
92
+ # Add(qapply(a), qapply(b), ...)
93
+ elif isinstance(e, Add):
94
+ result = 0
95
+ for arg in e.args:
96
+ result += qapply(arg, **options)
97
+ return result.expand()
98
+
99
+ # For a Density operator call qapply on its state
100
+ elif isinstance(e, Density):
101
+ new_args = [(qapply(state, **options), prob) for (state,
102
+ prob) in e.args]
103
+ return Density(*new_args)
104
+
105
+ # For a raw TensorProduct, call qapply on its args.
106
+ elif isinstance(e, TensorProduct):
107
+ return TensorProduct(*[qapply(t, **options) for t in e.args])
108
+
109
+ # For a Pow, call qapply on its base.
110
+ elif isinstance(e, Pow):
111
+ return qapply(e.base, **options)**e.exp
112
+
113
+ # We have a Mul where there might be actual operators to apply to kets.
114
+ elif isinstance(e, Mul):
115
+ c_part, nc_part = e.args_cnc()
116
+ c_mul = Mul(*c_part)
117
+ nc_mul = Mul(*nc_part)
118
+ if isinstance(nc_mul, Mul):
119
+ result = c_mul*qapply_Mul(nc_mul, **options)
120
+ else:
121
+ result = c_mul*qapply(nc_mul, **options)
122
+ if result == e and dagger:
123
+ return Dagger(qapply_Mul(Dagger(e), **options))
124
+ else:
125
+ return result
126
+
127
+ # In all other cases (State, Operator, Pow, Commutator, InnerProduct,
128
+ # OuterProduct) we won't ever have operators to apply to kets.
129
+ else:
130
+ return e
131
+
132
+
133
+ def qapply_Mul(e, **options):
134
+
135
+ ip_doit = options.get('ip_doit', True)
136
+
137
+ args = list(e.args)
138
+
139
+ # If we only have 0 or 1 args, we have nothing to do and return.
140
+ if len(args) <= 1 or not isinstance(e, Mul):
141
+ return e
142
+ rhs = args.pop()
143
+ lhs = args.pop()
144
+
145
+ # Make sure we have two non-commutative objects before proceeding.
146
+ if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \
147
+ (not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative):
148
+ return e
149
+
150
+ # For a Pow with an integer exponent, apply one of them and reduce the
151
+ # exponent by one.
152
+ if isinstance(lhs, Pow) and lhs.exp.is_Integer:
153
+ args.append(lhs.base**(lhs.exp - 1))
154
+ lhs = lhs.base
155
+
156
+ # Pull OuterProduct apart
157
+ if isinstance(lhs, OuterProduct):
158
+ args.append(lhs.ket)
159
+ lhs = lhs.bra
160
+
161
+ # Call .doit() on Commutator/AntiCommutator.
162
+ if isinstance(lhs, (Commutator, AntiCommutator)):
163
+ comm = lhs.doit()
164
+ if isinstance(comm, Add):
165
+ return qapply(
166
+ e.func(*(args + [comm.args[0], rhs])) +
167
+ e.func(*(args + [comm.args[1], rhs])),
168
+ **options
169
+ )
170
+ else:
171
+ return qapply(e.func(*args)*comm*rhs, **options)
172
+
173
+ # Apply tensor products of operators to states
174
+ if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
175
+ isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
176
+ len(lhs.args) == len(rhs.args):
177
+ result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
178
+ return qapply_Mul(e.func(*args), **options)*result
179
+
180
+ # Now try to actually apply the operator and build an inner product.
181
+ try:
182
+ result = lhs._apply_operator(rhs, **options)
183
+ except NotImplementedError:
184
+ result = None
185
+
186
+ if result is None:
187
+ _apply_right = getattr(rhs, '_apply_from_right_to', None)
188
+ if _apply_right is not None:
189
+ try:
190
+ result = _apply_right(lhs, **options)
191
+ except NotImplementedError:
192
+ result = None
193
+
194
+ if result is None:
195
+ if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
196
+ result = InnerProduct(lhs, rhs)
197
+ if ip_doit:
198
+ result = result.doit()
199
+
200
+ # TODO: I may need to expand before returning the final result.
201
+ if result == 0:
202
+ return S.Zero
203
+ elif result is None:
204
+ if len(args) == 0:
205
+ # We had two args to begin with so args=[].
206
+ return e
207
+ else:
208
+ return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs
209
+ elif isinstance(result, InnerProduct):
210
+ return result*qapply_Mul(e.func(*args), **options)
211
+ else: # result is a scalar times a Mul, Add or TensorProduct
212
+ return qapply(e.func(*args)*result, **options)
janus/lib/python3.10/site-packages/sympy/physics/quantum/qexpr.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.core.sympify import sympify
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.printing.pretty.stringpict import prettyForm
6
+ from sympy.core.containers import Tuple
7
+ from sympy.utilities.iterables import is_sequence
8
+
9
+ from sympy.physics.quantum.dagger import Dagger
10
+ from sympy.physics.quantum.matrixutils import (
11
+ numpy_ndarray, scipy_sparse_matrix,
12
+ to_sympy, to_numpy, to_scipy_sparse
13
+ )
14
+
15
+ __all__ = [
16
+ 'QuantumError',
17
+ 'QExpr'
18
+ ]
19
+
20
+
21
+ #-----------------------------------------------------------------------------
22
+ # Error handling
23
+ #-----------------------------------------------------------------------------
24
+
25
+ class QuantumError(Exception):
26
+ pass
27
+
28
+
29
+ def _qsympify_sequence(seq):
30
+ """Convert elements of a sequence to standard form.
31
+
32
+ This is like sympify, but it performs special logic for arguments passed
33
+ to QExpr. The following conversions are done:
34
+
35
+ * (list, tuple, Tuple) => _qsympify_sequence each element and convert
36
+ sequence to a Tuple.
37
+ * basestring => Symbol
38
+ * Matrix => Matrix
39
+ * other => sympify
40
+
41
+ Strings are passed to Symbol, not sympify to make sure that variables like
42
+ 'pi' are kept as Symbols, not the SymPy built-in number subclasses.
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy.physics.quantum.qexpr import _qsympify_sequence
48
+ >>> _qsympify_sequence((1,2,[3,4,[1,]]))
49
+ (1, 2, (3, 4, (1,)))
50
+
51
+ """
52
+
53
+ return tuple(__qsympify_sequence_helper(seq))
54
+
55
+
56
+ def __qsympify_sequence_helper(seq):
57
+ """
58
+ Helper function for _qsympify_sequence
59
+ This function does the actual work.
60
+ """
61
+ #base case. If not a list, do Sympification
62
+ if not is_sequence(seq):
63
+ if isinstance(seq, Matrix):
64
+ return seq
65
+ elif isinstance(seq, str):
66
+ return Symbol(seq)
67
+ else:
68
+ return sympify(seq)
69
+
70
+ # base condition, when seq is QExpr and also
71
+ # is iterable.
72
+ if isinstance(seq, QExpr):
73
+ return seq
74
+
75
+ #if list, recurse on each item in the list
76
+ result = [__qsympify_sequence_helper(item) for item in seq]
77
+
78
+ return Tuple(*result)
79
+
80
+
81
+ #-----------------------------------------------------------------------------
82
+ # Basic Quantum Expression from which all objects descend
83
+ #-----------------------------------------------------------------------------
84
+
85
+ class QExpr(Expr):
86
+ """A base class for all quantum object like operators and states."""
87
+
88
+ # In sympy, slots are for instance attributes that are computed
89
+ # dynamically by the __new__ method. They are not part of args, but they
90
+ # derive from args.
91
+
92
+ # The Hilbert space a quantum Object belongs to.
93
+ __slots__ = ('hilbert_space', )
94
+
95
+ is_commutative = False
96
+
97
+ # The separator used in printing the label.
98
+ _label_separator = ''
99
+
100
+ @property
101
+ def free_symbols(self):
102
+ return {self}
103
+
104
+ def __new__(cls, *args, **kwargs):
105
+ """Construct a new quantum object.
106
+
107
+ Parameters
108
+ ==========
109
+
110
+ args : tuple
111
+ The list of numbers or parameters that uniquely specify the
112
+ quantum object. For a state, this will be its symbol or its
113
+ set of quantum numbers.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy.physics.quantum.qexpr import QExpr
119
+ >>> q = QExpr(0)
120
+ >>> q
121
+ 0
122
+ >>> q.label
123
+ (0,)
124
+ >>> q.hilbert_space
125
+ H
126
+ >>> q.args
127
+ (0,)
128
+ >>> q.is_commutative
129
+ False
130
+ """
131
+
132
+ # First compute args and call Expr.__new__ to create the instance
133
+ args = cls._eval_args(args, **kwargs)
134
+ if len(args) == 0:
135
+ args = cls._eval_args(tuple(cls.default_args()), **kwargs)
136
+ inst = Expr.__new__(cls, *args)
137
+ # Now set the slots on the instance
138
+ inst.hilbert_space = cls._eval_hilbert_space(args)
139
+ return inst
140
+
141
+ @classmethod
142
+ def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
143
+ """Create new instance of this class with hilbert_space and args.
144
+
145
+ This is used to bypass the more complex logic in the ``__new__``
146
+ method in cases where you already have the exact ``hilbert_space``
147
+ and ``args``. This should be used when you are positive these
148
+ arguments are valid, in their final, proper form and want to optimize
149
+ the creation of the object.
150
+ """
151
+
152
+ obj = Expr.__new__(cls, *args, **old_assumptions)
153
+ obj.hilbert_space = hilbert_space
154
+ return obj
155
+
156
+ #-------------------------------------------------------------------------
157
+ # Properties
158
+ #-------------------------------------------------------------------------
159
+
160
+ @property
161
+ def label(self):
162
+ """The label is the unique set of identifiers for the object.
163
+
164
+ Usually, this will include all of the information about the state
165
+ *except* the time (in the case of time-dependent objects).
166
+
167
+ This must be a tuple, rather than a Tuple.
168
+ """
169
+ if len(self.args) == 0: # If there is no label specified, return the default
170
+ return self._eval_args(list(self.default_args()))
171
+ else:
172
+ return self.args
173
+
174
+ @property
175
+ def is_symbolic(self):
176
+ return True
177
+
178
+ @classmethod
179
+ def default_args(self):
180
+ """If no arguments are specified, then this will return a default set
181
+ of arguments to be run through the constructor.
182
+
183
+ NOTE: Any classes that override this MUST return a tuple of arguments.
184
+ Should be overridden by subclasses to specify the default arguments for kets and operators
185
+ """
186
+ raise NotImplementedError("No default arguments for this class!")
187
+
188
+ #-------------------------------------------------------------------------
189
+ # _eval_* methods
190
+ #-------------------------------------------------------------------------
191
+
192
+ def _eval_adjoint(self):
193
+ obj = Expr._eval_adjoint(self)
194
+ if obj is None:
195
+ obj = Expr.__new__(Dagger, self)
196
+ if isinstance(obj, QExpr):
197
+ obj.hilbert_space = self.hilbert_space
198
+ return obj
199
+
200
+ @classmethod
201
+ def _eval_args(cls, args):
202
+ """Process the args passed to the __new__ method.
203
+
204
+ This simply runs args through _qsympify_sequence.
205
+ """
206
+ return _qsympify_sequence(args)
207
+
208
+ @classmethod
209
+ def _eval_hilbert_space(cls, args):
210
+ """Compute the Hilbert space instance from the args.
211
+ """
212
+ from sympy.physics.quantum.hilbert import HilbertSpace
213
+ return HilbertSpace()
214
+
215
+ #-------------------------------------------------------------------------
216
+ # Printing
217
+ #-------------------------------------------------------------------------
218
+
219
+ # Utilities for printing: these operate on raw SymPy objects
220
+
221
+ def _print_sequence(self, seq, sep, printer, *args):
222
+ result = []
223
+ for item in seq:
224
+ result.append(printer._print(item, *args))
225
+ return sep.join(result)
226
+
227
+ def _print_sequence_pretty(self, seq, sep, printer, *args):
228
+ pform = printer._print(seq[0], *args)
229
+ for item in seq[1:]:
230
+ pform = prettyForm(*pform.right(sep))
231
+ pform = prettyForm(*pform.right(printer._print(item, *args)))
232
+ return pform
233
+
234
+ # Utilities for printing: these operate prettyForm objects
235
+
236
+ def _print_subscript_pretty(self, a, b):
237
+ top = prettyForm(*b.left(' '*a.width()))
238
+ bot = prettyForm(*a.right(' '*b.width()))
239
+ return prettyForm(binding=prettyForm.POW, *bot.below(top))
240
+
241
+ def _print_superscript_pretty(self, a, b):
242
+ return a**b
243
+
244
+ def _print_parens_pretty(self, pform, left='(', right=')'):
245
+ return prettyForm(*pform.parens(left=left, right=right))
246
+
247
+ # Printing of labels (i.e. args)
248
+
249
+ def _print_label(self, printer, *args):
250
+ """Prints the label of the QExpr
251
+
252
+ This method prints self.label, using self._label_separator to separate
253
+ the elements. This method should not be overridden, instead, override
254
+ _print_contents to change printing behavior.
255
+ """
256
+ return self._print_sequence(
257
+ self.label, self._label_separator, printer, *args
258
+ )
259
+
260
+ def _print_label_repr(self, printer, *args):
261
+ return self._print_sequence(
262
+ self.label, ',', printer, *args
263
+ )
264
+
265
+ def _print_label_pretty(self, printer, *args):
266
+ return self._print_sequence_pretty(
267
+ self.label, self._label_separator, printer, *args
268
+ )
269
+
270
+ def _print_label_latex(self, printer, *args):
271
+ return self._print_sequence(
272
+ self.label, self._label_separator, printer, *args
273
+ )
274
+
275
+ # Printing of contents (default to label)
276
+
277
+ def _print_contents(self, printer, *args):
278
+ """Printer for contents of QExpr
279
+
280
+ Handles the printing of any unique identifying contents of a QExpr to
281
+ print as its contents, such as any variables or quantum numbers. The
282
+ default is to print the label, which is almost always the args. This
283
+ should not include printing of any brackets or parentheses.
284
+ """
285
+ return self._print_label(printer, *args)
286
+
287
+ def _print_contents_pretty(self, printer, *args):
288
+ return self._print_label_pretty(printer, *args)
289
+
290
+ def _print_contents_latex(self, printer, *args):
291
+ return self._print_label_latex(printer, *args)
292
+
293
+ # Main printing methods
294
+
295
+ def _sympystr(self, printer, *args):
296
+ """Default printing behavior of QExpr objects
297
+
298
+ Handles the default printing of a QExpr. To add other things to the
299
+ printing of the object, such as an operator name to operators or
300
+ brackets to states, the class should override the _print/_pretty/_latex
301
+ functions directly and make calls to _print_contents where appropriate.
302
+ This allows things like InnerProduct to easily control its printing the
303
+ printing of contents.
304
+ """
305
+ return self._print_contents(printer, *args)
306
+
307
+ def _sympyrepr(self, printer, *args):
308
+ classname = self.__class__.__name__
309
+ label = self._print_label_repr(printer, *args)
310
+ return '%s(%s)' % (classname, label)
311
+
312
+ def _pretty(self, printer, *args):
313
+ pform = self._print_contents_pretty(printer, *args)
314
+ return pform
315
+
316
+ def _latex(self, printer, *args):
317
+ return self._print_contents_latex(printer, *args)
318
+
319
+ #-------------------------------------------------------------------------
320
+ # Represent
321
+ #-------------------------------------------------------------------------
322
+
323
+ def _represent_default_basis(self, **options):
324
+ raise NotImplementedError('This object does not have a default basis')
325
+
326
+ def _represent(self, *, basis=None, **options):
327
+ """Represent this object in a given basis.
328
+
329
+ This method dispatches to the actual methods that perform the
330
+ representation. Subclases of QExpr should define various methods to
331
+ determine how the object will be represented in various bases. The
332
+ format of these methods is::
333
+
334
+ def _represent_BasisName(self, basis, **options):
335
+
336
+ Thus to define how a quantum object is represented in the basis of
337
+ the operator Position, you would define::
338
+
339
+ def _represent_Position(self, basis, **options):
340
+
341
+ Usually, basis object will be instances of Operator subclasses, but
342
+ there is a chance we will relax this in the future to accommodate other
343
+ types of basis sets that are not associated with an operator.
344
+
345
+ If the ``format`` option is given it can be ("sympy", "numpy",
346
+ "scipy.sparse"). This will ensure that any matrices that result from
347
+ representing the object are returned in the appropriate matrix format.
348
+
349
+ Parameters
350
+ ==========
351
+
352
+ basis : Operator
353
+ The Operator whose basis functions will be used as the basis for
354
+ representation.
355
+ options : dict
356
+ A dictionary of key/value pairs that give options and hints for
357
+ the representation, such as the number of basis functions to
358
+ be used.
359
+ """
360
+ if basis is None:
361
+ result = self._represent_default_basis(**options)
362
+ else:
363
+ result = dispatch_method(self, '_represent', basis, **options)
364
+
365
+ # If we get a matrix representation, convert it to the right format.
366
+ format = options.get('format', 'sympy')
367
+ result = self._format_represent(result, format)
368
+ return result
369
+
370
+ def _format_represent(self, result, format):
371
+ if format == 'sympy' and not isinstance(result, Matrix):
372
+ return to_sympy(result)
373
+ elif format == 'numpy' and not isinstance(result, numpy_ndarray):
374
+ return to_numpy(result)
375
+ elif format == 'scipy.sparse' and \
376
+ not isinstance(result, scipy_sparse_matrix):
377
+ return to_scipy_sparse(result)
378
+
379
+ return result
380
+
381
+
382
+ def split_commutative_parts(e):
383
+ """Split into commutative and non-commutative parts."""
384
+ c_part, nc_part = e.args_cnc()
385
+ c_part = list(c_part)
386
+ return c_part, nc_part
387
+
388
+
389
+ def split_qexpr_parts(e):
390
+ """Split an expression into Expr and noncommutative QExpr parts."""
391
+ expr_part = []
392
+ qexpr_part = []
393
+ for arg in e.args:
394
+ if not isinstance(arg, QExpr):
395
+ expr_part.append(arg)
396
+ else:
397
+ qexpr_part.append(arg)
398
+ return expr_part, qexpr_part
399
+
400
+
401
+ def dispatch_method(self, basename, arg, **options):
402
+ """Dispatch a method to the proper handlers."""
403
+ method_name = '%s_%s' % (basename, arg.__class__.__name__)
404
+ if hasattr(self, method_name):
405
+ f = getattr(self, method_name)
406
+ # This can raise and we will allow it to propagate.
407
+ result = f(arg, **options)
408
+ if result is not None:
409
+ return result
410
+ raise NotImplementedError(
411
+ "%s.%s cannot handle: %r" %
412
+ (self.__class__.__name__, basename, arg)
413
+ )
janus/lib/python3.10/site-packages/sympy/physics/quantum/sho1d.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simple Harmonic Oscillator 1-Dimension"""
2
+
3
+ from sympy.core.numbers import (I, Integer)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.physics.quantum.constants import hbar
8
+ from sympy.physics.quantum.operator import Operator
9
+ from sympy.physics.quantum.state import Bra, Ket, State
10
+ from sympy.physics.quantum.qexpr import QExpr
11
+ from sympy.physics.quantum.cartesian import X, Px
12
+ from sympy.functions.special.tensor_functions import KroneckerDelta
13
+ from sympy.physics.quantum.hilbert import ComplexSpace
14
+ from sympy.physics.quantum.matrixutils import matrix_zeros
15
+
16
+ #------------------------------------------------------------------------------
17
+
18
+ class SHOOp(Operator):
19
+ """A base class for the SHO Operators.
20
+
21
+ We are limiting the number of arguments to be 1.
22
+
23
+ """
24
+
25
+ @classmethod
26
+ def _eval_args(cls, args):
27
+ args = QExpr._eval_args(args)
28
+ if len(args) == 1:
29
+ return args
30
+ else:
31
+ raise ValueError("Too many arguments")
32
+
33
+ @classmethod
34
+ def _eval_hilbert_space(cls, label):
35
+ return ComplexSpace(S.Infinity)
36
+
37
+ class RaisingOp(SHOOp):
38
+ """The Raising Operator or a^dagger.
39
+
40
+ When a^dagger acts on a state it raises the state up by one. Taking
41
+ the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger
42
+ can be rewritten in terms of position and momentum. We can represent
43
+ a^dagger as a matrix, which will be its default basis.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ args : tuple
49
+ The list of numbers or parameters that uniquely specify the
50
+ operator.
51
+
52
+ Examples
53
+ ========
54
+
55
+ Create a Raising Operator and rewrite it in terms of position and
56
+ momentum, and show that taking its adjoint returns 'a':
57
+
58
+ >>> from sympy.physics.quantum.sho1d import RaisingOp
59
+ >>> from sympy.physics.quantum import Dagger
60
+
61
+ >>> ad = RaisingOp('a')
62
+ >>> ad.rewrite('xp').doit()
63
+ sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
64
+
65
+ >>> Dagger(ad)
66
+ a
67
+
68
+ Taking the commutator of a^dagger with other Operators:
69
+
70
+ >>> from sympy.physics.quantum import Commutator
71
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
72
+ >>> from sympy.physics.quantum.sho1d import NumberOp
73
+
74
+ >>> ad = RaisingOp('a')
75
+ >>> a = LoweringOp('a')
76
+ >>> N = NumberOp('N')
77
+ >>> Commutator(ad, a).doit()
78
+ -1
79
+ >>> Commutator(ad, N).doit()
80
+ -RaisingOp(a)
81
+
82
+ Apply a^dagger to a state:
83
+
84
+ >>> from sympy.physics.quantum import qapply
85
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet
86
+
87
+ >>> ad = RaisingOp('a')
88
+ >>> k = SHOKet('k')
89
+ >>> qapply(ad*k)
90
+ sqrt(k + 1)*|k + 1>
91
+
92
+ Matrix Representation
93
+
94
+ >>> from sympy.physics.quantum.sho1d import RaisingOp
95
+ >>> from sympy.physics.quantum.represent import represent
96
+ >>> ad = RaisingOp('a')
97
+ >>> represent(ad, basis=N, ndim=4, format='sympy')
98
+ Matrix([
99
+ [0, 0, 0, 0],
100
+ [1, 0, 0, 0],
101
+ [0, sqrt(2), 0, 0],
102
+ [0, 0, sqrt(3), 0]])
103
+
104
+ """
105
+
106
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
107
+ return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
108
+ S.NegativeOne*I*Px + m*omega*X)
109
+
110
+ def _eval_adjoint(self):
111
+ return LoweringOp(*self.args)
112
+
113
+ def _eval_commutator_LoweringOp(self, other):
114
+ return S.NegativeOne
115
+
116
+ def _eval_commutator_NumberOp(self, other):
117
+ return S.NegativeOne*self
118
+
119
+ def _apply_operator_SHOKet(self, ket, **options):
120
+ temp = ket.n + S.One
121
+ return sqrt(temp)*SHOKet(temp)
122
+
123
+ def _represent_default_basis(self, **options):
124
+ return self._represent_NumberOp(None, **options)
125
+
126
+ def _represent_XOp(self, basis, **options):
127
+ # This logic is good but the underlying position
128
+ # representation logic is broken.
129
+ # temp = self.rewrite('xp').doit()
130
+ # result = represent(temp, basis=X)
131
+ # return result
132
+ raise NotImplementedError('Position representation is not implemented')
133
+
134
+ def _represent_NumberOp(self, basis, **options):
135
+ ndim_info = options.get('ndim', 4)
136
+ format = options.get('format','sympy')
137
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
138
+ for i in range(ndim_info - 1):
139
+ value = sqrt(i + 1)
140
+ if format == 'scipy.sparse':
141
+ value = float(value)
142
+ matrix[i + 1, i] = value
143
+ if format == 'scipy.sparse':
144
+ matrix = matrix.tocsr()
145
+ return matrix
146
+
147
+ #--------------------------------------------------------------------------
148
+ # Printing Methods
149
+ #--------------------------------------------------------------------------
150
+
151
+ def _print_contents(self, printer, *args):
152
+ arg0 = printer._print(self.args[0], *args)
153
+ return '%s(%s)' % (self.__class__.__name__, arg0)
154
+
155
+ def _print_contents_pretty(self, printer, *args):
156
+ from sympy.printing.pretty.stringpict import prettyForm
157
+ pform = printer._print(self.args[0], *args)
158
+ pform = pform**prettyForm('\N{DAGGER}')
159
+ return pform
160
+
161
+ def _print_contents_latex(self, printer, *args):
162
+ arg = printer._print(self.args[0])
163
+ return '%s^{\\dagger}' % arg
164
+
165
+ class LoweringOp(SHOOp):
166
+ """The Lowering Operator or 'a'.
167
+
168
+ When 'a' acts on a state it lowers the state up by one. Taking
169
+ the adjoint of 'a' returns a^dagger, the Raising Operator. 'a'
170
+ can be rewritten in terms of position and momentum. We can
171
+ represent 'a' as a matrix, which will be its default basis.
172
+
173
+ Parameters
174
+ ==========
175
+
176
+ args : tuple
177
+ The list of numbers or parameters that uniquely specify the
178
+ operator.
179
+
180
+ Examples
181
+ ========
182
+
183
+ Create a Lowering Operator and rewrite it in terms of position and
184
+ momentum, and show that taking its adjoint returns a^dagger:
185
+
186
+ >>> from sympy.physics.quantum.sho1d import LoweringOp
187
+ >>> from sympy.physics.quantum import Dagger
188
+
189
+ >>> a = LoweringOp('a')
190
+ >>> a.rewrite('xp').doit()
191
+ sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega))
192
+
193
+ >>> Dagger(a)
194
+ RaisingOp(a)
195
+
196
+ Taking the commutator of 'a' with other Operators:
197
+
198
+ >>> from sympy.physics.quantum import Commutator
199
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp
200
+ >>> from sympy.physics.quantum.sho1d import NumberOp
201
+
202
+ >>> a = LoweringOp('a')
203
+ >>> ad = RaisingOp('a')
204
+ >>> N = NumberOp('N')
205
+ >>> Commutator(a, ad).doit()
206
+ 1
207
+ >>> Commutator(a, N).doit()
208
+ a
209
+
210
+ Apply 'a' to a state:
211
+
212
+ >>> from sympy.physics.quantum import qapply
213
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
214
+
215
+ >>> a = LoweringOp('a')
216
+ >>> k = SHOKet('k')
217
+ >>> qapply(a*k)
218
+ sqrt(k)*|k - 1>
219
+
220
+ Taking 'a' of the lowest state will return 0:
221
+
222
+ >>> from sympy.physics.quantum import qapply
223
+ >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet
224
+
225
+ >>> a = LoweringOp('a')
226
+ >>> k = SHOKet(0)
227
+ >>> qapply(a*k)
228
+ 0
229
+
230
+ Matrix Representation
231
+
232
+ >>> from sympy.physics.quantum.sho1d import LoweringOp
233
+ >>> from sympy.physics.quantum.represent import represent
234
+ >>> a = LoweringOp('a')
235
+ >>> represent(a, basis=N, ndim=4, format='sympy')
236
+ Matrix([
237
+ [0, 1, 0, 0],
238
+ [0, 0, sqrt(2), 0],
239
+ [0, 0, 0, sqrt(3)],
240
+ [0, 0, 0, 0]])
241
+
242
+ """
243
+
244
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
245
+ return (S.One/sqrt(Integer(2)*hbar*m*omega))*(
246
+ I*Px + m*omega*X)
247
+
248
+ def _eval_adjoint(self):
249
+ return RaisingOp(*self.args)
250
+
251
+ def _eval_commutator_RaisingOp(self, other):
252
+ return S.One
253
+
254
+ def _eval_commutator_NumberOp(self, other):
255
+ return self
256
+
257
+ def _apply_operator_SHOKet(self, ket, **options):
258
+ temp = ket.n - Integer(1)
259
+ if ket.n is S.Zero:
260
+ return S.Zero
261
+ else:
262
+ return sqrt(ket.n)*SHOKet(temp)
263
+
264
+ def _represent_default_basis(self, **options):
265
+ return self._represent_NumberOp(None, **options)
266
+
267
+ def _represent_XOp(self, basis, **options):
268
+ # This logic is good but the underlying position
269
+ # representation logic is broken.
270
+ # temp = self.rewrite('xp').doit()
271
+ # result = represent(temp, basis=X)
272
+ # return result
273
+ raise NotImplementedError('Position representation is not implemented')
274
+
275
+ def _represent_NumberOp(self, basis, **options):
276
+ ndim_info = options.get('ndim', 4)
277
+ format = options.get('format', 'sympy')
278
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
279
+ for i in range(ndim_info - 1):
280
+ value = sqrt(i + 1)
281
+ if format == 'scipy.sparse':
282
+ value = float(value)
283
+ matrix[i,i + 1] = value
284
+ if format == 'scipy.sparse':
285
+ matrix = matrix.tocsr()
286
+ return matrix
287
+
288
+
289
+ class NumberOp(SHOOp):
290
+ """The Number Operator is simply a^dagger*a
291
+
292
+ It is often useful to write a^dagger*a as simply the Number Operator
293
+ because the Number Operator commutes with the Hamiltonian. And can be
294
+ expressed using the Number Operator. Also the Number Operator can be
295
+ applied to states. We can represent the Number Operator as a matrix,
296
+ which will be its default basis.
297
+
298
+ Parameters
299
+ ==========
300
+
301
+ args : tuple
302
+ The list of numbers or parameters that uniquely specify the
303
+ operator.
304
+
305
+ Examples
306
+ ========
307
+
308
+ Create a Number Operator and rewrite it in terms of the ladder
309
+ operators, position and momentum operators, and Hamiltonian:
310
+
311
+ >>> from sympy.physics.quantum.sho1d import NumberOp
312
+
313
+ >>> N = NumberOp('N')
314
+ >>> N.rewrite('a').doit()
315
+ RaisingOp(a)*a
316
+ >>> N.rewrite('xp').doit()
317
+ -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega)
318
+ >>> N.rewrite('H').doit()
319
+ -1/2 + H/(hbar*omega)
320
+
321
+ Take the Commutator of the Number Operator with other Operators:
322
+
323
+ >>> from sympy.physics.quantum import Commutator
324
+ >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian
325
+ >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp
326
+
327
+ >>> N = NumberOp('N')
328
+ >>> H = Hamiltonian('H')
329
+ >>> ad = RaisingOp('a')
330
+ >>> a = LoweringOp('a')
331
+ >>> Commutator(N,H).doit()
332
+ 0
333
+ >>> Commutator(N,ad).doit()
334
+ RaisingOp(a)
335
+ >>> Commutator(N,a).doit()
336
+ -a
337
+
338
+ Apply the Number Operator to a state:
339
+
340
+ >>> from sympy.physics.quantum import qapply
341
+ >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet
342
+
343
+ >>> N = NumberOp('N')
344
+ >>> k = SHOKet('k')
345
+ >>> qapply(N*k)
346
+ k*|k>
347
+
348
+ Matrix Representation
349
+
350
+ >>> from sympy.physics.quantum.sho1d import NumberOp
351
+ >>> from sympy.physics.quantum.represent import represent
352
+ >>> N = NumberOp('N')
353
+ >>> represent(N, basis=N, ndim=4, format='sympy')
354
+ Matrix([
355
+ [0, 0, 0, 0],
356
+ [0, 1, 0, 0],
357
+ [0, 0, 2, 0],
358
+ [0, 0, 0, 3]])
359
+
360
+ """
361
+
362
+ def _eval_rewrite_as_a(self, *args, **kwargs):
363
+ return ad*a
364
+
365
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
366
+ return (S.One/(Integer(2)*m*hbar*omega))*(Px**2 + (
367
+ m*omega*X)**2) - S.Half
368
+
369
+ def _eval_rewrite_as_H(self, *args, **kwargs):
370
+ return H/(hbar*omega) - S.Half
371
+
372
+ def _apply_operator_SHOKet(self, ket, **options):
373
+ return ket.n*ket
374
+
375
+ def _eval_commutator_Hamiltonian(self, other):
376
+ return S.Zero
377
+
378
+ def _eval_commutator_RaisingOp(self, other):
379
+ return other
380
+
381
+ def _eval_commutator_LoweringOp(self, other):
382
+ return S.NegativeOne*other
383
+
384
+ def _represent_default_basis(self, **options):
385
+ return self._represent_NumberOp(None, **options)
386
+
387
+ def _represent_XOp(self, basis, **options):
388
+ # This logic is good but the underlying position
389
+ # representation logic is broken.
390
+ # temp = self.rewrite('xp').doit()
391
+ # result = represent(temp, basis=X)
392
+ # return result
393
+ raise NotImplementedError('Position representation is not implemented')
394
+
395
+ def _represent_NumberOp(self, basis, **options):
396
+ ndim_info = options.get('ndim', 4)
397
+ format = options.get('format', 'sympy')
398
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
399
+ for i in range(ndim_info):
400
+ value = i
401
+ if format == 'scipy.sparse':
402
+ value = float(value)
403
+ matrix[i,i] = value
404
+ if format == 'scipy.sparse':
405
+ matrix = matrix.tocsr()
406
+ return matrix
407
+
408
+
409
+ class Hamiltonian(SHOOp):
410
+ """The Hamiltonian Operator.
411
+
412
+ The Hamiltonian is used to solve the time-independent Schrodinger
413
+ equation. The Hamiltonian can be expressed using the ladder operators,
414
+ as well as by position and momentum. We can represent the Hamiltonian
415
+ Operator as a matrix, which will be its default basis.
416
+
417
+ Parameters
418
+ ==========
419
+
420
+ args : tuple
421
+ The list of numbers or parameters that uniquely specify the
422
+ operator.
423
+
424
+ Examples
425
+ ========
426
+
427
+ Create a Hamiltonian Operator and rewrite it in terms of the ladder
428
+ operators, position and momentum, and the Number Operator:
429
+
430
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian
431
+
432
+ >>> H = Hamiltonian('H')
433
+ >>> H.rewrite('a').doit()
434
+ hbar*omega*(1/2 + RaisingOp(a)*a)
435
+ >>> H.rewrite('xp').doit()
436
+ (m**2*omega**2*X**2 + Px**2)/(2*m)
437
+ >>> H.rewrite('N').doit()
438
+ hbar*omega*(1/2 + N)
439
+
440
+ Take the Commutator of the Hamiltonian and the Number Operator:
441
+
442
+ >>> from sympy.physics.quantum import Commutator
443
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp
444
+
445
+ >>> H = Hamiltonian('H')
446
+ >>> N = NumberOp('N')
447
+ >>> Commutator(H,N).doit()
448
+ 0
449
+
450
+ Apply the Hamiltonian Operator to a state:
451
+
452
+ >>> from sympy.physics.quantum import qapply
453
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet
454
+
455
+ >>> H = Hamiltonian('H')
456
+ >>> k = SHOKet('k')
457
+ >>> qapply(H*k)
458
+ hbar*k*omega*|k> + hbar*omega*|k>/2
459
+
460
+ Matrix Representation
461
+
462
+ >>> from sympy.physics.quantum.sho1d import Hamiltonian
463
+ >>> from sympy.physics.quantum.represent import represent
464
+
465
+ >>> H = Hamiltonian('H')
466
+ >>> represent(H, basis=N, ndim=4, format='sympy')
467
+ Matrix([
468
+ [hbar*omega/2, 0, 0, 0],
469
+ [ 0, 3*hbar*omega/2, 0, 0],
470
+ [ 0, 0, 5*hbar*omega/2, 0],
471
+ [ 0, 0, 0, 7*hbar*omega/2]])
472
+
473
+ """
474
+
475
+ def _eval_rewrite_as_a(self, *args, **kwargs):
476
+ return hbar*omega*(ad*a + S.Half)
477
+
478
+ def _eval_rewrite_as_xp(self, *args, **kwargs):
479
+ return (S.One/(Integer(2)*m))*(Px**2 + (m*omega*X)**2)
480
+
481
+ def _eval_rewrite_as_N(self, *args, **kwargs):
482
+ return hbar*omega*(N + S.Half)
483
+
484
+ def _apply_operator_SHOKet(self, ket, **options):
485
+ return (hbar*omega*(ket.n + S.Half))*ket
486
+
487
+ def _eval_commutator_NumberOp(self, other):
488
+ return S.Zero
489
+
490
+ def _represent_default_basis(self, **options):
491
+ return self._represent_NumberOp(None, **options)
492
+
493
+ def _represent_XOp(self, basis, **options):
494
+ # This logic is good but the underlying position
495
+ # representation logic is broken.
496
+ # temp = self.rewrite('xp').doit()
497
+ # result = represent(temp, basis=X)
498
+ # return result
499
+ raise NotImplementedError('Position representation is not implemented')
500
+
501
+ def _represent_NumberOp(self, basis, **options):
502
+ ndim_info = options.get('ndim', 4)
503
+ format = options.get('format', 'sympy')
504
+ matrix = matrix_zeros(ndim_info, ndim_info, **options)
505
+ for i in range(ndim_info):
506
+ value = i + S.Half
507
+ if format == 'scipy.sparse':
508
+ value = float(value)
509
+ matrix[i,i] = value
510
+ if format == 'scipy.sparse':
511
+ matrix = matrix.tocsr()
512
+ return hbar*omega*matrix
513
+
514
+ #------------------------------------------------------------------------------
515
+
516
+ class SHOState(State):
517
+ """State class for SHO states"""
518
+
519
+ @classmethod
520
+ def _eval_hilbert_space(cls, label):
521
+ return ComplexSpace(S.Infinity)
522
+
523
+ @property
524
+ def n(self):
525
+ return self.args[0]
526
+
527
+
528
+ class SHOKet(SHOState, Ket):
529
+ """1D eigenket.
530
+
531
+ Inherits from SHOState and Ket.
532
+
533
+ Parameters
534
+ ==========
535
+
536
+ args : tuple
537
+ The list of numbers or parameters that uniquely specify the ket
538
+ This is usually its quantum numbers or its symbol.
539
+
540
+ Examples
541
+ ========
542
+
543
+ Ket's know about their associated bra:
544
+
545
+ >>> from sympy.physics.quantum.sho1d import SHOKet
546
+
547
+ >>> k = SHOKet('k')
548
+ >>> k.dual
549
+ <k|
550
+ >>> k.dual_class()
551
+ <class 'sympy.physics.quantum.sho1d.SHOBra'>
552
+
553
+ Take the Inner Product with a bra:
554
+
555
+ >>> from sympy.physics.quantum import InnerProduct
556
+ >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra
557
+
558
+ >>> k = SHOKet('k')
559
+ >>> b = SHOBra('b')
560
+ >>> InnerProduct(b,k).doit()
561
+ KroneckerDelta(b, k)
562
+
563
+ Vector representation of a numerical state ket:
564
+
565
+ >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp
566
+ >>> from sympy.physics.quantum.represent import represent
567
+
568
+ >>> k = SHOKet(3)
569
+ >>> N = NumberOp('N')
570
+ >>> represent(k, basis=N, ndim=4)
571
+ Matrix([
572
+ [0],
573
+ [0],
574
+ [0],
575
+ [1]])
576
+
577
+ """
578
+
579
+ @classmethod
580
+ def dual_class(self):
581
+ return SHOBra
582
+
583
+ def _eval_innerproduct_SHOBra(self, bra, **hints):
584
+ result = KroneckerDelta(self.n, bra.n)
585
+ return result
586
+
587
+ def _represent_default_basis(self, **options):
588
+ return self._represent_NumberOp(None, **options)
589
+
590
+ def _represent_NumberOp(self, basis, **options):
591
+ ndim_info = options.get('ndim', 4)
592
+ format = options.get('format', 'sympy')
593
+ options['spmatrix'] = 'lil'
594
+ vector = matrix_zeros(ndim_info, 1, **options)
595
+ if isinstance(self.n, Integer):
596
+ if self.n >= ndim_info:
597
+ return ValueError("N-Dimension too small")
598
+ if format == 'scipy.sparse':
599
+ vector[int(self.n), 0] = 1.0
600
+ vector = vector.tocsr()
601
+ elif format == 'numpy':
602
+ vector[int(self.n), 0] = 1.0
603
+ else:
604
+ vector[self.n, 0] = S.One
605
+ return vector
606
+ else:
607
+ return ValueError("Not Numerical State")
608
+
609
+
610
+ class SHOBra(SHOState, Bra):
611
+ """A time-independent Bra in SHO.
612
+
613
+ Inherits from SHOState and Bra.
614
+
615
+ Parameters
616
+ ==========
617
+
618
+ args : tuple
619
+ The list of numbers or parameters that uniquely specify the ket
620
+ This is usually its quantum numbers or its symbol.
621
+
622
+ Examples
623
+ ========
624
+
625
+ Bra's know about their associated ket:
626
+
627
+ >>> from sympy.physics.quantum.sho1d import SHOBra
628
+
629
+ >>> b = SHOBra('b')
630
+ >>> b.dual
631
+ |b>
632
+ >>> b.dual_class()
633
+ <class 'sympy.physics.quantum.sho1d.SHOKet'>
634
+
635
+ Vector representation of a numerical state bra:
636
+
637
+ >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp
638
+ >>> from sympy.physics.quantum.represent import represent
639
+
640
+ >>> b = SHOBra(3)
641
+ >>> N = NumberOp('N')
642
+ >>> represent(b, basis=N, ndim=4)
643
+ Matrix([[0, 0, 0, 1]])
644
+
645
+ """
646
+
647
+ @classmethod
648
+ def dual_class(self):
649
+ return SHOKet
650
+
651
+ def _represent_default_basis(self, **options):
652
+ return self._represent_NumberOp(None, **options)
653
+
654
+ def _represent_NumberOp(self, basis, **options):
655
+ ndim_info = options.get('ndim', 4)
656
+ format = options.get('format', 'sympy')
657
+ options['spmatrix'] = 'lil'
658
+ vector = matrix_zeros(1, ndim_info, **options)
659
+ if isinstance(self.n, Integer):
660
+ if self.n >= ndim_info:
661
+ return ValueError("N-Dimension too small")
662
+ if format == 'scipy.sparse':
663
+ vector[0, int(self.n)] = 1.0
664
+ vector = vector.tocsr()
665
+ elif format == 'numpy':
666
+ vector[0, int(self.n)] = 1.0
667
+ else:
668
+ vector[0, self.n] = S.One
669
+ return vector
670
+ else:
671
+ return ValueError("Not Numerical State")
672
+
673
+
674
+ ad = RaisingOp('a')
675
+ a = LoweringOp('a')
676
+ H = Hamiltonian('H')
677
+ N = NumberOp('N')
678
+ omega = Symbol('omega')
679
+ m = Symbol('m')
janus/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
janus/lib/python3.10/site-packages/sympy/physics/quantum/tensorproduct.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract tensor product."""
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.power import Pow
7
+ from sympy.core.sympify import sympify
8
+ from sympy.matrices.dense import DenseMatrix as Matrix
9
+ from sympy.matrices.immutable import ImmutableDenseMatrix as ImmutableMatrix
10
+ from sympy.printing.pretty.stringpict import prettyForm
11
+
12
+ from sympy.physics.quantum.qexpr import QuantumError
13
+ from sympy.physics.quantum.dagger import Dagger
14
+ from sympy.physics.quantum.commutator import Commutator
15
+ from sympy.physics.quantum.anticommutator import AntiCommutator
16
+ from sympy.physics.quantum.state import Ket, Bra
17
+ from sympy.physics.quantum.matrixutils import (
18
+ numpy_ndarray,
19
+ scipy_sparse_matrix,
20
+ matrix_tensor_product
21
+ )
22
+ from sympy.physics.quantum.trace import Tr
23
+
24
+
25
+ __all__ = [
26
+ 'TensorProduct',
27
+ 'tensor_product_simp'
28
+ ]
29
+
30
+ #-----------------------------------------------------------------------------
31
+ # Tensor product
32
+ #-----------------------------------------------------------------------------
33
+
34
+ _combined_printing = False
35
+
36
+
37
+ def combined_tensor_printing(combined):
38
+ """Set flag controlling whether tensor products of states should be
39
+ printed as a combined bra/ket or as an explicit tensor product of different
40
+ bra/kets. This is a global setting for all TensorProduct class instances.
41
+
42
+ Parameters
43
+ ----------
44
+ combine : bool
45
+ When true, tensor product states are combined into one ket/bra, and
46
+ when false explicit tensor product notation is used between each
47
+ ket/bra.
48
+ """
49
+ global _combined_printing
50
+ _combined_printing = combined
51
+
52
+
53
+ class TensorProduct(Expr):
54
+ """The tensor product of two or more arguments.
55
+
56
+ For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker
57
+ or tensor product matrix. For other objects a symbolic ``TensorProduct``
58
+ instance is returned. The tensor product is a non-commutative
59
+ multiplication that is used primarily with operators and states in quantum
60
+ mechanics.
61
+
62
+ Currently, the tensor product distinguishes between commutative and
63
+ non-commutative arguments. Commutative arguments are assumed to be scalars
64
+ and are pulled out in front of the ``TensorProduct``. Non-commutative
65
+ arguments remain in the resulting ``TensorProduct``.
66
+
67
+ Parameters
68
+ ==========
69
+
70
+ args : tuple
71
+ A sequence of the objects to take the tensor product of.
72
+
73
+ Examples
74
+ ========
75
+
76
+ Start with a simple tensor product of SymPy matrices::
77
+
78
+ >>> from sympy import Matrix
79
+ >>> from sympy.physics.quantum import TensorProduct
80
+
81
+ >>> m1 = Matrix([[1,2],[3,4]])
82
+ >>> m2 = Matrix([[1,0],[0,1]])
83
+ >>> TensorProduct(m1, m2)
84
+ Matrix([
85
+ [1, 0, 2, 0],
86
+ [0, 1, 0, 2],
87
+ [3, 0, 4, 0],
88
+ [0, 3, 0, 4]])
89
+ >>> TensorProduct(m2, m1)
90
+ Matrix([
91
+ [1, 2, 0, 0],
92
+ [3, 4, 0, 0],
93
+ [0, 0, 1, 2],
94
+ [0, 0, 3, 4]])
95
+
96
+ We can also construct tensor products of non-commutative symbols:
97
+
98
+ >>> from sympy import Symbol
99
+ >>> A = Symbol('A',commutative=False)
100
+ >>> B = Symbol('B',commutative=False)
101
+ >>> tp = TensorProduct(A, B)
102
+ >>> tp
103
+ AxB
104
+
105
+ We can take the dagger of a tensor product (note the order does NOT reverse
106
+ like the dagger of a normal product):
107
+
108
+ >>> from sympy.physics.quantum import Dagger
109
+ >>> Dagger(tp)
110
+ Dagger(A)xDagger(B)
111
+
112
+ Expand can be used to distribute a tensor product across addition:
113
+
114
+ >>> C = Symbol('C',commutative=False)
115
+ >>> tp = TensorProduct(A+B,C)
116
+ >>> tp
117
+ (A + B)xC
118
+ >>> tp.expand(tensorproduct=True)
119
+ AxC + BxC
120
+ """
121
+ is_commutative = False
122
+
123
+ def __new__(cls, *args):
124
+ if isinstance(args[0], (Matrix, ImmutableMatrix, numpy_ndarray,
125
+ scipy_sparse_matrix)):
126
+ return matrix_tensor_product(*args)
127
+ c_part, new_args = cls.flatten(sympify(args))
128
+ c_part = Mul(*c_part)
129
+ if len(new_args) == 0:
130
+ return c_part
131
+ elif len(new_args) == 1:
132
+ return c_part * new_args[0]
133
+ else:
134
+ tp = Expr.__new__(cls, *new_args)
135
+ return c_part * tp
136
+
137
+ @classmethod
138
+ def flatten(cls, args):
139
+ # TODO: disallow nested TensorProducts.
140
+ c_part = []
141
+ nc_parts = []
142
+ for arg in args:
143
+ cp, ncp = arg.args_cnc()
144
+ c_part.extend(list(cp))
145
+ nc_parts.append(Mul._from_args(ncp))
146
+ return c_part, nc_parts
147
+
148
+ def _eval_adjoint(self):
149
+ return TensorProduct(*[Dagger(i) for i in self.args])
150
+
151
+ def _eval_rewrite(self, rule, args, **hints):
152
+ return TensorProduct(*args).expand(tensorproduct=True)
153
+
154
+ def _sympystr(self, printer, *args):
155
+ length = len(self.args)
156
+ s = ''
157
+ for i in range(length):
158
+ if isinstance(self.args[i], (Add, Pow, Mul)):
159
+ s = s + '('
160
+ s = s + printer._print(self.args[i])
161
+ if isinstance(self.args[i], (Add, Pow, Mul)):
162
+ s = s + ')'
163
+ if i != length - 1:
164
+ s = s + 'x'
165
+ return s
166
+
167
+ def _pretty(self, printer, *args):
168
+
169
+ if (_combined_printing and
170
+ (all(isinstance(arg, Ket) for arg in self.args) or
171
+ all(isinstance(arg, Bra) for arg in self.args))):
172
+
173
+ length = len(self.args)
174
+ pform = printer._print('', *args)
175
+ for i in range(length):
176
+ next_pform = printer._print('', *args)
177
+ length_i = len(self.args[i].args)
178
+ for j in range(length_i):
179
+ part_pform = printer._print(self.args[i].args[j], *args)
180
+ next_pform = prettyForm(*next_pform.right(part_pform))
181
+ if j != length_i - 1:
182
+ next_pform = prettyForm(*next_pform.right(', '))
183
+
184
+ if len(self.args[i].args) > 1:
185
+ next_pform = prettyForm(
186
+ *next_pform.parens(left='{', right='}'))
187
+ pform = prettyForm(*pform.right(next_pform))
188
+ if i != length - 1:
189
+ pform = prettyForm(*pform.right(',' + ' '))
190
+
191
+ pform = prettyForm(*pform.left(self.args[0].lbracket))
192
+ pform = prettyForm(*pform.right(self.args[0].rbracket))
193
+ return pform
194
+
195
+ length = len(self.args)
196
+ pform = printer._print('', *args)
197
+ for i in range(length):
198
+ next_pform = printer._print(self.args[i], *args)
199
+ if isinstance(self.args[i], (Add, Mul)):
200
+ next_pform = prettyForm(
201
+ *next_pform.parens(left='(', right=')')
202
+ )
203
+ pform = prettyForm(*pform.right(next_pform))
204
+ if i != length - 1:
205
+ if printer._use_unicode:
206
+ pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
207
+ else:
208
+ pform = prettyForm(*pform.right('x' + ' '))
209
+ return pform
210
+
211
+ def _latex(self, printer, *args):
212
+
213
+ if (_combined_printing and
214
+ (all(isinstance(arg, Ket) for arg in self.args) or
215
+ all(isinstance(arg, Bra) for arg in self.args))):
216
+
217
+ def _label_wrap(label, nlabels):
218
+ return label if nlabels == 1 else r"\left\{%s\right\}" % label
219
+
220
+ s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args),
221
+ len(arg.args)) for arg in self.args])
222
+
223
+ return r"{%s%s%s}" % (self.args[0].lbracket_latex, s,
224
+ self.args[0].rbracket_latex)
225
+
226
+ length = len(self.args)
227
+ s = ''
228
+ for i in range(length):
229
+ if isinstance(self.args[i], (Add, Mul)):
230
+ s = s + '\\left('
231
+ # The extra {} brackets are needed to get matplotlib's latex
232
+ # rendered to render this properly.
233
+ s = s + '{' + printer._print(self.args[i], *args) + '}'
234
+ if isinstance(self.args[i], (Add, Mul)):
235
+ s = s + '\\right)'
236
+ if i != length - 1:
237
+ s = s + '\\otimes '
238
+ return s
239
+
240
+ def doit(self, **hints):
241
+ return TensorProduct(*[item.doit(**hints) for item in self.args])
242
+
243
+ def _eval_expand_tensorproduct(self, **hints):
244
+ """Distribute TensorProducts across addition."""
245
+ args = self.args
246
+ add_args = []
247
+ for i in range(len(args)):
248
+ if isinstance(args[i], Add):
249
+ for aa in args[i].args:
250
+ tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:])
251
+ c_part, nc_part = tp.args_cnc()
252
+ # Check for TensorProduct object: is the one object in nc_part, if any:
253
+ # (Note: any other object type to be expanded must be added here)
254
+ if len(nc_part) == 1 and isinstance(nc_part[0], TensorProduct):
255
+ nc_part = (nc_part[0]._eval_expand_tensorproduct(), )
256
+ add_args.append(Mul(*c_part)*Mul(*nc_part))
257
+ break
258
+
259
+ if add_args:
260
+ return Add(*add_args)
261
+ else:
262
+ return self
263
+
264
+ def _eval_trace(self, **kwargs):
265
+ indices = kwargs.get('indices', None)
266
+ exp = tensor_product_simp(self)
267
+
268
+ if indices is None or len(indices) == 0:
269
+ return Mul(*[Tr(arg).doit() for arg in exp.args])
270
+ else:
271
+ return Mul(*[Tr(value).doit() if idx in indices else value
272
+ for idx, value in enumerate(exp.args)])
273
+
274
+
275
+ def tensor_product_simp_Mul(e):
276
+ """Simplify a Mul with TensorProducts.
277
+
278
+ Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s
279
+ to a ``TensorProduct`` of ``Muls``. It currently only works for relatively
280
+ simple cases where the initial ``Mul`` only has scalars and raw
281
+ ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of
282
+ ``TensorProduct``s.
283
+
284
+ Parameters
285
+ ==========
286
+
287
+ e : Expr
288
+ A ``Mul`` of ``TensorProduct``s to be simplified.
289
+
290
+ Returns
291
+ =======
292
+
293
+ e : Expr
294
+ A ``TensorProduct`` of ``Mul``s.
295
+
296
+ Examples
297
+ ========
298
+
299
+ This is an example of the type of simplification that this function
300
+ performs::
301
+
302
+ >>> from sympy.physics.quantum.tensorproduct import \
303
+ tensor_product_simp_Mul, TensorProduct
304
+ >>> from sympy import Symbol
305
+ >>> A = Symbol('A',commutative=False)
306
+ >>> B = Symbol('B',commutative=False)
307
+ >>> C = Symbol('C',commutative=False)
308
+ >>> D = Symbol('D',commutative=False)
309
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
310
+ >>> e
311
+ AxB*CxD
312
+ >>> tensor_product_simp_Mul(e)
313
+ (A*C)x(B*D)
314
+
315
+ """
316
+ # TODO: This won't work with Muls that have other composites of
317
+ # TensorProducts, like an Add, Commutator, etc.
318
+ # TODO: This only works for the equivalent of single Qbit gates.
319
+ if not isinstance(e, Mul):
320
+ return e
321
+ c_part, nc_part = e.args_cnc()
322
+ n_nc = len(nc_part)
323
+ if n_nc == 0:
324
+ return e
325
+ elif n_nc == 1:
326
+ if isinstance(nc_part[0], Pow):
327
+ return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0])
328
+ return e
329
+ elif e.has(TensorProduct):
330
+ current = nc_part[0]
331
+ if not isinstance(current, TensorProduct):
332
+ if isinstance(current, Pow):
333
+ if isinstance(current.base, TensorProduct):
334
+ current = tensor_product_simp_Pow(current)
335
+ else:
336
+ raise TypeError('TensorProduct expected, got: %r' % current)
337
+ n_terms = len(current.args)
338
+ new_args = list(current.args)
339
+ for next in nc_part[1:]:
340
+ # TODO: check the hilbert spaces of next and current here.
341
+ if isinstance(next, TensorProduct):
342
+ if n_terms != len(next.args):
343
+ raise QuantumError(
344
+ 'TensorProducts of different lengths: %r and %r' %
345
+ (current, next)
346
+ )
347
+ for i in range(len(new_args)):
348
+ new_args[i] = new_args[i] * next.args[i]
349
+ else:
350
+ if isinstance(next, Pow):
351
+ if isinstance(next.base, TensorProduct):
352
+ new_tp = tensor_product_simp_Pow(next)
353
+ for i in range(len(new_args)):
354
+ new_args[i] = new_args[i] * new_tp.args[i]
355
+ else:
356
+ raise TypeError('TensorProduct expected, got: %r' % next)
357
+ else:
358
+ raise TypeError('TensorProduct expected, got: %r' % next)
359
+ current = next
360
+ return Mul(*c_part) * TensorProduct(*new_args)
361
+ elif e.has(Pow):
362
+ new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ]
363
+ return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args))
364
+ else:
365
+ return e
366
+
367
+ def tensor_product_simp_Pow(e):
368
+ """Evaluates ``Pow`` expressions whose base is ``TensorProduct``"""
369
+ if not isinstance(e, Pow):
370
+ return e
371
+
372
+ if isinstance(e.base, TensorProduct):
373
+ return TensorProduct(*[ b**e.exp for b in e.base.args])
374
+ else:
375
+ return e
376
+
377
+ def tensor_product_simp(e, **hints):
378
+ """Try to simplify and combine TensorProducts.
379
+
380
+ In general this will try to pull expressions inside of ``TensorProducts``.
381
+ It currently only works for relatively simple cases where the products have
382
+ only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators``
383
+ of ``TensorProducts``. It is best to see what it does by showing examples.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy.physics.quantum import tensor_product_simp
389
+ >>> from sympy.physics.quantum import TensorProduct
390
+ >>> from sympy import Symbol
391
+ >>> A = Symbol('A',commutative=False)
392
+ >>> B = Symbol('B',commutative=False)
393
+ >>> C = Symbol('C',commutative=False)
394
+ >>> D = Symbol('D',commutative=False)
395
+
396
+ First see what happens to products of tensor products:
397
+
398
+ >>> e = TensorProduct(A,B)*TensorProduct(C,D)
399
+ >>> e
400
+ AxB*CxD
401
+ >>> tensor_product_simp(e)
402
+ (A*C)x(B*D)
403
+
404
+ This is the core logic of this function, and it works inside, powers, sums,
405
+ commutators and anticommutators as well:
406
+
407
+ >>> tensor_product_simp(e**2)
408
+ (A*C)x(B*D)**2
409
+
410
+ """
411
+ if isinstance(e, Add):
412
+ return Add(*[tensor_product_simp(arg) for arg in e.args])
413
+ elif isinstance(e, Pow):
414
+ if isinstance(e.base, TensorProduct):
415
+ return tensor_product_simp_Pow(e)
416
+ else:
417
+ return tensor_product_simp(e.base) ** e.exp
418
+ elif isinstance(e, Mul):
419
+ return tensor_product_simp_Mul(e)
420
+ elif isinstance(e, Commutator):
421
+ return Commutator(*[tensor_product_simp(arg) for arg in e.args])
422
+ elif isinstance(e, AntiCommutator):
423
+ return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args])
424
+ else:
425
+ return e
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__init__.py ADDED
File without changes
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_anticommutator.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_cartesian.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_circuitplot.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_commutator.cpython-310.pyc ADDED
Binary file (3.44 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_operatorordering.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_pauli.cpython-310.pyc ADDED
Binary file (5.3 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_printing.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_qexpr.cpython-310.pyc ADDED
Binary file (1.88 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_represent.cpython-310.pyc ADDED
Binary file (6.21 kB). View file
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_trace.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
janus/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
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.numbers import Rational
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import symbols
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.physics.quantum.cg import Wigner3j, Wigner6j, Wigner9j, CG, cg_simp
7
+ from sympy.functions.special.tensor_functions import KroneckerDelta
8
+
9
+
10
+ def test_cg_simp_add():
11
+ j, m1, m1p, m2, m2p = symbols('j m1 m1p m2 m2p')
12
+ # Test Varshalovich 8.7.1 Eq 1
13
+ a = CG(S.Half, S.Half, 0, 0, S.Half, S.Half)
14
+ b = CG(S.Half, Rational(-1, 2), 0, 0, S.Half, Rational(-1, 2))
15
+ c = CG(1, 1, 0, 0, 1, 1)
16
+ d = CG(1, 0, 0, 0, 1, 0)
17
+ e = CG(1, -1, 0, 0, 1, -1)
18
+ assert cg_simp(a + b) == 2
19
+ assert cg_simp(c + d + e) == 3
20
+ assert cg_simp(a + b + c + d + e) == 5
21
+ assert cg_simp(a + b + c) == 2 + c
22
+ assert cg_simp(2*a + b) == 2 + a
23
+ assert cg_simp(2*c + d + e) == 3 + c
24
+ assert cg_simp(5*a + 5*b) == 10
25
+ assert cg_simp(5*c + 5*d + 5*e) == 15
26
+ assert cg_simp(-a - b) == -2
27
+ assert cg_simp(-c - d - e) == -3
28
+ assert cg_simp(-6*a - 6*b) == -12
29
+ assert cg_simp(-4*c - 4*d - 4*e) == -12
30
+ a = CG(S.Half, S.Half, j, 0, S.Half, S.Half)
31
+ b = CG(S.Half, Rational(-1, 2), j, 0, S.Half, Rational(-1, 2))
32
+ c = CG(1, 1, j, 0, 1, 1)
33
+ d = CG(1, 0, j, 0, 1, 0)
34
+ e = CG(1, -1, j, 0, 1, -1)
35
+ assert cg_simp(a + b) == 2*KroneckerDelta(j, 0)
36
+ assert cg_simp(c + d + e) == 3*KroneckerDelta(j, 0)
37
+ assert cg_simp(a + b + c + d + e) == 5*KroneckerDelta(j, 0)
38
+ assert cg_simp(a + b + c) == 2*KroneckerDelta(j, 0) + c
39
+ assert cg_simp(2*a + b) == 2*KroneckerDelta(j, 0) + a
40
+ assert cg_simp(2*c + d + e) == 3*KroneckerDelta(j, 0) + c
41
+ assert cg_simp(5*a + 5*b) == 10*KroneckerDelta(j, 0)
42
+ assert cg_simp(5*c + 5*d + 5*e) == 15*KroneckerDelta(j, 0)
43
+ assert cg_simp(-a - b) == -2*KroneckerDelta(j, 0)
44
+ assert cg_simp(-c - d - e) == -3*KroneckerDelta(j, 0)
45
+ assert cg_simp(-6*a - 6*b) == -12*KroneckerDelta(j, 0)
46
+ assert cg_simp(-4*c - 4*d - 4*e) == -12*KroneckerDelta(j, 0)
47
+ # Test Varshalovich 8.7.1 Eq 2
48
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)
49
+ b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
50
+ c = CG(1, 1, 1, -1, 0, 0)
51
+ d = CG(1, 0, 1, 0, 0, 0)
52
+ e = CG(1, -1, 1, 1, 0, 0)
53
+ assert cg_simp(a - b) == sqrt(2)
54
+ assert cg_simp(c - d + e) == sqrt(3)
55
+ assert cg_simp(a - b + c - d + e) == sqrt(2) + sqrt(3)
56
+ assert cg_simp(a - b + c) == sqrt(2) + c
57
+ assert cg_simp(2*a - b) == sqrt(2) + a
58
+ assert cg_simp(2*c - d + e) == sqrt(3) + c
59
+ assert cg_simp(5*a - 5*b) == 5*sqrt(2)
60
+ assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)
61
+ assert cg_simp(-a + b) == -sqrt(2)
62
+ assert cg_simp(-c + d - e) == -sqrt(3)
63
+ assert cg_simp(-6*a + 6*b) == -6*sqrt(2)
64
+ assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)
65
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), j, 0)
66
+ b = CG(S.Half, Rational(-1, 2), S.Half, S.Half, j, 0)
67
+ c = CG(1, 1, 1, -1, j, 0)
68
+ d = CG(1, 0, 1, 0, j, 0)
69
+ e = CG(1, -1, 1, 1, j, 0)
70
+ assert cg_simp(a - b) == sqrt(2)*KroneckerDelta(j, 0)
71
+ assert cg_simp(c - d + e) == sqrt(3)*KroneckerDelta(j, 0)
72
+ assert cg_simp(a - b + c - d + e) == sqrt(
73
+ 2)*KroneckerDelta(j, 0) + sqrt(3)*KroneckerDelta(j, 0)
74
+ assert cg_simp(a - b + c) == sqrt(2)*KroneckerDelta(j, 0) + c
75
+ assert cg_simp(2*a - b) == sqrt(2)*KroneckerDelta(j, 0) + a
76
+ assert cg_simp(2*c - d + e) == sqrt(3)*KroneckerDelta(j, 0) + c
77
+ assert cg_simp(5*a - 5*b) == 5*sqrt(2)*KroneckerDelta(j, 0)
78
+ assert cg_simp(5*c - 5*d + 5*e) == 5*sqrt(3)*KroneckerDelta(j, 0)
79
+ assert cg_simp(-a + b) == -sqrt(2)*KroneckerDelta(j, 0)
80
+ assert cg_simp(-c + d - e) == -sqrt(3)*KroneckerDelta(j, 0)
81
+ assert cg_simp(-6*a + 6*b) == -6*sqrt(2)*KroneckerDelta(j, 0)
82
+ assert cg_simp(-4*c + 4*d - 4*e) == -4*sqrt(3)*KroneckerDelta(j, 0)
83
+ # Test Varshalovich 8.7.2 Eq 9
84
+ # alpha=alphap,beta=betap case
85
+ # numerical
86
+ a = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0)**2
87
+ b = CG(S.Half, S.Half, S.Half, Rational(-1, 2), 0, 0)**2
88
+ c = CG(1, 0, 1, 1, 1, 1)**2
89
+ d = CG(1, 0, 1, 1, 2, 1)**2
90
+ assert cg_simp(a + b) == 1
91
+ assert cg_simp(c + d) == 1
92
+ assert cg_simp(a + b + c + d) == 2
93
+ assert cg_simp(4*a + 4*b) == 4
94
+ assert cg_simp(4*c + 4*d) == 4
95
+ assert cg_simp(5*a + 3*b) == 3 + 2*a
96
+ assert cg_simp(5*c + 3*d) == 3 + 2*c
97
+ assert cg_simp(-a - b) == -1
98
+ assert cg_simp(-c - d) == -1
99
+ # symbolic
100
+ a = CG(S.Half, m1, S.Half, m2, 1, 1)**2
101
+ b = CG(S.Half, m1, S.Half, m2, 1, 0)**2
102
+ c = CG(S.Half, m1, S.Half, m2, 1, -1)**2
103
+ d = CG(S.Half, m1, S.Half, m2, 0, 0)**2
104
+ assert cg_simp(a + b + c + d) == 1
105
+ assert cg_simp(4*a + 4*b + 4*c + 4*d) == 4
106
+ assert cg_simp(3*a + 5*b + 3*c + 4*d) == 3 + 2*b + d
107
+ assert cg_simp(-a - b - c - d) == -1
108
+ a = CG(1, m1, 1, m2, 2, 2)**2
109
+ b = CG(1, m1, 1, m2, 2, 1)**2
110
+ c = CG(1, m1, 1, m2, 2, 0)**2
111
+ d = CG(1, m1, 1, m2, 2, -1)**2
112
+ e = CG(1, m1, 1, m2, 2, -2)**2
113
+ f = CG(1, m1, 1, m2, 1, 1)**2
114
+ g = CG(1, m1, 1, m2, 1, 0)**2
115
+ h = CG(1, m1, 1, m2, 1, -1)**2
116
+ i = CG(1, m1, 1, m2, 0, 0)**2
117
+ assert cg_simp(a + b + c + d + e + f + g + h + i) == 1
118
+ assert cg_simp(4*(a + b + c + d + e + f + g + h + i)) == 4
119
+ assert cg_simp(a + b + 2*c + d + 4*e + f + g + h + i) == 1 + c + 3*e
120
+ assert cg_simp(-a - b - c - d - e - f - g - h - i) == -1
121
+ # alpha!=alphap or beta!=betap case
122
+ # numerical
123
+ a = CG(S.Half, S(
124
+ 1)/2, S.Half, Rational(-1, 2), 1, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 1, 0)
125
+ b = CG(S.Half, S(
126
+ 1)/2, S.Half, Rational(-1, 2), 0, 0)*CG(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0)
127
+ c = CG(1, 1, 1, 0, 2, 1)*CG(1, 0, 1, 1, 2, 1)
128
+ d = CG(1, 1, 1, 0, 1, 1)*CG(1, 0, 1, 1, 1, 1)
129
+ assert cg_simp(a + b) == 0
130
+ assert cg_simp(c + d) == 0
131
+ # symbolic
132
+ a = CG(S.Half, m1, S.Half, m2, 1, 1)*CG(S.Half, m1p, S.Half, m2p, 1, 1)
133
+ b = CG(S.Half, m1, S.Half, m2, 1, 0)*CG(S.Half, m1p, S.Half, m2p, 1, 0)
134
+ c = CG(S.Half, m1, S.Half, m2, 1, -1)*CG(S.Half, m1p, S.Half, m2p, 1, -1)
135
+ d = CG(S.Half, m1, S.Half, m2, 0, 0)*CG(S.Half, m1p, S.Half, m2p, 0, 0)
136
+ assert cg_simp(a + b + c + d) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
137
+ a = CG(1, m1, 1, m2, 2, 2)*CG(1, m1p, 1, m2p, 2, 2)
138
+ b = CG(1, m1, 1, m2, 2, 1)*CG(1, m1p, 1, m2p, 2, 1)
139
+ c = CG(1, m1, 1, m2, 2, 0)*CG(1, m1p, 1, m2p, 2, 0)
140
+ d = CG(1, m1, 1, m2, 2, -1)*CG(1, m1p, 1, m2p, 2, -1)
141
+ e = CG(1, m1, 1, m2, 2, -2)*CG(1, m1p, 1, m2p, 2, -2)
142
+ f = CG(1, m1, 1, m2, 1, 1)*CG(1, m1p, 1, m2p, 1, 1)
143
+ g = CG(1, m1, 1, m2, 1, 0)*CG(1, m1p, 1, m2p, 1, 0)
144
+ h = CG(1, m1, 1, m2, 1, -1)*CG(1, m1p, 1, m2p, 1, -1)
145
+ i = CG(1, m1, 1, m2, 0, 0)*CG(1, m1p, 1, m2p, 0, 0)
146
+ assert cg_simp(
147
+ a + b + c + d + e + f + g + h + i) == KroneckerDelta(m1, m1p)*KroneckerDelta(m2, m2p)
148
+
149
+
150
+ def test_cg_simp_sum():
151
+ x, a, b, c, cp, alpha, beta, gamma, gammap = symbols(
152
+ 'x a b c cp alpha beta gamma gammap')
153
+ # Varshalovich 8.7.1 Eq 1
154
+ assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)
155
+ )) == x*(2*a + 1)*KroneckerDelta(b, 0)
156
+ assert cg_simp(x * Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)) + CG(1, 0, 1, 0, 1, 0)) == x*(2*a + 1)*KroneckerDelta(b, 0) + CG(1, 0, 1, 0, 1, 0)
157
+ assert cg_simp(2 * Sum(CG(1, alpha, 0, 0, 1, alpha), (alpha, -1, 1))) == 6
158
+ # Varshalovich 8.7.1 Eq 2
159
+ assert cg_simp(x*Sum((-1)**(a - alpha) * CG(a, alpha, a, -alpha, c,
160
+ 0), (alpha, -a, a))) == x*sqrt(2*a + 1)*KroneckerDelta(c, 0)
161
+ assert cg_simp(3*Sum((-1)**(2 - alpha) * CG(
162
+ 2, alpha, 2, -alpha, 0, 0), (alpha, -2, 2))) == 3*sqrt(5)
163
+ # Varshalovich 8.7.2 Eq 4
164
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)
165
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, c, gammap), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(gamma, gammap)
166
+ assert cg_simp(Sum(CG(a, alpha, b, beta, c, gamma)*CG(a, alpha, b, beta, cp, gamma), (alpha, -a, a), (beta, -b, b))) == KroneckerDelta(c, cp)
167
+ assert cg_simp(Sum(CG(
168
+ a, alpha, b, beta, c, gamma)**2, (alpha, -a, a), (beta, -b, b))) == 1
169
+ assert cg_simp(Sum(CG(2, alpha, 1, beta, 2, gamma)*CG(2, alpha, 1, beta, 2, gammap), (alpha, -2, 2), (beta, -1, 1))) == KroneckerDelta(gamma, gammap)
170
+
171
+
172
+ def test_doit():
173
+ assert Wigner3j(S.Half, Rational(-1, 2), S.Half, S.Half, 0, 0).doit() == -sqrt(2)/2
174
+ assert Wigner3j(1/2,1/2,1/2,1/2,1/2,1/2).doit() == 0
175
+ assert Wigner3j(9/2,9/2,9/2,9/2,9/2,9/2).doit() == 0
176
+ assert Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105
177
+ assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105
178
+ assert Wigner9j(
179
+ 2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0).doit() == sqrt(2)/12
180
+ assert CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0).doit() == sqrt(2)/2
181
+ # J minus M is not integer
182
+ assert Wigner3j(1, -1, S.Half, S.Half, 1, S.Half).doit() == 0
183
+ assert CG(4, -1, S.Half, S.Half, 4, Rational(-1, 2)).doit() == 0
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_dagger.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import Expr
2
+ from sympy.core.mul import Mul
3
+ from sympy.core.numbers import (I, Integer)
4
+ from sympy.core.symbol import symbols
5
+ from sympy.functions.elementary.complexes import conjugate
6
+ from sympy.matrices.dense import Matrix
7
+
8
+ from sympy.physics.quantum.dagger import adjoint, Dagger
9
+ from sympy.external import import_module
10
+ from sympy.testing.pytest import skip
11
+ from sympy.physics.quantum.operator import Operator, IdentityOperator
12
+
13
+
14
+ def test_scalars():
15
+ x = symbols('x', complex=True)
16
+ assert Dagger(x) == conjugate(x)
17
+ assert Dagger(I*x) == -I*conjugate(x)
18
+
19
+ i = symbols('i', real=True)
20
+ assert Dagger(i) == i
21
+
22
+ p = symbols('p')
23
+ assert isinstance(Dagger(p), adjoint)
24
+
25
+ i = Integer(3)
26
+ assert Dagger(i) == i
27
+
28
+ A = symbols('A', commutative=False)
29
+ assert Dagger(A).is_commutative is False
30
+
31
+
32
+ def test_matrix():
33
+ x = symbols('x')
34
+ m = Matrix([[I, x*I], [2, 4]])
35
+ assert Dagger(m) == m.H
36
+
37
+
38
+ def test_dagger_mul():
39
+ O = Operator('O')
40
+ I = IdentityOperator()
41
+ assert Dagger(O)*O == Dagger(O)*O
42
+ assert Dagger(O)*O*I == Mul(Dagger(O), O)*I
43
+ assert Dagger(O)*Dagger(O) == Dagger(O)**2
44
+ assert Dagger(O)*Dagger(I) == Dagger(O)
45
+
46
+
47
+ class Foo(Expr):
48
+
49
+ def _eval_adjoint(self):
50
+ return I
51
+
52
+
53
+ def test_eval_adjoint():
54
+ f = Foo()
55
+ d = Dagger(f)
56
+ assert d == I
57
+
58
+ np = import_module('numpy')
59
+
60
+
61
+ def test_numpy_dagger():
62
+ if not np:
63
+ skip("numpy not installed.")
64
+
65
+ a = np.array([[1.0, 2.0j], [-1.0j, 2.0]])
66
+ adag = a.copy().transpose().conjugate()
67
+ assert (Dagger(a) == adag).all()
68
+
69
+
70
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
71
+
72
+
73
+ def test_scipy_sparse_dagger():
74
+ if not np:
75
+ skip("numpy not installed.")
76
+ if not scipy:
77
+ skip("scipy not installed.")
78
+ else:
79
+ sparse = scipy.sparse
80
+
81
+ a = sparse.csr_matrix([[1.0 + 0.0j, 2.0j], [-1.0j, 2.0 + 0.0j]])
82
+ adag = a.copy().transpose().conjugate()
83
+ assert np.linalg.norm((Dagger(a) - adag).todense()) == 0.0
84
+
85
+
86
+ def test_unknown():
87
+ """Check treatment of unknown objects.
88
+ Objects without adjoint or conjugate/transpose methods
89
+ are sympified and wrapped in dagger.
90
+ """
91
+ x = symbols("x")
92
+ result = Dagger(x)
93
+ assert result.args == (x,) and isinstance(result, adjoint)
94
+
95
+
96
+ def test_unevaluated():
97
+ """Check that evaluate=False returns unevaluated Dagger.
98
+ """
99
+ x = symbols("x", real=True)
100
+ assert Dagger(x) == x
101
+ result = Dagger(x, evaluate=False)
102
+ assert result.args == (x,) and isinstance(result, adjoint)
janus/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
janus/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)
janus/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)
janus/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
janus/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)
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_operatorset.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+
3
+ from sympy.physics.quantum.operatorset import (
4
+ operators_to_state, state_to_operators
5
+ )
6
+
7
+ from sympy.physics.quantum.cartesian import (
8
+ XOp, XKet, PxOp, PxKet, XBra, PxBra
9
+ )
10
+
11
+ from sympy.physics.quantum.state import Ket, Bra
12
+ from sympy.physics.quantum.operator import Operator
13
+ from sympy.physics.quantum.spin import (
14
+ JxKet, JyKet, JzKet, JxBra, JyBra, JzBra,
15
+ JxOp, JyOp, JzOp, J2Op
16
+ )
17
+
18
+ from sympy.testing.pytest import raises
19
+
20
+
21
+ def test_spin():
22
+ assert operators_to_state({J2Op, JxOp}) == JxKet
23
+ assert operators_to_state({J2Op, JyOp}) == JyKet
24
+ assert operators_to_state({J2Op, JzOp}) == JzKet
25
+ assert operators_to_state({J2Op(), JxOp()}) == JxKet
26
+ assert operators_to_state({J2Op(), JyOp()}) == JyKet
27
+ assert operators_to_state({J2Op(), JzOp()}) == JzKet
28
+
29
+ assert state_to_operators(JxKet) == {J2Op, JxOp}
30
+ assert state_to_operators(JyKet) == {J2Op, JyOp}
31
+ assert state_to_operators(JzKet) == {J2Op, JzOp}
32
+ assert state_to_operators(JxBra) == {J2Op, JxOp}
33
+ assert state_to_operators(JyBra) == {J2Op, JyOp}
34
+ assert state_to_operators(JzBra) == {J2Op, JzOp}
35
+
36
+ assert state_to_operators(JxKet(S.Half, S.Half)) == {J2Op(), JxOp()}
37
+ assert state_to_operators(JyKet(S.Half, S.Half)) == {J2Op(), JyOp()}
38
+ assert state_to_operators(JzKet(S.Half, S.Half)) == {J2Op(), JzOp()}
39
+ assert state_to_operators(JxBra(S.Half, S.Half)) == {J2Op(), JxOp()}
40
+ assert state_to_operators(JyBra(S.Half, S.Half)) == {J2Op(), JyOp()}
41
+ assert state_to_operators(JzBra(S.Half, S.Half)) == {J2Op(), JzOp()}
42
+
43
+
44
+ def test_op_to_state():
45
+ assert operators_to_state(XOp) == XKet()
46
+ assert operators_to_state(PxOp) == PxKet()
47
+ assert operators_to_state(Operator) == Ket()
48
+
49
+ assert state_to_operators(operators_to_state(XOp("Q"))) == XOp("Q")
50
+ assert state_to_operators(operators_to_state(XOp())) == XOp()
51
+
52
+ raises(NotImplementedError, lambda: operators_to_state(XKet))
53
+
54
+
55
+ def test_state_to_op():
56
+ assert state_to_operators(XKet) == XOp()
57
+ assert state_to_operators(PxKet) == PxOp()
58
+ assert state_to_operators(XBra) == XOp()
59
+ assert state_to_operators(PxBra) == PxOp()
60
+ assert state_to_operators(Ket) == Operator()
61
+ assert state_to_operators(Bra) == Operator()
62
+
63
+ assert operators_to_state(state_to_operators(XKet("test"))) == XKet("test")
64
+ assert operators_to_state(state_to_operators(XBra("test"))) == XKet("test")
65
+ assert operators_to_state(state_to_operators(XKet())) == XKet()
66
+ assert operators_to_state(state_to_operators(XBra())) == XKet()
67
+
68
+ raises(NotImplementedError, lambda: state_to_operators(XOp))
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_pauli.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.mul import Mul
2
+ from sympy.core.numbers import I
3
+ from sympy.matrices.dense import Matrix
4
+ from sympy.printing.latex import latex
5
+ from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply,
6
+ Operator, represent)
7
+ from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ,
8
+ SigmaMinus, SigmaPlus,
9
+ qsimplify_pauli)
10
+ from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra
11
+ from sympy.testing.pytest import raises
12
+
13
+
14
+ sx, sy, sz = SigmaX(), SigmaY(), SigmaZ()
15
+ sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1)
16
+ sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2)
17
+
18
+ sm, sp = SigmaMinus(), SigmaPlus()
19
+ sm1, sp1 = SigmaMinus(1), SigmaPlus(1)
20
+ A, B = Operator("A"), Operator("B")
21
+
22
+
23
+ def test_pauli_operators_types():
24
+
25
+ assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX)
26
+ assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY)
27
+ assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ)
28
+ assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus)
29
+ assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus)
30
+
31
+
32
+ def test_pauli_operators_commutator():
33
+
34
+ assert Commutator(sx, sy).doit() == 2 * I * sz
35
+ assert Commutator(sy, sz).doit() == 2 * I * sx
36
+ assert Commutator(sz, sx).doit() == 2 * I * sy
37
+
38
+
39
+ def test_pauli_operators_commutator_with_labels():
40
+
41
+ assert Commutator(sx1, sy1).doit() == 2 * I * sz1
42
+ assert Commutator(sy1, sz1).doit() == 2 * I * sx1
43
+ assert Commutator(sz1, sx1).doit() == 2 * I * sy1
44
+
45
+ assert Commutator(sx2, sy2).doit() == 2 * I * sz2
46
+ assert Commutator(sy2, sz2).doit() == 2 * I * sx2
47
+ assert Commutator(sz2, sx2).doit() == 2 * I * sy2
48
+
49
+ assert Commutator(sx1, sy2).doit() == 0
50
+ assert Commutator(sy1, sz2).doit() == 0
51
+ assert Commutator(sz1, sx2).doit() == 0
52
+
53
+
54
+ def test_pauli_operators_anticommutator():
55
+
56
+ assert AntiCommutator(sy, sz).doit() == 0
57
+ assert AntiCommutator(sz, sx).doit() == 0
58
+ assert AntiCommutator(sx, sm).doit() == 1
59
+ assert AntiCommutator(sx, sp).doit() == 1
60
+
61
+
62
+ def test_pauli_operators_adjoint():
63
+
64
+ assert Dagger(sx) == sx
65
+ assert Dagger(sy) == sy
66
+ assert Dagger(sz) == sz
67
+
68
+
69
+ def test_pauli_operators_adjoint_with_labels():
70
+
71
+ assert Dagger(sx1) == sx1
72
+ assert Dagger(sy1) == sy1
73
+ assert Dagger(sz1) == sz1
74
+
75
+ assert Dagger(sx1) != sx2
76
+ assert Dagger(sy1) != sy2
77
+ assert Dagger(sz1) != sz2
78
+
79
+
80
+ def test_pauli_operators_multiplication():
81
+
82
+ assert qsimplify_pauli(sx * sx) == 1
83
+ assert qsimplify_pauli(sy * sy) == 1
84
+ assert qsimplify_pauli(sz * sz) == 1
85
+
86
+ assert qsimplify_pauli(sx * sy) == I * sz
87
+ assert qsimplify_pauli(sy * sz) == I * sx
88
+ assert qsimplify_pauli(sz * sx) == I * sy
89
+
90
+ assert qsimplify_pauli(sy * sx) == - I * sz
91
+ assert qsimplify_pauli(sz * sy) == - I * sx
92
+ assert qsimplify_pauli(sx * sz) == - I * sy
93
+
94
+
95
+ def test_pauli_operators_multiplication_with_labels():
96
+
97
+ assert qsimplify_pauli(sx1 * sx1) == 1
98
+ assert qsimplify_pauli(sy1 * sy1) == 1
99
+ assert qsimplify_pauli(sz1 * sz1) == 1
100
+
101
+ assert isinstance(sx1 * sx2, Mul)
102
+ assert isinstance(sy1 * sy2, Mul)
103
+ assert isinstance(sz1 * sz2, Mul)
104
+
105
+ assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2
106
+ assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2
107
+
108
+
109
+ def test_pauli_states():
110
+ sx, sz = SigmaX(), SigmaZ()
111
+
112
+ up = SigmaZKet(0)
113
+ down = SigmaZKet(1)
114
+
115
+ assert qapply(sx * up) == down
116
+ assert qapply(sx * down) == up
117
+ assert qapply(sz * up) == up
118
+ assert qapply(sz * down) == - down
119
+
120
+ up = SigmaZBra(0)
121
+ down = SigmaZBra(1)
122
+
123
+ assert qapply(up * sx, dagger=True) == down
124
+ assert qapply(down * sx, dagger=True) == up
125
+ assert qapply(up * sz, dagger=True) == up
126
+ assert qapply(down * sz, dagger=True) == - down
127
+
128
+ assert Dagger(SigmaZKet(0)) == SigmaZBra(0)
129
+ assert Dagger(SigmaZBra(1)) == SigmaZKet(1)
130
+ raises(ValueError, lambda: SigmaZBra(2))
131
+ raises(ValueError, lambda: SigmaZKet(2))
132
+
133
+
134
+ def test_use_name():
135
+ assert sm.use_name is False
136
+ assert sm1.use_name is True
137
+ assert sx.use_name is False
138
+ assert sx1.use_name is True
139
+
140
+
141
+ def test_printing():
142
+ assert latex(sx) == r'{\sigma_x}'
143
+ assert latex(sx1) == r'{\sigma_x^{(1)}}'
144
+ assert latex(sy) == r'{\sigma_y}'
145
+ assert latex(sy1) == r'{\sigma_y^{(1)}}'
146
+ assert latex(sz) == r'{\sigma_z}'
147
+ assert latex(sz1) == r'{\sigma_z^{(1)}}'
148
+ assert latex(sm) == r'{\sigma_-}'
149
+ assert latex(sm1) == r'{\sigma_-^{(1)}}'
150
+ assert latex(sp) == r'{\sigma_+}'
151
+ assert latex(sp1) == r'{\sigma_+^{(1)}}'
152
+
153
+
154
+ def test_represent():
155
+ assert represent(sx) == Matrix([[0, 1], [1, 0]])
156
+ assert represent(sy) == Matrix([[0, -I], [I, 0]])
157
+ assert represent(sz) == Matrix([[1, 0], [0, -1]])
158
+ assert represent(sm) == Matrix([[0, 0], [1, 0]])
159
+ assert represent(sp) == Matrix([[0, 1], [0, 0]])
janus/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
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_printing.py ADDED
@@ -0,0 +1,900 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- encoding: utf-8 -*-
2
+ """
3
+ TODO:
4
+ * Address Issue 2251, printing of spin states
5
+ """
6
+ from __future__ import annotations
7
+ from typing import Any
8
+
9
+ from sympy.physics.quantum.anticommutator import AntiCommutator
10
+ from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j
11
+ from sympy.physics.quantum.commutator import Commutator
12
+ from sympy.physics.quantum.constants import hbar
13
+ from sympy.physics.quantum.dagger import Dagger
14
+ from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate
15
+ from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2
16
+ from sympy.physics.quantum.innerproduct import InnerProduct
17
+ from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator
18
+ from sympy.physics.quantum.qexpr import QExpr
19
+ from sympy.physics.quantum.qubit import Qubit, IntQubit
20
+ from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD
21
+ from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet
22
+ from sympy.physics.quantum.tensorproduct import TensorProduct
23
+ from sympy.physics.quantum.sho1d import RaisingOp
24
+
25
+ from sympy.core.function import (Derivative, Function)
26
+ from sympy.core.numbers import oo
27
+ from sympy.core.power import Pow
28
+ from sympy.core.singleton import S
29
+ from sympy.core.symbol import (Symbol, symbols)
30
+ from sympy.matrices.dense import Matrix
31
+ from sympy.sets.sets import Interval
32
+ from sympy.testing.pytest import XFAIL
33
+
34
+ # Imports used in srepr strings
35
+ from sympy.physics.quantum.spin import JzOp
36
+
37
+ from sympy.printing import srepr
38
+ from sympy.printing.pretty import pretty as xpretty
39
+ from sympy.printing.latex import latex
40
+
41
+ MutableDenseMatrix = Matrix
42
+
43
+
44
+ ENV: dict[str, Any] = {}
45
+ exec('from sympy import *', ENV)
46
+ exec('from sympy.physics.quantum import *', ENV)
47
+ exec('from sympy.physics.quantum.cg import *', ENV)
48
+ exec('from sympy.physics.quantum.spin import *', ENV)
49
+ exec('from sympy.physics.quantum.hilbert import *', ENV)
50
+ exec('from sympy.physics.quantum.qubit import *', ENV)
51
+ exec('from sympy.physics.quantum.qexpr import *', ENV)
52
+ exec('from sympy.physics.quantum.gate import *', ENV)
53
+ exec('from sympy.physics.quantum.constants import *', ENV)
54
+
55
+
56
+ def sT(expr, string):
57
+ """
58
+ sT := sreprTest
59
+ from sympy/printing/tests/test_repr.py
60
+ """
61
+ assert srepr(expr) == string
62
+ assert eval(string, ENV) == expr
63
+
64
+
65
+ def pretty(expr):
66
+ """ASCII pretty-printing"""
67
+ return xpretty(expr, use_unicode=False, wrap_line=False)
68
+
69
+
70
+ def upretty(expr):
71
+ """Unicode pretty-printing"""
72
+ return xpretty(expr, use_unicode=True, wrap_line=False)
73
+
74
+
75
+ def test_anticommutator():
76
+ A = Operator('A')
77
+ B = Operator('B')
78
+ ac = AntiCommutator(A, B)
79
+ ac_tall = AntiCommutator(A**2, B)
80
+ assert str(ac) == '{A,B}'
81
+ assert pretty(ac) == '{A,B}'
82
+ assert upretty(ac) == '{A,B}'
83
+ assert latex(ac) == r'\left\{A,B\right\}'
84
+ sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
85
+ assert str(ac_tall) == '{A**2,B}'
86
+ ascii_str = \
87
+ """\
88
+ / 2 \\\n\
89
+ <A ,B>\n\
90
+ \\ /\
91
+ """
92
+ ucode_str = \
93
+ """\
94
+ ⎧ 2 ⎫\n\
95
+ ⎨A ,B⎬\n\
96
+ ⎩ ⎭\
97
+ """
98
+ assert pretty(ac_tall) == ascii_str
99
+ assert upretty(ac_tall) == ucode_str
100
+ assert latex(ac_tall) == r'\left\{A^{2},B\right\}'
101
+ sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
102
+
103
+
104
+ def test_cg():
105
+ cg = CG(1, 2, 3, 4, 5, 6)
106
+ wigner3j = Wigner3j(1, 2, 3, 4, 5, 6)
107
+ wigner6j = Wigner6j(1, 2, 3, 4, 5, 6)
108
+ wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)
109
+ assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)'
110
+ ascii_str = \
111
+ """\
112
+ 5,6 \n\
113
+ C \n\
114
+ 1,2,3,4\
115
+ """
116
+ ucode_str = \
117
+ """\
118
+ 5,6 \n\
119
+ C \n\
120
+ 1,2,3,4\
121
+ """
122
+ assert pretty(cg) == ascii_str
123
+ assert upretty(cg) == ucode_str
124
+ assert latex(cg) == 'C^{5,6}_{1,2,3,4}'
125
+ assert latex(cg ** 2) == R'\left(C^{5,6}_{1,2,3,4}\right)^{2}'
126
+ sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
127
+ assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)'
128
+ ascii_str = \
129
+ """\
130
+ /1 3 5\\\n\
131
+ | |\n\
132
+ \\2 4 6/\
133
+ """
134
+ ucode_str = \
135
+ """\
136
+ ⎛1 3 5⎞\n\
137
+ ⎜ ⎟\n\
138
+ ⎝2 4 6⎠\
139
+ """
140
+ assert pretty(wigner3j) == ascii_str
141
+ assert upretty(wigner3j) == ucode_str
142
+ assert latex(wigner3j) == \
143
+ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)'
144
+ sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
145
+ assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)'
146
+ ascii_str = \
147
+ """\
148
+ /1 2 3\\\n\
149
+ < >\n\
150
+ \\4 5 6/\
151
+ """
152
+ ucode_str = \
153
+ """\
154
+ ⎧1 2 3⎫\n\
155
+ ⎨ ⎬\n\
156
+ ⎩4 5 6⎭\
157
+ """
158
+ assert pretty(wigner6j) == ascii_str
159
+ assert upretty(wigner6j) == ucode_str
160
+ assert latex(wigner6j) == \
161
+ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}'
162
+ sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
163
+ assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)'
164
+ ascii_str = \
165
+ """\
166
+ /1 2 3\\\n\
167
+ | |\n\
168
+ <4 5 6>\n\
169
+ | |\n\
170
+ \\7 8 9/\
171
+ """
172
+ ucode_str = \
173
+ """\
174
+ ⎧1 2 3⎫\n\
175
+ ⎪ ⎪\n\
176
+ ⎨4 5 6⎬\n\
177
+ ⎪ ⎪\n\
178
+ ⎩7 8 9⎭\
179
+ """
180
+ assert pretty(wigner9j) == ascii_str
181
+ assert upretty(wigner9j) == ucode_str
182
+ assert latex(wigner9j) == \
183
+ r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}'
184
+ sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))")
185
+
186
+
187
+ def test_commutator():
188
+ A = Operator('A')
189
+ B = Operator('B')
190
+ c = Commutator(A, B)
191
+ c_tall = Commutator(A**2, B)
192
+ assert str(c) == '[A,B]'
193
+ assert pretty(c) == '[A,B]'
194
+ assert upretty(c) == '[A,B]'
195
+ assert latex(c) == r'\left[A,B\right]'
196
+ sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
197
+ assert str(c_tall) == '[A**2,B]'
198
+ ascii_str = \
199
+ """\
200
+ [ 2 ]\n\
201
+ [A ,B]\
202
+ """
203
+ ucode_str = \
204
+ """\
205
+ ⎡ 2 ⎤\n\
206
+ ⎣A ,B⎦\
207
+ """
208
+ assert pretty(c_tall) == ascii_str
209
+ assert upretty(c_tall) == ucode_str
210
+ assert latex(c_tall) == r'\left[A^{2},B\right]'
211
+ sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
212
+
213
+
214
+ def test_constants():
215
+ assert str(hbar) == 'hbar'
216
+ assert pretty(hbar) == 'hbar'
217
+ assert upretty(hbar) == 'ℏ'
218
+ assert latex(hbar) == r'\hbar'
219
+ sT(hbar, "HBar()")
220
+
221
+
222
+ def test_dagger():
223
+ x = symbols('x')
224
+ expr = Dagger(x)
225
+ assert str(expr) == 'Dagger(x)'
226
+ ascii_str = \
227
+ """\
228
+ +\n\
229
+ x \
230
+ """
231
+ ucode_str = \
232
+ """\
233
+ †\n\
234
+ x \
235
+ """
236
+ assert pretty(expr) == ascii_str
237
+ assert upretty(expr) == ucode_str
238
+ assert latex(expr) == r'x^{\dagger}'
239
+ sT(expr, "Dagger(Symbol('x'))")
240
+
241
+
242
+ @XFAIL
243
+ def test_gate_failing():
244
+ a, b, c, d = symbols('a,b,c,d')
245
+ uMat = Matrix([[a, b], [c, d]])
246
+ g = UGate((0,), uMat)
247
+ assert str(g) == 'U(0)'
248
+
249
+
250
+ def test_gate():
251
+ a, b, c, d = symbols('a,b,c,d')
252
+ uMat = Matrix([[a, b], [c, d]])
253
+ q = Qubit(1, 0, 1, 0, 1)
254
+ g1 = IdentityGate(2)
255
+ g2 = CGate((3, 0), XGate(1))
256
+ g3 = CNotGate(1, 0)
257
+ g4 = UGate((0,), uMat)
258
+ assert str(g1) == '1(2)'
259
+ assert pretty(g1) == '1 \n 2'
260
+ assert upretty(g1) == '1 \n 2'
261
+ assert latex(g1) == r'1_{2}'
262
+ sT(g1, "IdentityGate(Integer(2))")
263
+ assert str(g1*q) == '1(2)*|10101>'
264
+ ascii_str = \
265
+ """\
266
+ 1 *|10101>\n\
267
+ 2 \
268
+ """
269
+ ucode_str = \
270
+ """\
271
+ 1 ⋅❘10101⟩\n\
272
+ 2 \
273
+ """
274
+ assert pretty(g1*q) == ascii_str
275
+ assert upretty(g1*q) == ucode_str
276
+ assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }'
277
+ sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))")
278
+ assert str(g2) == 'C((3,0),X(1))'
279
+ ascii_str = \
280
+ """\
281
+ C /X \\\n\
282
+ 3,0\\ 1/\
283
+ """
284
+ ucode_str = \
285
+ """\
286
+ C ⎛X ⎞\n\
287
+ 3,0⎝ 1⎠\
288
+ """
289
+ assert pretty(g2) == ascii_str
290
+ assert upretty(g2) == ucode_str
291
+ assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}'
292
+ sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))")
293
+ assert str(g3) == 'CNOT(1,0)'
294
+ ascii_str = \
295
+ """\
296
+ CNOT \n\
297
+ 1,0\
298
+ """
299
+ ucode_str = \
300
+ """\
301
+ CNOT \n\
302
+ 1,0\
303
+ """
304
+ assert pretty(g3) == ascii_str
305
+ assert upretty(g3) == ucode_str
306
+ assert latex(g3) == r'\text{CNOT}_{1,0}'
307
+ sT(g3, "CNotGate(Integer(1),Integer(0))")
308
+ ascii_str = \
309
+ """\
310
+ U \n\
311
+ 0\
312
+ """
313
+ ucode_str = \
314
+ """\
315
+ U \n\
316
+ 0\
317
+ """
318
+ assert str(g4) == \
319
+ """\
320
+ U((0,),Matrix([\n\
321
+ [a, b],\n\
322
+ [c, d]]))\
323
+ """
324
+ assert pretty(g4) == ascii_str
325
+ assert upretty(g4) == ucode_str
326
+ assert latex(g4) == r'U_{0}'
327
+ sT(g4, "UGate(Tuple(Integer(0)),ImmutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))")
328
+
329
+
330
+ def test_hilbert():
331
+ h1 = HilbertSpace()
332
+ h2 = ComplexSpace(2)
333
+ h3 = FockSpace()
334
+ h4 = L2(Interval(0, oo))
335
+ assert str(h1) == 'H'
336
+ assert pretty(h1) == 'H'
337
+ assert upretty(h1) == 'H'
338
+ assert latex(h1) == r'\mathcal{H}'
339
+ sT(h1, "HilbertSpace()")
340
+ assert str(h2) == 'C(2)'
341
+ ascii_str = \
342
+ """\
343
+ 2\n\
344
+ C \
345
+ """
346
+ ucode_str = \
347
+ """\
348
+ 2\n\
349
+ C \
350
+ """
351
+ assert pretty(h2) == ascii_str
352
+ assert upretty(h2) == ucode_str
353
+ assert latex(h2) == r'\mathcal{C}^{2}'
354
+ sT(h2, "ComplexSpace(Integer(2))")
355
+ assert str(h3) == 'F'
356
+ assert pretty(h3) == 'F'
357
+ assert upretty(h3) == 'F'
358
+ assert latex(h3) == r'\mathcal{F}'
359
+ sT(h3, "FockSpace()")
360
+ assert str(h4) == 'L2(Interval(0, oo))'
361
+ ascii_str = \
362
+ """\
363
+ 2\n\
364
+ L \
365
+ """
366
+ ucode_str = \
367
+ """\
368
+ 2\n\
369
+ L \
370
+ """
371
+ assert pretty(h4) == ascii_str
372
+ assert upretty(h4) == ucode_str
373
+ assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)'
374
+ sT(h4, "L2(Interval(Integer(0), oo, false, true))")
375
+ assert str(h1 + h2) == 'H+C(2)'
376
+ ascii_str = \
377
+ """\
378
+ 2\n\
379
+ H + C \
380
+ """
381
+ ucode_str = \
382
+ """\
383
+ 2\n\
384
+ H ⊕ C \
385
+ """
386
+ assert pretty(h1 + h2) == ascii_str
387
+ assert upretty(h1 + h2) == ucode_str
388
+ assert latex(h1 + h2)
389
+ sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
390
+ assert str(h1*h2) == "H*C(2)"
391
+ ascii_str = \
392
+ """\
393
+ 2\n\
394
+ H x C \
395
+ """
396
+ ucode_str = \
397
+ """\
398
+ 2\n\
399
+ H ⨂ C \
400
+ """
401
+ assert pretty(h1*h2) == ascii_str
402
+ assert upretty(h1*h2) == ucode_str
403
+ assert latex(h1*h2)
404
+ sT(h1*h2,
405
+ "TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
406
+ assert str(h1**2) == 'H**2'
407
+ ascii_str = \
408
+ """\
409
+ x2\n\
410
+ H \
411
+ """
412
+ ucode_str = \
413
+ """\
414
+ ⨂2\n\
415
+ H \
416
+ """
417
+ assert pretty(h1**2) == ascii_str
418
+ assert upretty(h1**2) == ucode_str
419
+ assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}'
420
+ sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))")
421
+
422
+
423
+ def test_innerproduct():
424
+ x = symbols('x')
425
+ ip1 = InnerProduct(Bra(), Ket())
426
+ ip2 = InnerProduct(TimeDepBra(), TimeDepKet())
427
+ ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1))
428
+ ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1)))
429
+ ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2))
430
+ ip_tall2 = InnerProduct(Bra(x), Ket(x/2))
431
+ ip_tall3 = InnerProduct(Bra(x/2), Ket(x))
432
+ assert str(ip1) == '<psi|psi>'
433
+ assert pretty(ip1) == '<psi|psi>'
434
+ assert upretty(ip1) == '⟨ψ❘ψ⟩'
435
+ assert latex(
436
+ ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }'
437
+ sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))")
438
+ assert str(ip2) == '<psi;t|psi;t>'
439
+ assert pretty(ip2) == '<psi;t|psi;t>'
440
+ assert upretty(ip2) == '⟨ψ;t❘ψ;t⟩'
441
+ assert latex(ip2) == \
442
+ r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }'
443
+ sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))")
444
+ assert str(ip3) == "<1,1|1,1>"
445
+ assert pretty(ip3) == '<1,1|1,1>'
446
+ assert upretty(ip3) == '⟨1,1❘1,1⟩'
447
+ assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }'
448
+ sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))")
449
+ assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>"
450
+ assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>'
451
+ assert upretty(ip4) == '⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩'
452
+ assert latex(ip4) == \
453
+ r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }'
454
+ sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))")
455
+ assert str(ip_tall1) == '<x/2|x/2>'
456
+ ascii_str = \
457
+ """\
458
+ / | \\ \n\
459
+ / x|x \\\n\
460
+ \\ -|- /\n\
461
+ \\2|2/ \
462
+ """
463
+ ucode_str = \
464
+ """\
465
+ ╱ │ ╲ \n\
466
+ ╱ x│x ╲\n\
467
+ ╲ ─│─ ╱\n\
468
+ ╲2│2╱ \
469
+ """
470
+ assert pretty(ip_tall1) == ascii_str
471
+ assert upretty(ip_tall1) == ucode_str
472
+ assert latex(ip_tall1) == \
473
+ r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }'
474
+ sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))")
475
+ assert str(ip_tall2) == '<x|x/2>'
476
+ ascii_str = \
477
+ """\
478
+ / | \\ \n\
479
+ / |x \\\n\
480
+ \\ x|- /\n\
481
+ \\ |2/ \
482
+ """
483
+ ucode_str = \
484
+ """\
485
+ ╱ │ ╲ \n\
486
+ ╱ │x ╲\n\
487
+ ╲ x│─ ╱\n\
488
+ ╲ │2╱ \
489
+ """
490
+ assert pretty(ip_tall2) == ascii_str
491
+ assert upretty(ip_tall2) == ucode_str
492
+ assert latex(ip_tall2) == \
493
+ r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }'
494
+ sT(ip_tall2,
495
+ "InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))")
496
+ assert str(ip_tall3) == '<x/2|x>'
497
+ ascii_str = \
498
+ """\
499
+ / | \\ \n\
500
+ / x| \\\n\
501
+ \\ -|x /\n\
502
+ \\2| / \
503
+ """
504
+ ucode_str = \
505
+ """\
506
+ ╱ │ ╲ \n\
507
+ ╱ x│ ╲\n\
508
+ ╲ ─│x ╱\n\
509
+ ╲2│ ╱ \
510
+ """
511
+ assert pretty(ip_tall3) == ascii_str
512
+ assert upretty(ip_tall3) == ucode_str
513
+ assert latex(ip_tall3) == \
514
+ r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }'
515
+ sT(ip_tall3,
516
+ "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))")
517
+
518
+
519
+ def test_operator():
520
+ a = Operator('A')
521
+ b = Operator('B', Symbol('t'), S.Half)
522
+ inv = a.inv()
523
+ f = Function('f')
524
+ x = symbols('x')
525
+ d = DifferentialOperator(Derivative(f(x), x), f(x))
526
+ op = OuterProduct(Ket(), Bra())
527
+ assert str(a) == 'A'
528
+ assert pretty(a) == 'A'
529
+ assert upretty(a) == 'A'
530
+ assert latex(a) == 'A'
531
+ sT(a, "Operator(Symbol('A'))")
532
+ assert str(inv) == 'A**(-1)'
533
+ ascii_str = \
534
+ """\
535
+ -1\n\
536
+ A \
537
+ """
538
+ ucode_str = \
539
+ """\
540
+ -1\n\
541
+ A \
542
+ """
543
+ assert pretty(inv) == ascii_str
544
+ assert upretty(inv) == ucode_str
545
+ assert latex(inv) == r'A^{-1}'
546
+ sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
547
+ assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
548
+ ascii_str = \
549
+ """\
550
+ /d \\\n\
551
+ DifferentialOperator|--(f(x)),f(x)|\n\
552
+ \\dx /\
553
+ """
554
+ ucode_str = \
555
+ """\
556
+ ⎛d ⎞\n\
557
+ DifferentialOperator⎜──(f(x)),f(x)⎟\n\
558
+ ⎝dx ⎠\
559
+ """
560
+ assert pretty(d) == ascii_str
561
+ assert upretty(d) == ucode_str
562
+ assert latex(d) == \
563
+ r'DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)'
564
+ sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))")
565
+ assert str(b) == 'Operator(B,t,1/2)'
566
+ assert pretty(b) == 'Operator(B,t,1/2)'
567
+ assert upretty(b) == 'Operator(B,t,1/2)'
568
+ assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
569
+ sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
570
+ assert str(op) == '|psi><psi|'
571
+ assert pretty(op) == '|psi><psi|'
572
+ assert upretty(op) == '❘ψ⟩⟨ψ❘'
573
+ assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
574
+ sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
575
+
576
+
577
+ def test_qexpr():
578
+ q = QExpr('q')
579
+ assert str(q) == 'q'
580
+ assert pretty(q) == 'q'
581
+ assert upretty(q) == 'q'
582
+ assert latex(q) == r'q'
583
+ sT(q, "QExpr(Symbol('q'))")
584
+
585
+
586
+ def test_qubit():
587
+ q1 = Qubit('0101')
588
+ q2 = IntQubit(8)
589
+ assert str(q1) == '|0101>'
590
+ assert pretty(q1) == '|0101>'
591
+ assert upretty(q1) == '❘0101⟩'
592
+ assert latex(q1) == r'{\left|0101\right\rangle }'
593
+ sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
594
+ assert str(q2) == '|8>'
595
+ assert pretty(q2) == '|8>'
596
+ assert upretty(q2) == '❘8⟩'
597
+ assert latex(q2) == r'{\left|8\right\rangle }'
598
+ sT(q2, "IntQubit(8)")
599
+
600
+
601
+ def test_spin():
602
+ lz = JzOp('L')
603
+ ket = JzKet(1, 0)
604
+ bra = JzBra(1, 0)
605
+ cket = JzKetCoupled(1, 0, (1, 2))
606
+ cbra = JzBraCoupled(1, 0, (1, 2))
607
+ cket_big = JzKetCoupled(1, 0, (1, 2, 3))
608
+ cbra_big = JzBraCoupled(1, 0, (1, 2, 3))
609
+ rot = Rotation(1, 2, 3)
610
+ bigd = WignerD(1, 2, 3, 4, 5, 6)
611
+ smalld = WignerD(1, 2, 3, 0, 4, 0)
612
+ assert str(lz) == 'Lz'
613
+ ascii_str = \
614
+ """\
615
+ L \n\
616
+ z\
617
+ """
618
+ ucode_str = \
619
+ """\
620
+ L \n\
621
+ z\
622
+ """
623
+ assert pretty(lz) == ascii_str
624
+ assert upretty(lz) == ucode_str
625
+ assert latex(lz) == 'L_z'
626
+ sT(lz, "JzOp(Symbol('L'))")
627
+ assert str(J2) == 'J2'
628
+ ascii_str = \
629
+ """\
630
+ 2\n\
631
+ J \
632
+ """
633
+ ucode_str = \
634
+ """\
635
+ 2\n\
636
+ J \
637
+ """
638
+ assert pretty(J2) == ascii_str
639
+ assert upretty(J2) == ucode_str
640
+ assert latex(J2) == r'J^2'
641
+ sT(J2, "J2Op(Symbol('J'))")
642
+ assert str(Jz) == 'Jz'
643
+ ascii_str = \
644
+ """\
645
+ J \n\
646
+ z\
647
+ """
648
+ ucode_str = \
649
+ """\
650
+ J \n\
651
+ z\
652
+ """
653
+ assert pretty(Jz) == ascii_str
654
+ assert upretty(Jz) == ucode_str
655
+ assert latex(Jz) == 'J_z'
656
+ sT(Jz, "JzOp(Symbol('J'))")
657
+ assert str(ket) == '|1,0>'
658
+ assert pretty(ket) == '|1,0>'
659
+ assert upretty(ket) == '❘1,0⟩'
660
+ assert latex(ket) == r'{\left|1,0\right\rangle }'
661
+ sT(ket, "JzKet(Integer(1),Integer(0))")
662
+ assert str(bra) == '<1,0|'
663
+ assert pretty(bra) == '<1,0|'
664
+ assert upretty(bra) == '⟨1,0❘'
665
+ assert latex(bra) == r'{\left\langle 1,0\right|}'
666
+ sT(bra, "JzBra(Integer(1),Integer(0))")
667
+ assert str(cket) == '|1,0,j1=1,j2=2>'
668
+ assert pretty(cket) == '|1,0,j1=1,j2=2>'
669
+ assert upretty(cket) == '❘1,0,j₁=1,j₂=2⟩'
670
+ assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }'
671
+ sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
672
+ assert str(cbra) == '<1,0,j1=1,j2=2|'
673
+ assert pretty(cbra) == '<1,0,j1=1,j2=2|'
674
+ assert upretty(cbra) == '⟨1,0,j₁=1,j₂=2❘'
675
+ assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}'
676
+ sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
677
+ assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>'
678
+ # TODO: Fix non-unicode pretty printing
679
+ # i.e. j1,2 -> j(1,2)
680
+ assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>'
681
+ assert upretty(cket_big) == '❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩'
682
+ assert latex(cket_big) == \
683
+ r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }'
684
+ sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
685
+ assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|'
686
+ assert pretty(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j1,2=3|'
687
+ assert upretty(cbra_big) == '⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘'
688
+ assert latex(cbra_big) == \
689
+ r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}'
690
+ sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
691
+ assert str(rot) == 'R(1,2,3)'
692
+ assert pretty(rot) == 'R (1,2,3)'
693
+ assert upretty(rot) == 'ℛ (1,2,3)'
694
+ assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)'
695
+ sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))")
696
+ assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)'
697
+ ascii_str = \
698
+ """\
699
+ 1 \n\
700
+ D (4,5,6)\n\
701
+ 2,3 \
702
+ """
703
+ ucode_str = \
704
+ """\
705
+ 1 \n\
706
+ D (4,5,6)\n\
707
+ 2,3 \
708
+ """
709
+ assert pretty(bigd) == ascii_str
710
+ assert upretty(bigd) == ucode_str
711
+ assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)'
712
+ sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
713
+ assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)'
714
+ ascii_str = \
715
+ """\
716
+ 1 \n\
717
+ d (4)\n\
718
+ 2,3 \
719
+ """
720
+ ucode_str = \
721
+ """\
722
+ 1 \n\
723
+ d (4)\n\
724
+ 2,3 \
725
+ """
726
+ assert pretty(smalld) == ascii_str
727
+ assert upretty(smalld) == ucode_str
728
+ assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)'
729
+ sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))")
730
+
731
+
732
+ def test_state():
733
+ x = symbols('x')
734
+ bra = Bra()
735
+ ket = Ket()
736
+ bra_tall = Bra(x/2)
737
+ ket_tall = Ket(x/2)
738
+ tbra = TimeDepBra()
739
+ tket = TimeDepKet()
740
+ assert str(bra) == '<psi|'
741
+ assert pretty(bra) == '<psi|'
742
+ assert upretty(bra) == '⟨ψ❘'
743
+ assert latex(bra) == r'{\left\langle \psi\right|}'
744
+ sT(bra, "Bra(Symbol('psi'))")
745
+ assert str(ket) == '|psi>'
746
+ assert pretty(ket) == '|psi>'
747
+ assert upretty(ket) == '❘ψ⟩'
748
+ assert latex(ket) == r'{\left|\psi\right\rangle }'
749
+ sT(ket, "Ket(Symbol('psi'))")
750
+ assert str(bra_tall) == '<x/2|'
751
+ ascii_str = \
752
+ """\
753
+ / |\n\
754
+ / x|\n\
755
+ \\ -|\n\
756
+ \\2|\
757
+ """
758
+ ucode_str = \
759
+ """\
760
+ ╱ │\n\
761
+ ╱ x│\n\
762
+ ╲ ─│\n\
763
+ ╲2│\
764
+ """
765
+ assert pretty(bra_tall) == ascii_str
766
+ assert upretty(bra_tall) == ucode_str
767
+ assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}'
768
+ sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))")
769
+ assert str(ket_tall) == '|x/2>'
770
+ ascii_str = \
771
+ """\
772
+ | \\ \n\
773
+ |x \\\n\
774
+ |- /\n\
775
+ |2/ \
776
+ """
777
+ ucode_str = \
778
+ """\
779
+ │ ╲ \n\
780
+ │x ╲\n\
781
+ │─ ╱\n\
782
+ │2╱ \
783
+ """
784
+ assert pretty(ket_tall) == ascii_str
785
+ assert upretty(ket_tall) == ucode_str
786
+ assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }'
787
+ sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))")
788
+ assert str(tbra) == '<psi;t|'
789
+ assert pretty(tbra) == '<psi;t|'
790
+ assert upretty(tbra) == '⟨ψ;t❘'
791
+ assert latex(tbra) == r'{\left\langle \psi;t\right|}'
792
+ sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))")
793
+ assert str(tket) == '|psi;t>'
794
+ assert pretty(tket) == '|psi;t>'
795
+ assert upretty(tket) == '❘ψ;t⟩'
796
+ assert latex(tket) == r'{\left|\psi;t\right\rangle }'
797
+ sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))")
798
+
799
+
800
+ def test_tensorproduct():
801
+ tp = TensorProduct(JzKet(1, 1), JzKet(1, 0))
802
+ assert str(tp) == '|1,1>x|1,0>'
803
+ assert pretty(tp) == '|1,1>x |1,0>'
804
+ assert upretty(tp) == '❘1,1⟩⨂ ❘1,0⟩'
805
+ assert latex(tp) == \
806
+ r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}'
807
+ sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))")
808
+
809
+
810
+ def test_big_expr():
811
+ f = Function('f')
812
+ x = symbols('x')
813
+ e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1))
814
+ e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2))
815
+ e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1)))
816
+ e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval(
817
+ 0, oo)) + HilbertSpace())
818
+ assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
819
+ ascii_str = \
820
+ """\
821
+ / 3 \\ \n\
822
+ |/ +\\ | \n\
823
+ 2 / + +\\ <| /d \\ | + +> \n\
824
+ /J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
825
+ \\ z/ \\\\ \\dx / / / \
826
+ """
827
+ ucode_str = \
828
+ """\
829
+ ⎧ 3 ⎫ \n\
830
+ ⎪⎛ †⎞ ⎪ \n\
831
+ 2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\
832
+ ⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
833
+ ⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \
834
+ """
835
+ assert pretty(e1) == ascii_str
836
+ assert upretty(e1) == ucode_str
837
+ assert latex(e1) == \
838
+ r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
839
+ sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))")
840
+ assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
841
+ ascii_str = \
842
+ """\
843
+ [ 2 ] / -2 + +\\ [ 2 ]\n\
844
+ [/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\
845
+ [\\ z/ ] \\ / [ z]\
846
+ """
847
+ ucode_str = \
848
+ """\
849
+ ⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\
850
+ ⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
851
+ ⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\
852
+ """
853
+ assert pretty(e2) == ascii_str
854
+ assert upretty(e2) == ucode_str
855
+ assert latex(e2) == \
856
+ r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]'
857
+ sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))")
858
+ assert str(e3) == \
859
+ "Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
860
+ ascii_str = \
861
+ """\
862
+ [ + ] / 2 \\ \n\
863
+ /1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
864
+ | | \\ z/ \n\
865
+ \\2 4 6/ \
866
+ """
867
+ ucode_str = \
868
+ """\
869
+ ⎡ † ⎤ ⎛ 2 ⎞ \n\
870
+ ⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
871
+ ⎜ ⎟ ⎝ z⎠ \n\
872
+ ⎝2 4 6⎠ \
873
+ """
874
+ assert pretty(e3) == ascii_str
875
+ assert upretty(e3) == ucode_str
876
+ assert latex(e3) == \
877
+ r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
878
+ sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))")
879
+ assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)'
880
+ ascii_str = \
881
+ """\
882
+ // 1 2\\ x2\\ / 2 \\\n\
883
+ \\\\C x C / + F / x \\L + H/\
884
+ """
885
+ ucode_str = \
886
+ """\
887
+ ⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\
888
+ ⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\
889
+ """
890
+ assert pretty(e4) == ascii_str
891
+ assert upretty(e4) == ucode_str
892
+ assert latex(e4) == \
893
+ r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
894
+ sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))")
895
+
896
+
897
+ def _test_sho1d():
898
+ ad = RaisingOp('a')
899
+ assert pretty(ad) == ' \N{DAGGER}\na '
900
+ assert latex(ad) == 'a^{\\dagger}'
janus/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")]
janus/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_spin.py ADDED
The diff for this file is too large to render. See raw diff
 
janus/lib/python3.10/site-packages/sympy/physics/quantum/trace.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.containers import Tuple
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.power import Pow
6
+ from sympy.core.sorting import default_sort_key
7
+ from sympy.core.sympify import sympify
8
+ from sympy.matrices import Matrix
9
+
10
+
11
+ def _is_scalar(e):
12
+ """ Helper method used in Tr"""
13
+
14
+ # sympify to set proper attributes
15
+ e = sympify(e)
16
+ if isinstance(e, Expr):
17
+ if (e.is_Integer or e.is_Float or
18
+ e.is_Rational or e.is_Number or
19
+ (e.is_Symbol and e.is_commutative)
20
+ ):
21
+ return True
22
+
23
+ return False
24
+
25
+
26
+ def _cycle_permute(l):
27
+ """ Cyclic permutations based on canonical ordering
28
+
29
+ Explanation
30
+ ===========
31
+
32
+ This method does the sort based ascii values while
33
+ a better approach would be to used lexicographic sort.
34
+
35
+ TODO: Handle condition such as symbols have subscripts/superscripts
36
+ in case of lexicographic sort
37
+
38
+ """
39
+
40
+ if len(l) == 1:
41
+ return l
42
+
43
+ min_item = min(l, key=default_sort_key)
44
+ indices = [i for i, x in enumerate(l) if x == min_item]
45
+
46
+ le = list(l)
47
+ le.extend(l) # duplicate and extend string for easy processing
48
+
49
+ # adding the first min_item index back for easier looping
50
+ indices.append(len(l) + indices[0])
51
+
52
+ # create sublist of items with first item as min_item and last_item
53
+ # in each of the sublist is item just before the next occurrence of
54
+ # minitem in the cycle formed.
55
+ sublist = [[le[indices[i]:indices[i + 1]]] for i in
56
+ range(len(indices) - 1)]
57
+
58
+ # we do comparison of strings by comparing elements
59
+ # in each sublist
60
+ idx = sublist.index(min(sublist))
61
+ ordered_l = le[indices[idx]:indices[idx] + len(l)]
62
+
63
+ return ordered_l
64
+
65
+
66
+ def _rearrange_args(l):
67
+ """ this just moves the last arg to first position
68
+ to enable expansion of args
69
+ A,B,A ==> A**2,B
70
+ """
71
+ if len(l) == 1:
72
+ return l
73
+
74
+ x = list(l[-1:])
75
+ x.extend(l[0:-1])
76
+ return Mul(*x).args
77
+
78
+
79
+ class Tr(Expr):
80
+ """ Generic Trace operation than can trace over:
81
+
82
+ a) SymPy matrix
83
+ b) operators
84
+ c) outer products
85
+
86
+ Parameters
87
+ ==========
88
+ o : operator, matrix, expr
89
+ i : tuple/list indices (optional)
90
+
91
+ Examples
92
+ ========
93
+
94
+ # TODO: Need to handle printing
95
+
96
+ a) Trace(A+B) = Tr(A) + Tr(B)
97
+ b) Trace(scalar*Operator) = scalar*Trace(Operator)
98
+
99
+ >>> from sympy.physics.quantum.trace import Tr
100
+ >>> from sympy import symbols, Matrix
101
+ >>> a, b = symbols('a b', commutative=True)
102
+ >>> A, B = symbols('A B', commutative=False)
103
+ >>> Tr(a*A,[2])
104
+ a*Tr(A)
105
+ >>> m = Matrix([[1,2],[1,1]])
106
+ >>> Tr(m)
107
+ 2
108
+
109
+ """
110
+ def __new__(cls, *args):
111
+ """ Construct a Trace object.
112
+
113
+ Parameters
114
+ ==========
115
+ args = SymPy expression
116
+ indices = tuple/list if indices, optional
117
+
118
+ """
119
+
120
+ # expect no indices,int or a tuple/list/Tuple
121
+ if (len(args) == 2):
122
+ if not isinstance(args[1], (list, Tuple, tuple)):
123
+ indices = Tuple(args[1])
124
+ else:
125
+ indices = Tuple(*args[1])
126
+
127
+ expr = args[0]
128
+ elif (len(args) == 1):
129
+ indices = Tuple()
130
+ expr = args[0]
131
+ else:
132
+ raise ValueError("Arguments to Tr should be of form "
133
+ "(expr[, [indices]])")
134
+
135
+ if isinstance(expr, Matrix):
136
+ return expr.trace()
137
+ elif hasattr(expr, 'trace') and callable(expr.trace):
138
+ #for any objects that have trace() defined e.g numpy
139
+ return expr.trace()
140
+ elif isinstance(expr, Add):
141
+ return Add(*[Tr(arg, indices) for arg in expr.args])
142
+ elif isinstance(expr, Mul):
143
+ c_part, nc_part = expr.args_cnc()
144
+ if len(nc_part) == 0:
145
+ return Mul(*c_part)
146
+ else:
147
+ obj = Expr.__new__(cls, Mul(*nc_part), indices )
148
+ #this check is needed to prevent cached instances
149
+ #being returned even if len(c_part)==0
150
+ return Mul(*c_part)*obj if len(c_part) > 0 else obj
151
+ elif isinstance(expr, Pow):
152
+ if (_is_scalar(expr.args[0]) and
153
+ _is_scalar(expr.args[1])):
154
+ return expr
155
+ else:
156
+ return Expr.__new__(cls, expr, indices)
157
+ else:
158
+ if (_is_scalar(expr)):
159
+ return expr
160
+
161
+ return Expr.__new__(cls, expr, indices)
162
+
163
+ @property
164
+ def kind(self):
165
+ expr = self.args[0]
166
+ expr_kind = expr.kind
167
+ return expr_kind.element_kind
168
+
169
+ def doit(self, **hints):
170
+ """ Perform the trace operation.
171
+
172
+ #TODO: Current version ignores the indices set for partial trace.
173
+
174
+ >>> from sympy.physics.quantum.trace import Tr
175
+ >>> from sympy.physics.quantum.operator import OuterProduct
176
+ >>> from sympy.physics.quantum.spin import JzKet, JzBra
177
+ >>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1)))
178
+ >>> t.doit()
179
+ 1
180
+
181
+ """
182
+ if hasattr(self.args[0], '_eval_trace'):
183
+ return self.args[0]._eval_trace(indices=self.args[1])
184
+
185
+ return self
186
+
187
+ @property
188
+ def is_number(self):
189
+ # TODO : improve this implementation
190
+ return True
191
+
192
+ #TODO: Review if the permute method is needed
193
+ # and if it needs to return a new instance
194
+ def permute(self, pos):
195
+ """ Permute the arguments cyclically.
196
+
197
+ Parameters
198
+ ==========
199
+
200
+ pos : integer, if positive, shift-right, else shift-left
201
+
202
+ Examples
203
+ ========
204
+
205
+ >>> from sympy.physics.quantum.trace import Tr
206
+ >>> from sympy import symbols
207
+ >>> A, B, C, D = symbols('A B C D', commutative=False)
208
+ >>> t = Tr(A*B*C*D)
209
+ >>> t.permute(2)
210
+ Tr(C*D*A*B)
211
+ >>> t.permute(-2)
212
+ Tr(C*D*A*B)
213
+
214
+ """
215
+ if pos > 0:
216
+ pos = pos % len(self.args[0].args)
217
+ else:
218
+ pos = -(abs(pos) % len(self.args[0].args))
219
+
220
+ args = list(self.args[0].args[-pos:] + self.args[0].args[0:-pos])
221
+
222
+ return Tr(Mul(*(args)))
223
+
224
+ def _hashable_content(self):
225
+ if isinstance(self.args[0], Mul):
226
+ args = _cycle_permute(_rearrange_args(self.args[0].args))
227
+ else:
228
+ args = [self.args[0]]
229
+
230
+ return tuple(args) + (self.args[1], )
janus/lib/python3.10/site-packages/sympy/physics/units/__pycache__/prefixes.cpython-310.pyc ADDED
Binary file (6.1 kB). View file