applied-ai-018 commited on
Commit
58d37b5
·
verified ·
1 Parent(s): 660f2ea

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. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/paulialgebra.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/wigner.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py +782 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py +108 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__init__.py +15 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/control_plots.py +961 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/lti.py +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__init__.py +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py +716 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py +427 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py +178 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py +13 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py +36 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_hilbert.py +110 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_operatorordering.py +38 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_printing.py +900 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_qft.py +50 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py +189 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_shor.py +21 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_spin.py +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__init__.py +36 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/__init__.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/dyadic.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/fieldfunctions.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/frame.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/functions.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/point.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/printing.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/vector.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (419 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/hydrogen.cpython-310.pyc ADDED
Binary file (7.36 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/matrices.cpython-310.pyc ADDED
Binary file (3.63 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/paulialgebra.cpython-310.pyc ADDED
Binary file (6.14 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/qho_1d.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/secondquant.cpython-310.pyc ADDED
Binary file (83.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/wigner.cpython-310.pyc ADDED
Binary file (37.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (299 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc ADDED
Binary file (120 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc ADDED
Binary file (22.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (204 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand
2
+ from sympy.core.numbers import (Rational, pi)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.sets.sets import Interval
6
+ from sympy.simplify.simplify import simplify
7
+ from sympy.physics.continuum_mechanics.beam import Beam
8
+ from sympy.functions import SingularityFunction, Piecewise, meijerg, Abs, log
9
+ from sympy.testing.pytest import raises
10
+ from sympy.physics.units import meter, newton, kilo, giga, milli
11
+ from sympy.physics.continuum_mechanics.beam import Beam3D
12
+ from sympy.geometry import Circle, Polygon, Point2D, Triangle
13
+ from sympy.core.sympify import sympify
14
+
15
+ x = Symbol('x')
16
+ y = Symbol('y')
17
+ R1, R2 = symbols('R1, R2')
18
+
19
+
20
+ def test_Beam():
21
+ E = Symbol('E')
22
+ E_1 = Symbol('E_1')
23
+ I = Symbol('I')
24
+ I_1 = Symbol('I_1')
25
+ A = Symbol('A')
26
+
27
+ b = Beam(1, E, I)
28
+ assert b.length == 1
29
+ assert b.elastic_modulus == E
30
+ assert b.second_moment == I
31
+ assert b.variable == x
32
+
33
+ # Test the length setter
34
+ b.length = 4
35
+ assert b.length == 4
36
+
37
+ # Test the E setter
38
+ b.elastic_modulus = E_1
39
+ assert b.elastic_modulus == E_1
40
+
41
+ # Test the I setter
42
+ b.second_moment = I_1
43
+ assert b.second_moment is I_1
44
+
45
+ # Test the variable setter
46
+ b.variable = y
47
+ assert b.variable is y
48
+
49
+ # Test for all boundary conditions.
50
+ b.bc_deflection = [(0, 2)]
51
+ b.bc_slope = [(0, 1)]
52
+ assert b.boundary_conditions == {'deflection': [(0, 2)], 'slope': [(0, 1)]}
53
+
54
+ # Test for slope boundary condition method
55
+ b.bc_slope.extend([(4, 3), (5, 0)])
56
+ s_bcs = b.bc_slope
57
+ assert s_bcs == [(0, 1), (4, 3), (5, 0)]
58
+
59
+ # Test for deflection boundary condition method
60
+ b.bc_deflection.extend([(4, 3), (5, 0)])
61
+ d_bcs = b.bc_deflection
62
+ assert d_bcs == [(0, 2), (4, 3), (5, 0)]
63
+
64
+ # Test for updated boundary conditions
65
+ bcs_new = b.boundary_conditions
66
+ assert bcs_new == {
67
+ 'deflection': [(0, 2), (4, 3), (5, 0)],
68
+ 'slope': [(0, 1), (4, 3), (5, 0)]}
69
+
70
+ b1 = Beam(30, E, I)
71
+ b1.apply_load(-8, 0, -1)
72
+ b1.apply_load(R1, 10, -1)
73
+ b1.apply_load(R2, 30, -1)
74
+ b1.apply_load(120, 30, -2)
75
+ b1.bc_deflection = [(10, 0), (30, 0)]
76
+ b1.solve_for_reaction_loads(R1, R2)
77
+
78
+ # Test for finding reaction forces
79
+ p = b1.reaction_loads
80
+ q = {R1: 6, R2: 2}
81
+ assert p == q
82
+
83
+ # Test for load distribution function.
84
+ p = b1.load
85
+ q = -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) \
86
+ + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
87
+ assert p == q
88
+
89
+ # Test for shear force distribution function
90
+ p = b1.shear_force()
91
+ q = 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
92
+ - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
93
+ assert p == q
94
+
95
+ # Test for shear stress distribution function
96
+ p = b1.shear_stress()
97
+ q = (8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
98
+ - 120*SingularityFunction(x, 30, -1) \
99
+ - 2*SingularityFunction(x, 30, 0))/A
100
+ assert p==q
101
+
102
+ # Test for bending moment distribution function
103
+ p = b1.bending_moment()
104
+ q = 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) \
105
+ - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
106
+ assert p == q
107
+
108
+ # Test for slope distribution function
109
+ p = b1.slope()
110
+ q = -4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) \
111
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) \
112
+ + Rational(4000, 3)
113
+ assert p == q/(E*I)
114
+
115
+ # Test for deflection distribution function
116
+ p = b1.deflection()
117
+ q = x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 \
118
+ + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) \
119
+ + SingularityFunction(x, 30, 3)/3 - 12000
120
+ assert p == q/(E*I)
121
+
122
+ # Test using symbols
123
+ l = Symbol('l')
124
+ w0 = Symbol('w0')
125
+ w2 = Symbol('w2')
126
+ a1 = Symbol('a1')
127
+ c = Symbol('c')
128
+ c1 = Symbol('c1')
129
+ d = Symbol('d')
130
+ e = Symbol('e')
131
+ f = Symbol('f')
132
+
133
+ b2 = Beam(l, E, I)
134
+
135
+ b2.apply_load(w0, a1, 1)
136
+ b2.apply_load(w2, c1, -1)
137
+
138
+ b2.bc_deflection = [(c, d)]
139
+ b2.bc_slope = [(e, f)]
140
+
141
+ # Test for load distribution function.
142
+ p = b2.load
143
+ q = w0*SingularityFunction(x, a1, 1) + w2*SingularityFunction(x, c1, -1)
144
+ assert p == q
145
+
146
+ # Test for shear force distribution function
147
+ p = b2.shear_force()
148
+ q = -w0*SingularityFunction(x, a1, 2)/2 \
149
+ - w2*SingularityFunction(x, c1, 0)
150
+ assert p == q
151
+
152
+ # Test for shear stress distribution function
153
+ p = b2.shear_stress()
154
+ q = (-w0*SingularityFunction(x, a1, 2)/2 \
155
+ - w2*SingularityFunction(x, c1, 0))/A
156
+ assert p == q
157
+
158
+ # Test for bending moment distribution function
159
+ p = b2.bending_moment()
160
+ q = -w0*SingularityFunction(x, a1, 3)/6 - w2*SingularityFunction(x, c1, 1)
161
+ assert p == q
162
+
163
+ # Test for slope distribution function
164
+ p = b2.slope()
165
+ q = (w0*SingularityFunction(x, a1, 4)/24 + w2*SingularityFunction(x, c1, 2)/2)/(E*I) + (E*I*f - w0*SingularityFunction(e, a1, 4)/24 - w2*SingularityFunction(e, c1, 2)/2)/(E*I)
166
+ assert expand(p) == expand(q)
167
+
168
+ # Test for deflection distribution function
169
+ p = b2.deflection()
170
+ q = x*(E*I*f - w0*SingularityFunction(e, a1, 4)/24 \
171
+ - w2*SingularityFunction(e, c1, 2)/2)/(E*I) \
172
+ + (w0*SingularityFunction(x, a1, 5)/120 \
173
+ + w2*SingularityFunction(x, c1, 3)/6)/(E*I) \
174
+ + (E*I*(-c*f + d) + c*w0*SingularityFunction(e, a1, 4)/24 \
175
+ + c*w2*SingularityFunction(e, c1, 2)/2 \
176
+ - w0*SingularityFunction(c, a1, 5)/120 \
177
+ - w2*SingularityFunction(c, c1, 3)/6)/(E*I)
178
+ assert simplify(p - q) == 0
179
+
180
+ b3 = Beam(9, E, I, 2)
181
+ b3.apply_load(value=-2, start=2, order=2, end=3)
182
+ b3.bc_slope.append((0, 2))
183
+ C3 = symbols('C3')
184
+ C4 = symbols('C4')
185
+
186
+ p = b3.load
187
+ q = -2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) \
188
+ + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
189
+ assert p == q
190
+
191
+ p = b3.shear_force()
192
+ q = 2*SingularityFunction(x, 2, 3)/3 - 2*SingularityFunction(x, 3, 1) \
193
+ - 2*SingularityFunction(x, 3, 2) - 2*SingularityFunction(x, 3, 3)/3
194
+ assert p == q
195
+
196
+ p = b3.shear_stress()
197
+ q = SingularityFunction(x, 2, 3)/3 - 1*SingularityFunction(x, 3, 1) \
198
+ - 1*SingularityFunction(x, 3, 2) - 1*SingularityFunction(x, 3, 3)/3
199
+ assert p == q
200
+
201
+ p = b3.slope()
202
+ q = 2 - (SingularityFunction(x, 2, 5)/30 - SingularityFunction(x, 3, 3)/3 \
203
+ - SingularityFunction(x, 3, 4)/6 - SingularityFunction(x, 3, 5)/30)/(E*I)
204
+ assert p == q
205
+
206
+ p = b3.deflection()
207
+ q = 2*x - (SingularityFunction(x, 2, 6)/180 \
208
+ - SingularityFunction(x, 3, 4)/12 - SingularityFunction(x, 3, 5)/30 \
209
+ - SingularityFunction(x, 3, 6)/180)/(E*I)
210
+ assert p == q + C4
211
+
212
+ b4 = Beam(4, E, I, 3)
213
+ b4.apply_load(-3, 0, 0, end=3)
214
+
215
+ p = b4.load
216
+ q = -3*SingularityFunction(x, 0, 0) + 3*SingularityFunction(x, 3, 0)
217
+ assert p == q
218
+
219
+ p = b4.shear_force()
220
+ q = 3*SingularityFunction(x, 0, 1) \
221
+ - 3*SingularityFunction(x, 3, 1)
222
+ assert p == q
223
+
224
+ p = b4.shear_stress()
225
+ q = SingularityFunction(x, 0, 1) - SingularityFunction(x, 3, 1)
226
+ assert p == q
227
+
228
+ p = b4.slope()
229
+ q = -3*SingularityFunction(x, 0, 3)/6 + 3*SingularityFunction(x, 3, 3)/6
230
+ assert p == q/(E*I) + C3
231
+
232
+ p = b4.deflection()
233
+ q = -3*SingularityFunction(x, 0, 4)/24 + 3*SingularityFunction(x, 3, 4)/24
234
+ assert p == q/(E*I) + C3*x + C4
235
+
236
+ # can't use end with point loads
237
+ raises(ValueError, lambda: b4.apply_load(-3, 0, -1, end=3))
238
+ with raises(TypeError):
239
+ b4.variable = 1
240
+
241
+
242
+ def test_insufficient_bconditions():
243
+ # Test cases when required number of boundary conditions
244
+ # are not provided to solve the integration constants.
245
+ L = symbols('L', positive=True)
246
+ E, I, P, a3, a4 = symbols('E I P a3 a4')
247
+
248
+ b = Beam(L, E, I, base_char='a')
249
+ b.apply_load(R2, L, -1)
250
+ b.apply_load(R1, 0, -1)
251
+ b.apply_load(-P, L/2, -1)
252
+ b.solve_for_reaction_loads(R1, R2)
253
+
254
+ p = b.slope()
255
+ q = P*SingularityFunction(x, 0, 2)/4 - P*SingularityFunction(x, L/2, 2)/2 + P*SingularityFunction(x, L, 2)/4
256
+ assert p == q/(E*I) + a3
257
+
258
+ p = b.deflection()
259
+ q = P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
260
+ assert p == q/(E*I) + a3*x + a4
261
+
262
+ b.bc_deflection = [(0, 0)]
263
+ p = b.deflection()
264
+ q = a3*x + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
265
+ assert p == q/(E*I)
266
+
267
+ b.bc_deflection = [(0, 0), (L, 0)]
268
+ p = b.deflection()
269
+ q = -L**2*P*x/16 + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
270
+ assert p == q/(E*I)
271
+
272
+
273
+ def test_statically_indeterminate():
274
+ E = Symbol('E')
275
+ I = Symbol('I')
276
+ M1, M2 = symbols('M1, M2')
277
+ F = Symbol('F')
278
+ l = Symbol('l', positive=True)
279
+
280
+ b5 = Beam(l, E, I)
281
+ b5.bc_deflection = [(0, 0),(l, 0)]
282
+ b5.bc_slope = [(0, 0),(l, 0)]
283
+
284
+ b5.apply_load(R1, 0, -1)
285
+ b5.apply_load(M1, 0, -2)
286
+ b5.apply_load(R2, l, -1)
287
+ b5.apply_load(M2, l, -2)
288
+ b5.apply_load(-F, l/2, -1)
289
+
290
+ b5.solve_for_reaction_loads(R1, R2, M1, M2)
291
+ p = b5.reaction_loads
292
+ q = {R1: F/2, R2: F/2, M1: -F*l/8, M2: F*l/8}
293
+ assert p == q
294
+
295
+
296
+ def test_beam_units():
297
+ E = Symbol('E')
298
+ I = Symbol('I')
299
+ R1, R2 = symbols('R1, R2')
300
+
301
+ kN = kilo*newton
302
+ gN = giga*newton
303
+
304
+ b = Beam(8*meter, 200*gN/meter**2, 400*1000000*(milli*meter)**4)
305
+ b.apply_load(5*kN, 2*meter, -1)
306
+ b.apply_load(R1, 0*meter, -1)
307
+ b.apply_load(R2, 8*meter, -1)
308
+ b.apply_load(10*kN/meter, 4*meter, 0, end=8*meter)
309
+ b.bc_deflection = [(0*meter, 0*meter), (8*meter, 0*meter)]
310
+ b.solve_for_reaction_loads(R1, R2)
311
+ assert b.reaction_loads == {R1: -13750*newton, R2: -31250*newton}
312
+
313
+ b = Beam(3*meter, E*newton/meter**2, I*meter**4)
314
+ b.apply_load(8*kN, 1*meter, -1)
315
+ b.apply_load(R1, 0*meter, -1)
316
+ b.apply_load(R2, 3*meter, -1)
317
+ b.apply_load(12*kN*meter, 2*meter, -2)
318
+ b.bc_deflection = [(0*meter, 0*meter), (3*meter, 0*meter)]
319
+ b.solve_for_reaction_loads(R1, R2)
320
+ assert b.reaction_loads == {R1: newton*Rational(-28000, 3), R2: newton*Rational(4000, 3)}
321
+ assert b.deflection().subs(x, 1*meter) == 62000*meter/(9*E*I)
322
+
323
+
324
+ def test_variable_moment():
325
+ E = Symbol('E')
326
+ I = Symbol('I')
327
+
328
+ b = Beam(4, E, 2*(4 - x))
329
+ b.apply_load(20, 4, -1)
330
+ R, M = symbols('R, M')
331
+ b.apply_load(R, 0, -1)
332
+ b.apply_load(M, 0, -2)
333
+ b.bc_deflection = [(0, 0)]
334
+ b.bc_slope = [(0, 0)]
335
+ b.solve_for_reaction_loads(R, M)
336
+ assert b.slope().expand() == ((10*x*SingularityFunction(x, 0, 0)
337
+ - 10*(x - 4)*SingularityFunction(x, 4, 0))/E).expand()
338
+ assert b.deflection().expand() == ((5*x**2*SingularityFunction(x, 0, 0)
339
+ - 10*Piecewise((0, Abs(x)/4 < 1), (16*meijerg(((3, 1), ()), ((), (2, 0)), x/4), True))
340
+ + 40*SingularityFunction(x, 4, 1))/E).expand()
341
+
342
+ b = Beam(4, E - x, I)
343
+ b.apply_load(20, 4, -1)
344
+ R, M = symbols('R, M')
345
+ b.apply_load(R, 0, -1)
346
+ b.apply_load(M, 0, -2)
347
+ b.bc_deflection = [(0, 0)]
348
+ b.bc_slope = [(0, 0)]
349
+ b.solve_for_reaction_loads(R, M)
350
+ assert b.slope().expand() == ((-80*(-log(-E) + log(-E + x))*SingularityFunction(x, 0, 0)
351
+ + 80*(-log(-E + 4) + log(-E + x))*SingularityFunction(x, 4, 0) + 20*(-E*log(-E)
352
+ + E*log(-E + x) + x)*SingularityFunction(x, 0, 0) - 20*(-E*log(-E + 4) + E*log(-E + x)
353
+ + x - 4)*SingularityFunction(x, 4, 0))/I).expand()
354
+
355
+
356
+ def test_composite_beam():
357
+ E = Symbol('E')
358
+ I = Symbol('I')
359
+ b1 = Beam(2, E, 1.5*I)
360
+ b2 = Beam(2, E, I)
361
+ b = b1.join(b2, "fixed")
362
+ b.apply_load(-20, 0, -1)
363
+ b.apply_load(80, 0, -2)
364
+ b.apply_load(20, 4, -1)
365
+ b.bc_slope = [(0, 0)]
366
+ b.bc_deflection = [(0, 0)]
367
+ assert b.length == 4
368
+ assert b.second_moment == Piecewise((1.5*I, x <= 2), (I, x <= 4))
369
+ assert b.slope().subs(x, 4) == 120.0/(E*I)
370
+ assert b.slope().subs(x, 2) == 80.0/(E*I)
371
+ assert int(b.deflection().subs(x, 4).args[0]) == -302 # Coefficient of 1/(E*I)
372
+
373
+ l = symbols('l', positive=True)
374
+ R1, M1, R2, R3, P = symbols('R1 M1 R2 R3 P')
375
+ b1 = Beam(2*l, E, I)
376
+ b2 = Beam(2*l, E, I)
377
+ b = b1.join(b2,"hinge")
378
+ b.apply_load(M1, 0, -2)
379
+ b.apply_load(R1, 0, -1)
380
+ b.apply_load(R2, l, -1)
381
+ b.apply_load(R3, 4*l, -1)
382
+ b.apply_load(P, 3*l, -1)
383
+ b.bc_slope = [(0, 0)]
384
+ b.bc_deflection = [(0, 0), (l, 0), (4*l, 0)]
385
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
386
+ assert b.reaction_loads == {R3: -P/2, R2: P*Rational(-5, 4), M1: -P*l/4, R1: P*Rational(3, 4)}
387
+ assert b.slope().subs(x, 3*l) == -7*P*l**2/(48*E*I)
388
+ assert b.deflection().subs(x, 2*l) == 7*P*l**3/(24*E*I)
389
+ assert b.deflection().subs(x, 3*l) == 5*P*l**3/(16*E*I)
390
+
391
+ # When beams having same second moment are joined.
392
+ b1 = Beam(2, 500, 10)
393
+ b2 = Beam(2, 500, 10)
394
+ b = b1.join(b2, "fixed")
395
+ b.apply_load(M1, 0, -2)
396
+ b.apply_load(R1, 0, -1)
397
+ b.apply_load(R2, 1, -1)
398
+ b.apply_load(R3, 4, -1)
399
+ b.apply_load(10, 3, -1)
400
+ b.bc_slope = [(0, 0)]
401
+ b.bc_deflection = [(0, 0), (1, 0), (4, 0)]
402
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
403
+ assert b.slope() == -2*SingularityFunction(x, 0, 1)/5625 + SingularityFunction(x, 0, 2)/1875\
404
+ - 133*SingularityFunction(x, 1, 2)/135000 + SingularityFunction(x, 3, 2)/1000\
405
+ - 37*SingularityFunction(x, 4, 2)/67500
406
+ assert b.deflection() == -SingularityFunction(x, 0, 2)/5625 + SingularityFunction(x, 0, 3)/5625\
407
+ - 133*SingularityFunction(x, 1, 3)/405000 + SingularityFunction(x, 3, 3)/3000\
408
+ - 37*SingularityFunction(x, 4, 3)/202500
409
+
410
+
411
+ def test_point_cflexure():
412
+ E = Symbol('E')
413
+ I = Symbol('I')
414
+ b = Beam(10, E, I)
415
+ b.apply_load(-4, 0, -1)
416
+ b.apply_load(-46, 6, -1)
417
+ b.apply_load(10, 2, -1)
418
+ b.apply_load(20, 4, -1)
419
+ b.apply_load(3, 6, 0)
420
+ assert b.point_cflexure() == [Rational(10, 3)]
421
+
422
+
423
+ def test_remove_load():
424
+ E = Symbol('E')
425
+ I = Symbol('I')
426
+ b = Beam(4, E, I)
427
+
428
+ try:
429
+ b.remove_load(2, 1, -1)
430
+ # As no load is applied on beam, ValueError should be returned.
431
+ except ValueError:
432
+ assert True
433
+ else:
434
+ assert False
435
+
436
+ b.apply_load(-3, 0, -2)
437
+ b.apply_load(4, 2, -1)
438
+ b.apply_load(-2, 2, 2, end = 3)
439
+ b.remove_load(-2, 2, 2, end = 3)
440
+ assert b.load == -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
441
+ assert b.applied_loads == [(-3, 0, -2, None), (4, 2, -1, None)]
442
+
443
+ try:
444
+ b.remove_load(1, 2, -1)
445
+ # As load of this magnitude was never applied at
446
+ # this position, method should return a ValueError.
447
+ except ValueError:
448
+ assert True
449
+ else:
450
+ assert False
451
+
452
+ b.remove_load(-3, 0, -2)
453
+ b.remove_load(4, 2, -1)
454
+ assert b.load == 0
455
+ assert b.applied_loads == []
456
+
457
+
458
+ def test_apply_support():
459
+ E = Symbol('E')
460
+ I = Symbol('I')
461
+
462
+ b = Beam(4, E, I)
463
+ b.apply_support(0, "cantilever")
464
+ b.apply_load(20, 4, -1)
465
+ M_0, R_0 = symbols('M_0, R_0')
466
+ b.solve_for_reaction_loads(R_0, M_0)
467
+ assert simplify(b.slope()) == simplify((80*SingularityFunction(x, 0, 1) - 10*SingularityFunction(x, 0, 2)
468
+ + 10*SingularityFunction(x, 4, 2))/(E*I))
469
+ assert simplify(b.deflection()) == simplify((40*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 0, 3)/3
470
+ + 10*SingularityFunction(x, 4, 3)/3)/(E*I))
471
+
472
+ b = Beam(30, E, I)
473
+ b.apply_support(10, "pin")
474
+ b.apply_support(30, "roller")
475
+ b.apply_load(-8, 0, -1)
476
+ b.apply_load(120, 30, -2)
477
+ R_10, R_30 = symbols('R_10, R_30')
478
+ b.solve_for_reaction_loads(R_10, R_30)
479
+ assert b.slope() == (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
480
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3))/(E*I)
481
+ assert b.deflection() == (x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
482
+ + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
483
+
484
+ P = Symbol('P', positive=True)
485
+ L = Symbol('L', positive=True)
486
+ b = Beam(L, E, I)
487
+ b.apply_support(0, type='fixed')
488
+ b.apply_support(L, type='fixed')
489
+ b.apply_load(-P, L/2, -1)
490
+ R_0, R_L, M_0, M_L = symbols('R_0, R_L, M_0, M_L')
491
+ b.solve_for_reaction_loads(R_0, R_L, M_0, M_L)
492
+ assert b.reaction_loads == {R_0: P/2, R_L: P/2, M_0: -L*P/8, M_L: L*P/8}
493
+
494
+
495
+ def test_max_shear_force():
496
+ E = Symbol('E')
497
+ I = Symbol('I')
498
+
499
+ b = Beam(3, E, I)
500
+ R, M = symbols('R, M')
501
+ b.apply_load(R, 0, -1)
502
+ b.apply_load(M, 0, -2)
503
+ b.apply_load(2, 3, -1)
504
+ b.apply_load(4, 2, -1)
505
+ b.apply_load(2, 2, 0, end=3)
506
+ b.solve_for_reaction_loads(R, M)
507
+ assert b.max_shear_force() == (Interval(0, 2), 8)
508
+
509
+ l = symbols('l', positive=True)
510
+ P = Symbol('P')
511
+ b = Beam(l, E, I)
512
+ R1, R2 = symbols('R1, R2')
513
+ b.apply_load(R1, 0, -1)
514
+ b.apply_load(R2, l, -1)
515
+ b.apply_load(P, 0, 0, end=l)
516
+ b.solve_for_reaction_loads(R1, R2)
517
+ assert b.max_shear_force() == (0, l*Abs(P)/2)
518
+
519
+
520
+ def test_max_bmoment():
521
+ E = Symbol('E')
522
+ I = Symbol('I')
523
+ l, P = symbols('l, P', positive=True)
524
+
525
+ b = Beam(l, E, I)
526
+ R1, R2 = symbols('R1, R2')
527
+ b.apply_load(R1, 0, -1)
528
+ b.apply_load(R2, l, -1)
529
+ b.apply_load(P, l/2, -1)
530
+ b.solve_for_reaction_loads(R1, R2)
531
+ b.reaction_loads
532
+ assert b.max_bmoment() == (l/2, P*l/4)
533
+
534
+ b = Beam(l, E, I)
535
+ R1, R2 = symbols('R1, R2')
536
+ b.apply_load(R1, 0, -1)
537
+ b.apply_load(R2, l, -1)
538
+ b.apply_load(P, 0, 0, end=l)
539
+ b.solve_for_reaction_loads(R1, R2)
540
+ assert b.max_bmoment() == (l/2, P*l**2/8)
541
+
542
+
543
+ def test_max_deflection():
544
+ E, I, l, F = symbols('E, I, l, F', positive=True)
545
+ b = Beam(l, E, I)
546
+ b.bc_deflection = [(0, 0),(l, 0)]
547
+ b.bc_slope = [(0, 0),(l, 0)]
548
+ b.apply_load(F/2, 0, -1)
549
+ b.apply_load(-F*l/8, 0, -2)
550
+ b.apply_load(F/2, l, -1)
551
+ b.apply_load(F*l/8, l, -2)
552
+ b.apply_load(-F, l/2, -1)
553
+ assert b.max_deflection() == (l/2, F*l**3/(192*E*I))
554
+
555
+
556
+ def test_Beam3D():
557
+ l, E, G, I, A = symbols('l, E, G, I, A')
558
+ R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
559
+
560
+ b = Beam3D(l, E, G, I, A)
561
+ m, q = symbols('m, q')
562
+ b.apply_load(q, 0, 0, dir="y")
563
+ b.apply_moment_load(m, 0, 0, dir="z")
564
+ b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
565
+ b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
566
+ b.solve_slope_deflection()
567
+
568
+ assert b.polar_moment() == 2*I
569
+ assert b.shear_force() == [0, -q*x, 0]
570
+ assert b.shear_stress() == [0, -q*x/A, 0]
571
+ assert b.axial_stress() == 0
572
+ assert b.bending_moment() == [0, 0, -m*x + q*x**2/2]
573
+ expected_deflection = (x*(A*G*q*x**3/4 + A*G*x**2*(-l*(A*G*l*(l*q - 2*m) +
574
+ 12*E*I*q)/(A*G*l**2 + 12*E*I)/2 - m) + 3*E*I*l*(A*G*l*(l*q - 2*m) +
575
+ 12*E*I*q)/(A*G*l**2 + 12*E*I) + x*(-A*G*l**2*q/2 +
576
+ 3*A*G*l**2*(A*G*l*(l*q - 2*m) + 12*E*I*q)/(A*G*l**2 + 12*E*I)/4 +
577
+ A*G*l*m*Rational(3, 2) - 3*E*I*q))/(6*A*E*G*I))
578
+ dx, dy, dz = b.deflection()
579
+ assert dx == dz == 0
580
+ assert simplify(dy - expected_deflection) == 0
581
+
582
+ b2 = Beam3D(30, E, G, I, A, x)
583
+ b2.apply_load(50, start=0, order=0, dir="y")
584
+ b2.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
585
+ b2.apply_load(R1, start=0, order=-1, dir="y")
586
+ b2.apply_load(R2, start=30, order=-1, dir="y")
587
+ b2.solve_for_reaction_loads(R1, R2)
588
+ assert b2.reaction_loads == {R1: -750, R2: -750}
589
+
590
+ b2.solve_slope_deflection()
591
+ assert b2.slope() == [0, 0, 25*x**3/(3*E*I) - 375*x**2/(E*I) + 3750*x/(E*I)]
592
+ expected_deflection = 25*x**4/(12*E*I) - 125*x**3/(E*I) + 1875*x**2/(E*I) - \
593
+ 25*x**2/(A*G) + 750*x/(A*G)
594
+ dx, dy, dz = b2.deflection()
595
+ assert dx == dz == 0
596
+ assert dy == expected_deflection
597
+
598
+ # Test for solve_for_reaction_loads
599
+ b3 = Beam3D(30, E, G, I, A, x)
600
+ b3.apply_load(8, start=0, order=0, dir="y")
601
+ b3.apply_load(9*x, start=0, order=0, dir="z")
602
+ b3.apply_load(R1, start=0, order=-1, dir="y")
603
+ b3.apply_load(R2, start=30, order=-1, dir="y")
604
+ b3.apply_load(R3, start=0, order=-1, dir="z")
605
+ b3.apply_load(R4, start=30, order=-1, dir="z")
606
+ b3.solve_for_reaction_loads(R1, R2, R3, R4)
607
+ assert b3.reaction_loads == {R1: -120, R2: -120, R3: -1350, R4: -2700}
608
+
609
+
610
+ def test_polar_moment_Beam3D():
611
+ l, E, G, A, I1, I2 = symbols('l, E, G, A, I1, I2')
612
+ I = [I1, I2]
613
+
614
+ b = Beam3D(l, E, G, I, A)
615
+ assert b.polar_moment() == I1 + I2
616
+
617
+
618
+ def test_parabolic_loads():
619
+
620
+ E, I, L = symbols('E, I, L', positive=True, real=True)
621
+ R, M, P = symbols('R, M, P', real=True)
622
+
623
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
624
+ # length of beam
625
+ beam = Beam(L, E, I)
626
+
627
+ beam.bc_deflection.append((0, 0))
628
+ beam.bc_slope.append((0, 0))
629
+ beam.apply_load(R, 0, -1)
630
+ beam.apply_load(M, 0, -2)
631
+
632
+ # parabolic load
633
+ beam.apply_load(1, 0, 2)
634
+
635
+ beam.solve_for_reaction_loads(R, M)
636
+
637
+ assert beam.reaction_loads[R] == -L**3/3
638
+
639
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
640
+ # first half of beam
641
+ beam = Beam(2*L, E, I)
642
+
643
+ beam.bc_deflection.append((0, 0))
644
+ beam.bc_slope.append((0, 0))
645
+ beam.apply_load(R, 0, -1)
646
+ beam.apply_load(M, 0, -2)
647
+
648
+ # parabolic load from x=0 to x=L
649
+ beam.apply_load(1, 0, 2, end=L)
650
+
651
+ beam.solve_for_reaction_loads(R, M)
652
+
653
+ # result should be the same as the prior example
654
+ assert beam.reaction_loads[R] == -L**3/3
655
+
656
+ # check constant load
657
+ beam = Beam(2*L, E, I)
658
+ beam.apply_load(P, 0, 0, end=L)
659
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
660
+ assert loading.xreplace({x: 5}) == 40
661
+ assert loading.xreplace({x: 15}) == 0
662
+
663
+ # check ramp load
664
+ beam = Beam(2*L, E, I)
665
+ beam.apply_load(P, 0, 1, end=L)
666
+ assert beam.load == (P*SingularityFunction(x, 0, 1) -
667
+ P*SingularityFunction(x, L, 1) -
668
+ P*L*SingularityFunction(x, L, 0))
669
+
670
+ # check higher order load: x**8 load from x=0 to x=L
671
+ beam = Beam(2*L, E, I)
672
+ beam.apply_load(P, 0, 8, end=L)
673
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
674
+ assert loading.xreplace({x: 5}) == 40*5**8
675
+ assert loading.xreplace({x: 15}) == 0
676
+
677
+
678
+ def test_cross_section():
679
+ I = Symbol('I')
680
+ l = Symbol('l')
681
+ E = Symbol('E')
682
+ C3, C4 = symbols('C3, C4')
683
+ a, c, g, h, r, n = symbols('a, c, g, h, r, n')
684
+
685
+ # test for second_moment and cross_section setter
686
+ b0 = Beam(l, E, I)
687
+ assert b0.second_moment == I
688
+ assert b0.cross_section == None
689
+ b0.cross_section = Circle((0, 0), 5)
690
+ assert b0.second_moment == pi*Rational(625, 4)
691
+ assert b0.cross_section == Circle((0, 0), 5)
692
+ b0.second_moment = 2*n - 6
693
+ assert b0.second_moment == 2*n-6
694
+ assert b0.cross_section == None
695
+ with raises(ValueError):
696
+ b0.second_moment = Circle((0, 0), 5)
697
+
698
+ # beam with a circular cross-section
699
+ b1 = Beam(50, E, Circle((0, 0), r))
700
+ assert b1.cross_section == Circle((0, 0), r)
701
+ assert b1.second_moment == pi*r*Abs(r)**3/4
702
+
703
+ b1.apply_load(-10, 0, -1)
704
+ b1.apply_load(R1, 5, -1)
705
+ b1.apply_load(R2, 50, -1)
706
+ b1.apply_load(90, 45, -2)
707
+ b1.solve_for_reaction_loads(R1, R2)
708
+ assert b1.load == (-10*SingularityFunction(x, 0, -1) + 82*SingularityFunction(x, 5, -1)/S(9)
709
+ + 90*SingularityFunction(x, 45, -2) + 8*SingularityFunction(x, 50, -1)/9)
710
+ assert b1.bending_moment() == (10*SingularityFunction(x, 0, 1) - 82*SingularityFunction(x, 5, 1)/9
711
+ - 90*SingularityFunction(x, 45, 0) - 8*SingularityFunction(x, 50, 1)/9)
712
+ q = (-5*SingularityFunction(x, 0, 2) + 41*SingularityFunction(x, 5, 2)/S(9)
713
+ + 90*SingularityFunction(x, 45, 1) + 4*SingularityFunction(x, 50, 2)/S(9))/(pi*E*r*Abs(r)**3)
714
+ assert b1.slope() == C3 + 4*q
715
+ q = (-5*SingularityFunction(x, 0, 3)/3 + 41*SingularityFunction(x, 5, 3)/27 + 45*SingularityFunction(x, 45, 2)
716
+ + 4*SingularityFunction(x, 50, 3)/27)/(pi*E*r*Abs(r)**3)
717
+ assert b1.deflection() == C3*x + C4 + 4*q
718
+
719
+ # beam with a recatangular cross-section
720
+ b2 = Beam(20, E, Polygon((0, 0), (a, 0), (a, c), (0, c)))
721
+ assert b2.cross_section == Polygon((0, 0), (a, 0), (a, c), (0, c))
722
+ assert b2.second_moment == a*c**3/12
723
+ # beam with a triangular cross-section
724
+ b3 = Beam(15, E, Triangle((0, 0), (g, 0), (g/2, h)))
725
+ assert b3.cross_section == Triangle(Point2D(0, 0), Point2D(g, 0), Point2D(g/2, h))
726
+ assert b3.second_moment == g*h**3/36
727
+
728
+ # composite beam
729
+ b = b2.join(b3, "fixed")
730
+ b.apply_load(-30, 0, -1)
731
+ b.apply_load(65, 0, -2)
732
+ b.apply_load(40, 0, -1)
733
+ b.bc_slope = [(0, 0)]
734
+ b.bc_deflection = [(0, 0)]
735
+
736
+ assert b.second_moment == Piecewise((a*c**3/12, x <= 20), (g*h**3/36, x <= 35))
737
+ assert b.cross_section == None
738
+ assert b.length == 35
739
+ assert b.slope().subs(x, 7) == 8400/(E*a*c**3)
740
+ assert b.slope().subs(x, 25) == 52200/(E*g*h**3) + 39600/(E*a*c**3)
741
+ assert b.deflection().subs(x, 30) == -537000/(E*g*h**3) - 712000/(E*a*c**3)
742
+
743
+ def test_max_shear_force_Beam3D():
744
+ x = symbols('x')
745
+ b = Beam3D(20, 40, 21, 100, 25)
746
+ b.apply_load(15, start=0, order=0, dir="z")
747
+ b.apply_load(12*x, start=0, order=0, dir="y")
748
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
749
+ assert b.max_shear_force() == [(0, 0), (20, 2400), (20, 300)]
750
+
751
+ def test_max_bending_moment_Beam3D():
752
+ x = symbols('x')
753
+ b = Beam3D(20, 40, 21, 100, 25)
754
+ b.apply_load(15, start=0, order=0, dir="z")
755
+ b.apply_load(12*x, start=0, order=0, dir="y")
756
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
757
+ assert b.max_bmoment() == [(0, 0), (20, 3000), (20, 16000)]
758
+
759
+ def test_max_deflection_Beam3D():
760
+ x = symbols('x')
761
+ b = Beam3D(20, 40, 21, 100, 25)
762
+ b.apply_load(15, start=0, order=0, dir="z")
763
+ b.apply_load(12*x, start=0, order=0, dir="y")
764
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
765
+ b.solve_slope_deflection()
766
+ c = sympify("495/14")
767
+ p = sympify("-10 + 10*sqrt(10793)/43")
768
+ q = sympify("(10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560")
769
+ assert b.max_deflection() == [(0, 0), (10, c), (p, q)]
770
+
771
+ def test_torsion_Beam3D():
772
+ x = symbols('x')
773
+ b = Beam3D(20, 40, 21, 100, 25)
774
+ b.apply_moment_load(15, 5, -2, dir='x')
775
+ b.apply_moment_load(25, 10, -2, dir='x')
776
+ b.apply_moment_load(-5, 20, -2, dir='x')
777
+ b.solve_for_torsion()
778
+ assert b.angular_deflection().subs(x, 3) == sympify("1/40")
779
+ assert b.angular_deflection().subs(x, 9) == sympify("17/280")
780
+ assert b.angular_deflection().subs(x, 12) == sympify("53/840")
781
+ assert b.angular_deflection().subs(x, 17) == sympify("2/35")
782
+ assert b.angular_deflection().subs(x, 20) == sympify("3/56")
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import Symbol, symbols
2
+ from sympy.physics.continuum_mechanics.truss import Truss
3
+ from sympy import sqrt
4
+
5
+
6
+ def test_truss():
7
+ A = Symbol('A')
8
+ B = Symbol('B')
9
+ C = Symbol('C')
10
+ AB, BC, AC = symbols('AB, BC, AC')
11
+ P = Symbol('P')
12
+
13
+ t = Truss()
14
+ assert t.nodes == []
15
+ assert t.node_labels == []
16
+ assert t.node_positions == []
17
+ assert t.members == {}
18
+ assert t.loads == {}
19
+ assert t.supports == {}
20
+ assert t.reaction_loads == {}
21
+ assert t.internal_forces == {}
22
+
23
+ # testing the add_node method
24
+ t.add_node(A, 0, 0)
25
+ t.add_node(B, 2, 2)
26
+ t.add_node(C, 3, 0)
27
+ assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)]
28
+ assert t.node_labels == [A, B, C]
29
+ assert t.node_positions == [(0, 0), (2, 2), (3, 0)]
30
+ assert t.loads == {}
31
+ assert t.supports == {}
32
+ assert t.reaction_loads == {}
33
+
34
+ # testing the remove_node method
35
+ t.remove_node(C)
36
+ assert t.nodes == [(A, 0, 0), (B, 2, 2)]
37
+ assert t.node_labels == [A, B]
38
+ assert t.node_positions == [(0, 0), (2, 2)]
39
+ assert t.loads == {}
40
+ assert t.supports == {}
41
+
42
+ t.add_node(C, 3, 0)
43
+
44
+ # testing the add_member method
45
+ t.add_member(AB, A, B)
46
+ t.add_member(BC, B, C)
47
+ t.add_member(AC, A, C)
48
+ assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]}
49
+ assert t.internal_forces == {AB: 0, BC: 0, AC: 0}
50
+
51
+ # testing the remove_member method
52
+ t.remove_member(BC)
53
+ assert t.members == {AB: [A, B], AC: [A, C]}
54
+ assert t.internal_forces == {AB: 0, AC: 0}
55
+
56
+ t.add_member(BC, B, C)
57
+
58
+ D, CD = symbols('D, CD')
59
+
60
+ # testing the change_label methods
61
+ t.change_node_label(B, D)
62
+ assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)]
63
+ assert t.node_labels == [A, D, C]
64
+ assert t.loads == {}
65
+ assert t.supports == {}
66
+ assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]}
67
+
68
+ t.change_member_label(BC, CD)
69
+ assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]}
70
+ assert t.internal_forces == {AB: 0, CD: 0, AC: 0}
71
+
72
+
73
+ # testing the apply_load method
74
+ t.apply_load(A, P, 90)
75
+ t.apply_load(A, P/4, 90)
76
+ t.apply_load(A, 2*P,45)
77
+ t.apply_load(D, P/2, 90)
78
+ assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]}
79
+ assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]]
80
+
81
+ # testing the remove_load method
82
+ t.remove_load(A, P/4, 90)
83
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]}
84
+ assert t.loads[A] == [[P, 90], [2*P, 45]]
85
+
86
+ # testing the apply_support method
87
+ t.apply_support(A, "pinned")
88
+ t.apply_support(D, "roller")
89
+ assert t.supports == {A: 'pinned', D: 'roller'}
90
+ assert t.reaction_loads == {}
91
+ assert t.loads == {A: [[P, 90], [2*P, 45], [Symbol('R_A_x'), 0], [Symbol('R_A_y'), 90]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
92
+
93
+ # testing the remove_support method
94
+ t.remove_support(A)
95
+ assert t.supports == {D: 'roller'}
96
+ assert t.reaction_loads == {}
97
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
98
+
99
+ t.apply_support(A, "pinned")
100
+
101
+ # testing the solve method
102
+ t.solve()
103
+ assert t.reaction_loads['R_A_x'] == -sqrt(2)*P
104
+ assert t.reaction_loads['R_A_y'] == -sqrt(2)*P - P
105
+ assert t.reaction_loads['R_D_y'] == -P/2
106
+ assert t.internal_forces[AB]/P == 0
107
+ assert t.internal_forces[CD] == 0
108
+ assert t.internal_forces[AC] == 0
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel,
2
+ Feedback, MIMOFeedback, TransferFunctionMatrix, bilinear, backward_diff)
3
+ from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
4
+ step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
5
+ ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
6
+ bode_phase_plot, bode_plot)
7
+
8
+ __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel',
9
+ 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix','bilinear',
10
+ 'backward_diff', 'pole_zero_numerical_data',
11
+ 'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot',
12
+ 'impulse_response_numerical_data', 'impulse_response_plot',
13
+ 'ramp_response_numerical_data', 'ramp_response_plot',
14
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
15
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc ADDED
Binary file (30 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc ADDED
Binary file (118 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/control_plots.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I, pi
2
+ from sympy.functions.elementary.exponential import (exp, log)
3
+ from sympy.polys.partfrac import apart
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.external import import_module
6
+ from sympy.functions import arg, Abs
7
+ from sympy.integrals.laplace import _fast_inverse_laplace
8
+ from sympy.physics.control.lti import SISOLinearTimeInvariant
9
+ from sympy.plotting.plot import LineOver1DRangeSeries
10
+ from sympy.polys.polytools import Poly
11
+ from sympy.printing.latex import latex
12
+
13
+ __all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
14
+ 'step_response_numerical_data', 'step_response_plot',
15
+ 'impulse_response_numerical_data', 'impulse_response_plot',
16
+ 'ramp_response_numerical_data', 'ramp_response_plot',
17
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
18
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
19
+
20
+ matplotlib = import_module(
21
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
22
+ catch=(RuntimeError,))
23
+
24
+ numpy = import_module('numpy')
25
+
26
+ if matplotlib:
27
+ plt = matplotlib.pyplot
28
+
29
+ if numpy:
30
+ np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
31
+
32
+
33
+ def _check_system(system):
34
+ """Function to check whether the dynamical system passed for plots is
35
+ compatible or not."""
36
+ if not isinstance(system, SISOLinearTimeInvariant):
37
+ raise NotImplementedError("Only SISO LTI systems are currently supported.")
38
+ sys = system.to_expr()
39
+ len_free_symbols = len(sys.free_symbols)
40
+ if len_free_symbols > 1:
41
+ raise ValueError("Extra degree of freedom found. Make sure"
42
+ " that there are no free symbols in the dynamical system other"
43
+ " than the variable of Laplace transform.")
44
+ if sys.has(exp):
45
+ # Should test that exp is not part of a constant, in which case
46
+ # no exception is required, compare exp(s) with s*exp(1)
47
+ raise NotImplementedError("Time delay terms are not supported.")
48
+
49
+
50
+ def pole_zero_numerical_data(system):
51
+ """
52
+ Returns the numerical data of poles and zeros of the system.
53
+ It is internally used by ``pole_zero_plot`` to get the data
54
+ for plotting poles and zeros. Users can use this data to further
55
+ analyse the dynamics of the system or plot using a different
56
+ backend/plotting-module.
57
+
58
+ Parameters
59
+ ==========
60
+
61
+ system : SISOLinearTimeInvariant
62
+ The system for which the pole-zero data is to be computed.
63
+
64
+ Returns
65
+ =======
66
+
67
+ tuple : (zeros, poles)
68
+ zeros = Zeros of the system. NumPy array of complex numbers.
69
+ poles = Poles of the system. NumPy array of complex numbers.
70
+
71
+ Raises
72
+ ======
73
+
74
+ NotImplementedError
75
+ When a SISO LTI system is not passed.
76
+
77
+ When time delay terms are present in the system.
78
+
79
+ ValueError
80
+ When more than one free symbol is present in the system.
81
+ The only variable in the transfer function should be
82
+ the variable of the Laplace transform.
83
+
84
+ Examples
85
+ ========
86
+
87
+ >>> from sympy.abc import s
88
+ >>> from sympy.physics.control.lti import TransferFunction
89
+ >>> from sympy.physics.control.control_plots import pole_zero_numerical_data
90
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
91
+ >>> pole_zero_numerical_data(tf1) # doctest: +SKIP
92
+ ([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
93
+
94
+ See Also
95
+ ========
96
+
97
+ pole_zero_plot
98
+
99
+ """
100
+ _check_system(system)
101
+ system = system.doit() # Get the equivalent TransferFunction object.
102
+
103
+ num_poly = Poly(system.num, system.var).all_coeffs()
104
+ den_poly = Poly(system.den, system.var).all_coeffs()
105
+
106
+ num_poly = np.array(num_poly, dtype=np.complex128)
107
+ den_poly = np.array(den_poly, dtype=np.complex128)
108
+
109
+ zeros = np.roots(num_poly)
110
+ poles = np.roots(den_poly)
111
+
112
+ return zeros, poles
113
+
114
+
115
+ def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
116
+ zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
117
+ show=True, **kwargs):
118
+ r"""
119
+ Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
120
+
121
+ A Pole-Zero plot is a graphical representation of a system's poles and
122
+ zeros. It is plotted on a complex plane, with circular markers representing
123
+ the system's zeros and 'x' shaped markers representing the system's poles.
124
+
125
+ Parameters
126
+ ==========
127
+
128
+ system : SISOLinearTimeInvariant type systems
129
+ The system for which the pole-zero plot is to be computed.
130
+ pole_color : str, tuple, optional
131
+ The color of the pole points on the plot. Default color
132
+ is blue. The color can be provided as a matplotlib color string,
133
+ or a 3-tuple of floats each in the 0-1 range.
134
+ pole_markersize : Number, optional
135
+ The size of the markers used to mark the poles in the plot.
136
+ Default pole markersize is 10.
137
+ zero_color : str, tuple, optional
138
+ The color of the zero points on the plot. Default color
139
+ is orange. The color can be provided as a matplotlib color string,
140
+ or a 3-tuple of floats each in the 0-1 range.
141
+ zero_markersize : Number, optional
142
+ The size of the markers used to mark the zeros in the plot.
143
+ Default zero markersize is 7.
144
+ grid : boolean, optional
145
+ If ``True``, the plot will have a grid. Defaults to True.
146
+ show_axes : boolean, optional
147
+ If ``True``, the coordinate axes will be shown. Defaults to False.
148
+ show : boolean, optional
149
+ If ``True``, the plot will be displayed otherwise
150
+ the equivalent matplotlib ``plot`` object will be returned.
151
+ Defaults to True.
152
+
153
+ Examples
154
+ ========
155
+
156
+ .. plot::
157
+ :context: close-figs
158
+ :format: doctest
159
+ :include-source: True
160
+
161
+ >>> from sympy.abc import s
162
+ >>> from sympy.physics.control.lti import TransferFunction
163
+ >>> from sympy.physics.control.control_plots import pole_zero_plot
164
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
165
+ >>> pole_zero_plot(tf1) # doctest: +SKIP
166
+
167
+ See Also
168
+ ========
169
+
170
+ pole_zero_numerical_data
171
+
172
+ References
173
+ ==========
174
+
175
+ .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
176
+
177
+ """
178
+ zeros, poles = pole_zero_numerical_data(system)
179
+
180
+ zero_real = np.real(zeros)
181
+ zero_imag = np.imag(zeros)
182
+
183
+ pole_real = np.real(poles)
184
+ pole_imag = np.imag(poles)
185
+
186
+ plt.plot(pole_real, pole_imag, 'x', mfc='none',
187
+ markersize=pole_markersize, color=pole_color)
188
+ plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
189
+ color=zero_color)
190
+ plt.xlabel('Real Axis')
191
+ plt.ylabel('Imaginary Axis')
192
+ plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
193
+
194
+ if grid:
195
+ plt.grid()
196
+ if show_axes:
197
+ plt.axhline(0, color='black')
198
+ plt.axvline(0, color='black')
199
+ if show:
200
+ plt.show()
201
+ return
202
+
203
+ return plt
204
+
205
+
206
+ def step_response_numerical_data(system, prec=8, lower_limit=0,
207
+ upper_limit=10, **kwargs):
208
+ """
209
+ Returns the numerical values of the points in the step response plot
210
+ of a SISO continuous-time system. By default, adaptive sampling
211
+ is used. If the user wants to instead get an uniformly
212
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
213
+ and ``nb_of_points`` must be passed as additional kwargs.
214
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
215
+ for more details.
216
+
217
+ Parameters
218
+ ==========
219
+
220
+ system : SISOLinearTimeInvariant
221
+ The system for which the unit step response data is to be computed.
222
+ prec : int, optional
223
+ The decimal point precision for the point coordinate values.
224
+ Defaults to 8.
225
+ lower_limit : Number, optional
226
+ The lower limit of the plot range. Defaults to 0.
227
+ upper_limit : Number, optional
228
+ The upper limit of the plot range. Defaults to 10.
229
+ kwargs :
230
+ Additional keyword arguments are passed to the underlying
231
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
232
+
233
+ Returns
234
+ =======
235
+
236
+ tuple : (x, y)
237
+ x = Time-axis values of the points in the step response. NumPy array.
238
+ y = Amplitude-axis values of the points in the step response. NumPy array.
239
+
240
+ Raises
241
+ ======
242
+
243
+ NotImplementedError
244
+ When a SISO LTI system is not passed.
245
+
246
+ When time delay terms are present in the system.
247
+
248
+ ValueError
249
+ When more than one free symbol is present in the system.
250
+ The only variable in the transfer function should be
251
+ the variable of the Laplace transform.
252
+
253
+ When ``lower_limit`` parameter is less than 0.
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy.abc import s
259
+ >>> from sympy.physics.control.lti import TransferFunction
260
+ >>> from sympy.physics.control.control_plots import step_response_numerical_data
261
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
262
+ >>> step_response_numerical_data(tf1) # doctest: +SKIP
263
+ ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
264
+ [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
265
+
266
+ See Also
267
+ ========
268
+
269
+ step_response_plot
270
+
271
+ """
272
+ if lower_limit < 0:
273
+ raise ValueError("Lower limit of time must be greater "
274
+ "than or equal to zero.")
275
+ _check_system(system)
276
+ _x = Dummy("x")
277
+ expr = system.to_expr()/(system.var)
278
+ expr = apart(expr, system.var, full=True)
279
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
280
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
281
+ **kwargs).get_points()
282
+
283
+
284
+ def step_response_plot(system, color='b', prec=8, lower_limit=0,
285
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
286
+ r"""
287
+ Returns the unit step response of a continuous-time system. It is
288
+ the response of the system when the input signal is a step function.
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ system : SISOLinearTimeInvariant type
294
+ The LTI SISO system for which the Step Response is to be computed.
295
+ color : str, tuple, optional
296
+ The color of the line. Default is Blue.
297
+ show : boolean, optional
298
+ If ``True``, the plot will be displayed otherwise
299
+ the equivalent matplotlib ``plot`` object will be returned.
300
+ Defaults to True.
301
+ lower_limit : Number, optional
302
+ The lower limit of the plot range. Defaults to 0.
303
+ upper_limit : Number, optional
304
+ The upper limit of the plot range. Defaults to 10.
305
+ prec : int, optional
306
+ The decimal point precision for the point coordinate values.
307
+ Defaults to 8.
308
+ show_axes : boolean, optional
309
+ If ``True``, the coordinate axes will be shown. Defaults to False.
310
+ grid : boolean, optional
311
+ If ``True``, the plot will have a grid. Defaults to True.
312
+
313
+ Examples
314
+ ========
315
+
316
+ .. plot::
317
+ :context: close-figs
318
+ :format: doctest
319
+ :include-source: True
320
+
321
+ >>> from sympy.abc import s
322
+ >>> from sympy.physics.control.lti import TransferFunction
323
+ >>> from sympy.physics.control.control_plots import step_response_plot
324
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
325
+ >>> step_response_plot(tf1) # doctest: +SKIP
326
+
327
+ See Also
328
+ ========
329
+
330
+ impulse_response_plot, ramp_response_plot
331
+
332
+ References
333
+ ==========
334
+
335
+ .. [1] https://www.mathworks.com/help/control/ref/lti.step.html
336
+
337
+ """
338
+ x, y = step_response_numerical_data(system, prec=prec,
339
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
340
+ plt.plot(x, y, color=color)
341
+ plt.xlabel('Time (s)')
342
+ plt.ylabel('Amplitude')
343
+ plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
344
+
345
+ if grid:
346
+ plt.grid()
347
+ if show_axes:
348
+ plt.axhline(0, color='black')
349
+ plt.axvline(0, color='black')
350
+ if show:
351
+ plt.show()
352
+ return
353
+
354
+ return plt
355
+
356
+
357
+ def impulse_response_numerical_data(system, prec=8, lower_limit=0,
358
+ upper_limit=10, **kwargs):
359
+ """
360
+ Returns the numerical values of the points in the impulse response plot
361
+ of a SISO continuous-time system. By default, adaptive sampling
362
+ is used. If the user wants to instead get an uniformly
363
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
364
+ and ``nb_of_points`` must be passed as additional kwargs.
365
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
366
+ for more details.
367
+
368
+ Parameters
369
+ ==========
370
+
371
+ system : SISOLinearTimeInvariant
372
+ The system for which the impulse response data is to be computed.
373
+ prec : int, optional
374
+ The decimal point precision for the point coordinate values.
375
+ Defaults to 8.
376
+ lower_limit : Number, optional
377
+ The lower limit of the plot range. Defaults to 0.
378
+ upper_limit : Number, optional
379
+ The upper limit of the plot range. Defaults to 10.
380
+ kwargs :
381
+ Additional keyword arguments are passed to the underlying
382
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
383
+
384
+ Returns
385
+ =======
386
+
387
+ tuple : (x, y)
388
+ x = Time-axis values of the points in the impulse response. NumPy array.
389
+ y = Amplitude-axis values of the points in the impulse response. NumPy array.
390
+
391
+ Raises
392
+ ======
393
+
394
+ NotImplementedError
395
+ When a SISO LTI system is not passed.
396
+
397
+ When time delay terms are present in the system.
398
+
399
+ ValueError
400
+ When more than one free symbol is present in the system.
401
+ The only variable in the transfer function should be
402
+ the variable of the Laplace transform.
403
+
404
+ When ``lower_limit`` parameter is less than 0.
405
+
406
+ Examples
407
+ ========
408
+
409
+ >>> from sympy.abc import s
410
+ >>> from sympy.physics.control.lti import TransferFunction
411
+ >>> from sympy.physics.control.control_plots import impulse_response_numerical_data
412
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
413
+ >>> impulse_response_numerical_data(tf1) # doctest: +SKIP
414
+ ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
415
+ [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
416
+
417
+ See Also
418
+ ========
419
+
420
+ impulse_response_plot
421
+
422
+ """
423
+ if lower_limit < 0:
424
+ raise ValueError("Lower limit of time must be greater "
425
+ "than or equal to zero.")
426
+ _check_system(system)
427
+ _x = Dummy("x")
428
+ expr = system.to_expr()
429
+ expr = apart(expr, system.var, full=True)
430
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
431
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
432
+ **kwargs).get_points()
433
+
434
+
435
+ def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
436
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
437
+ r"""
438
+ Returns the unit impulse response (Input is the Dirac-Delta Function) of a
439
+ continuous-time system.
440
+
441
+ Parameters
442
+ ==========
443
+
444
+ system : SISOLinearTimeInvariant type
445
+ The LTI SISO system for which the Impulse Response is to be computed.
446
+ color : str, tuple, optional
447
+ The color of the line. Default is Blue.
448
+ show : boolean, optional
449
+ If ``True``, the plot will be displayed otherwise
450
+ the equivalent matplotlib ``plot`` object will be returned.
451
+ Defaults to True.
452
+ lower_limit : Number, optional
453
+ The lower limit of the plot range. Defaults to 0.
454
+ upper_limit : Number, optional
455
+ The upper limit of the plot range. Defaults to 10.
456
+ prec : int, optional
457
+ The decimal point precision for the point coordinate values.
458
+ Defaults to 8.
459
+ show_axes : boolean, optional
460
+ If ``True``, the coordinate axes will be shown. Defaults to False.
461
+ grid : boolean, optional
462
+ If ``True``, the plot will have a grid. Defaults to True.
463
+
464
+ Examples
465
+ ========
466
+
467
+ .. plot::
468
+ :context: close-figs
469
+ :format: doctest
470
+ :include-source: True
471
+
472
+ >>> from sympy.abc import s
473
+ >>> from sympy.physics.control.lti import TransferFunction
474
+ >>> from sympy.physics.control.control_plots import impulse_response_plot
475
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
476
+ >>> impulse_response_plot(tf1) # doctest: +SKIP
477
+
478
+ See Also
479
+ ========
480
+
481
+ step_response_plot, ramp_response_plot
482
+
483
+ References
484
+ ==========
485
+
486
+ .. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html
487
+
488
+ """
489
+ x, y = impulse_response_numerical_data(system, prec=prec,
490
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
491
+ plt.plot(x, y, color=color)
492
+ plt.xlabel('Time (s)')
493
+ plt.ylabel('Amplitude')
494
+ plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
495
+
496
+ if grid:
497
+ plt.grid()
498
+ if show_axes:
499
+ plt.axhline(0, color='black')
500
+ plt.axvline(0, color='black')
501
+ if show:
502
+ plt.show()
503
+ return
504
+
505
+ return plt
506
+
507
+
508
+ def ramp_response_numerical_data(system, slope=1, prec=8,
509
+ lower_limit=0, upper_limit=10, **kwargs):
510
+ """
511
+ Returns the numerical values of the points in the ramp response plot
512
+ of a SISO continuous-time system. By default, adaptive sampling
513
+ is used. If the user wants to instead get an uniformly
514
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
515
+ and ``nb_of_points`` must be passed as additional kwargs.
516
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
517
+ for more details.
518
+
519
+ Parameters
520
+ ==========
521
+
522
+ system : SISOLinearTimeInvariant
523
+ The system for which the ramp response data is to be computed.
524
+ slope : Number, optional
525
+ The slope of the input ramp function. Defaults to 1.
526
+ prec : int, optional
527
+ The decimal point precision for the point coordinate values.
528
+ Defaults to 8.
529
+ lower_limit : Number, optional
530
+ The lower limit of the plot range. Defaults to 0.
531
+ upper_limit : Number, optional
532
+ The upper limit of the plot range. Defaults to 10.
533
+ kwargs :
534
+ Additional keyword arguments are passed to the underlying
535
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
536
+
537
+ Returns
538
+ =======
539
+
540
+ tuple : (x, y)
541
+ x = Time-axis values of the points in the ramp response plot. NumPy array.
542
+ y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
543
+
544
+ Raises
545
+ ======
546
+
547
+ NotImplementedError
548
+ When a SISO LTI system is not passed.
549
+
550
+ When time delay terms are present in the system.
551
+
552
+ ValueError
553
+ When more than one free symbol is present in the system.
554
+ The only variable in the transfer function should be
555
+ the variable of the Laplace transform.
556
+
557
+ When ``lower_limit`` parameter is less than 0.
558
+
559
+ When ``slope`` is negative.
560
+
561
+ Examples
562
+ ========
563
+
564
+ >>> from sympy.abc import s
565
+ >>> from sympy.physics.control.lti import TransferFunction
566
+ >>> from sympy.physics.control.control_plots import ramp_response_numerical_data
567
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
568
+ >>> ramp_response_numerical_data(tf1) # doctest: +SKIP
569
+ (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
570
+ [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
571
+
572
+ See Also
573
+ ========
574
+
575
+ ramp_response_plot
576
+
577
+ """
578
+ if slope < 0:
579
+ raise ValueError("Slope must be greater than or equal"
580
+ " to zero.")
581
+ if lower_limit < 0:
582
+ raise ValueError("Lower limit of time must be greater "
583
+ "than or equal to zero.")
584
+ _check_system(system)
585
+ _x = Dummy("x")
586
+ expr = (slope*system.to_expr())/((system.var)**2)
587
+ expr = apart(expr, system.var, full=True)
588
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
589
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
590
+ **kwargs).get_points()
591
+
592
+
593
+ def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
594
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
595
+ r"""
596
+ Returns the ramp response of a continuous-time system.
597
+
598
+ Ramp function is defined as the straight line
599
+ passing through origin ($f(x) = mx$). The slope of
600
+ the ramp function can be varied by the user and
601
+ the default value is 1.
602
+
603
+ Parameters
604
+ ==========
605
+
606
+ system : SISOLinearTimeInvariant type
607
+ The LTI SISO system for which the Ramp Response is to be computed.
608
+ slope : Number, optional
609
+ The slope of the input ramp function. Defaults to 1.
610
+ color : str, tuple, optional
611
+ The color of the line. Default is Blue.
612
+ show : boolean, optional
613
+ If ``True``, the plot will be displayed otherwise
614
+ the equivalent matplotlib ``plot`` object will be returned.
615
+ Defaults to True.
616
+ lower_limit : Number, optional
617
+ The lower limit of the plot range. Defaults to 0.
618
+ upper_limit : Number, optional
619
+ The upper limit of the plot range. Defaults to 10.
620
+ prec : int, optional
621
+ The decimal point precision for the point coordinate values.
622
+ Defaults to 8.
623
+ show_axes : boolean, optional
624
+ If ``True``, the coordinate axes will be shown. Defaults to False.
625
+ grid : boolean, optional
626
+ If ``True``, the plot will have a grid. Defaults to True.
627
+
628
+ Examples
629
+ ========
630
+
631
+ .. plot::
632
+ :context: close-figs
633
+ :format: doctest
634
+ :include-source: True
635
+
636
+ >>> from sympy.abc import s
637
+ >>> from sympy.physics.control.lti import TransferFunction
638
+ >>> from sympy.physics.control.control_plots import ramp_response_plot
639
+ >>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
640
+ >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
641
+
642
+ See Also
643
+ ========
644
+
645
+ step_response_plot, ramp_response_plot
646
+
647
+ References
648
+ ==========
649
+
650
+ .. [1] https://en.wikipedia.org/wiki/Ramp_function
651
+
652
+ """
653
+ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
654
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
655
+ plt.plot(x, y, color=color)
656
+ plt.xlabel('Time (s)')
657
+ plt.ylabel('Amplitude')
658
+ plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
659
+
660
+ if grid:
661
+ plt.grid()
662
+ if show_axes:
663
+ plt.axhline(0, color='black')
664
+ plt.axvline(0, color='black')
665
+ if show:
666
+ plt.show()
667
+ return
668
+
669
+ return plt
670
+
671
+
672
+ def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
673
+ """
674
+ Returns the numerical data of the Bode magnitude plot of the system.
675
+ It is internally used by ``bode_magnitude_plot`` to get the data
676
+ for plotting Bode magnitude plot. Users can use this data to further
677
+ analyse the dynamics of the system or plot using a different
678
+ backend/plotting-module.
679
+
680
+ Parameters
681
+ ==========
682
+
683
+ system : SISOLinearTimeInvariant
684
+ The system for which the data is to be computed.
685
+ initial_exp : Number, optional
686
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
687
+ final_exp : Number, optional
688
+ The final exponent of 10 of the semilog plot. Defaults to 5.
689
+ freq_unit : string, optional
690
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
691
+
692
+ Returns
693
+ =======
694
+
695
+ tuple : (x, y)
696
+ x = x-axis values of the Bode magnitude plot.
697
+ y = y-axis values of the Bode magnitude plot.
698
+
699
+ Raises
700
+ ======
701
+
702
+ NotImplementedError
703
+ When a SISO LTI system is not passed.
704
+
705
+ When time delay terms are present in the system.
706
+
707
+ ValueError
708
+ When more than one free symbol is present in the system.
709
+ The only variable in the transfer function should be
710
+ the variable of the Laplace transform.
711
+
712
+ When incorrect frequency units are given as input.
713
+
714
+ Examples
715
+ ========
716
+
717
+ >>> from sympy.abc import s
718
+ >>> from sympy.physics.control.lti import TransferFunction
719
+ >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
720
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
721
+ >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
722
+ ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
723
+ [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
724
+
725
+ See Also
726
+ ========
727
+
728
+ bode_magnitude_plot, bode_phase_numerical_data
729
+
730
+ """
731
+ _check_system(system)
732
+ expr = system.to_expr()
733
+ freq_units = ('rad/sec', 'Hz')
734
+ if freq_unit not in freq_units:
735
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
736
+
737
+ _w = Dummy("w", real=True)
738
+ if freq_unit == 'Hz':
739
+ repl = I*_w*2*pi
740
+ else:
741
+ repl = I*_w
742
+ w_expr = expr.subs({system.var: repl})
743
+
744
+ mag = 20*log(Abs(w_expr), 10)
745
+
746
+ x, y = LineOver1DRangeSeries(mag,
747
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
748
+
749
+ return x, y
750
+
751
+
752
+ def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
753
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
754
+ r"""
755
+ Returns the Bode magnitude plot of a continuous-time system.
756
+
757
+ See ``bode_plot`` for all the parameters.
758
+ """
759
+ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
760
+ final_exp=final_exp, freq_unit=freq_unit)
761
+ plt.plot(x, y, color=color, **kwargs)
762
+ plt.xscale('log')
763
+
764
+
765
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
766
+ plt.ylabel('Magnitude (dB)')
767
+ plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
768
+
769
+ if grid:
770
+ plt.grid(True)
771
+ if show_axes:
772
+ plt.axhline(0, color='black')
773
+ plt.axvline(0, color='black')
774
+ if show:
775
+ plt.show()
776
+ return
777
+
778
+ return plt
779
+
780
+
781
+ def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', **kwargs):
782
+ """
783
+ Returns the numerical data of the Bode phase plot of the system.
784
+ It is internally used by ``bode_phase_plot`` to get the data
785
+ for plotting Bode phase plot. Users can use this data to further
786
+ analyse the dynamics of the system or plot using a different
787
+ backend/plotting-module.
788
+
789
+ Parameters
790
+ ==========
791
+
792
+ system : SISOLinearTimeInvariant
793
+ The system for which the Bode phase plot data is to be computed.
794
+ initial_exp : Number, optional
795
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
796
+ final_exp : Number, optional
797
+ The final exponent of 10 of the semilog plot. Defaults to 5.
798
+ freq_unit : string, optional
799
+ User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
800
+ phase_unit : string, optional
801
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
802
+
803
+ Returns
804
+ =======
805
+
806
+ tuple : (x, y)
807
+ x = x-axis values of the Bode phase plot.
808
+ y = y-axis values of the Bode phase plot.
809
+
810
+ Raises
811
+ ======
812
+
813
+ NotImplementedError
814
+ When a SISO LTI system is not passed.
815
+
816
+ When time delay terms are present in the system.
817
+
818
+ ValueError
819
+ When more than one free symbol is present in the system.
820
+ The only variable in the transfer function should be
821
+ the variable of the Laplace transform.
822
+
823
+ When incorrect frequency or phase units are given as input.
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy.abc import s
829
+ >>> from sympy.physics.control.lti import TransferFunction
830
+ >>> from sympy.physics.control.control_plots import bode_phase_numerical_data
831
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
832
+ >>> bode_phase_numerical_data(tf1) # doctest: +SKIP
833
+ ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
834
+ [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
835
+
836
+ See Also
837
+ ========
838
+
839
+ bode_magnitude_plot, bode_phase_numerical_data
840
+
841
+ """
842
+ _check_system(system)
843
+ expr = system.to_expr()
844
+ freq_units = ('rad/sec', 'Hz')
845
+ phase_units = ('rad', 'deg')
846
+ if freq_unit not in freq_units:
847
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
848
+ if phase_unit not in phase_units:
849
+ raise ValueError('Only "rad" and "deg" are accepted phase units.')
850
+
851
+ _w = Dummy("w", real=True)
852
+ if freq_unit == 'Hz':
853
+ repl = I*_w*2*pi
854
+ else:
855
+ repl = I*_w
856
+ w_expr = expr.subs({system.var: repl})
857
+
858
+ if phase_unit == 'deg':
859
+ phase = arg(w_expr)*180/pi
860
+ else:
861
+ phase = arg(w_expr)
862
+
863
+ x, y = LineOver1DRangeSeries(phase,
864
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
865
+
866
+ return x, y
867
+
868
+
869
+ def bode_phase_plot(system, initial_exp=-5, final_exp=5,
870
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
871
+ r"""
872
+ Returns the Bode phase plot of a continuous-time system.
873
+
874
+ See ``bode_plot`` for all the parameters.
875
+ """
876
+ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
877
+ final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit)
878
+ plt.plot(x, y, color=color, **kwargs)
879
+ plt.xscale('log')
880
+
881
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
882
+ plt.ylabel('Phase (%s)' % phase_unit)
883
+ plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
884
+
885
+ if grid:
886
+ plt.grid(True)
887
+ if show_axes:
888
+ plt.axhline(0, color='black')
889
+ plt.axvline(0, color='black')
890
+ if show:
891
+ plt.show()
892
+ return
893
+
894
+ return plt
895
+
896
+
897
+ def bode_plot(system, initial_exp=-5, final_exp=5,
898
+ grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
899
+ r"""
900
+ Returns the Bode phase and magnitude plots of a continuous-time system.
901
+
902
+ Parameters
903
+ ==========
904
+
905
+ system : SISOLinearTimeInvariant type
906
+ The LTI SISO system for which the Bode Plot is to be computed.
907
+ initial_exp : Number, optional
908
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
909
+ final_exp : Number, optional
910
+ The final exponent of 10 of the semilog plot. Defaults to 5.
911
+ show : boolean, optional
912
+ If ``True``, the plot will be displayed otherwise
913
+ the equivalent matplotlib ``plot`` object will be returned.
914
+ Defaults to True.
915
+ prec : int, optional
916
+ The decimal point precision for the point coordinate values.
917
+ Defaults to 8.
918
+ grid : boolean, optional
919
+ If ``True``, the plot will have a grid. Defaults to True.
920
+ show_axes : boolean, optional
921
+ If ``True``, the coordinate axes will be shown. Defaults to False.
922
+ freq_unit : string, optional
923
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
924
+ phase_unit : string, optional
925
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
926
+
927
+ Examples
928
+ ========
929
+
930
+ .. plot::
931
+ :context: close-figs
932
+ :format: doctest
933
+ :include-source: True
934
+
935
+ >>> from sympy.abc import s
936
+ >>> from sympy.physics.control.lti import TransferFunction
937
+ >>> from sympy.physics.control.control_plots import bode_plot
938
+ >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
939
+ >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
940
+
941
+ See Also
942
+ ========
943
+
944
+ bode_magnitude_plot, bode_phase_plot
945
+
946
+ """
947
+ plt.subplot(211)
948
+ mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
949
+ show=False, grid=grid, show_axes=show_axes,
950
+ freq_unit=freq_unit, **kwargs)
951
+ mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
952
+ mag.xlabel(None)
953
+ plt.subplot(212)
954
+ bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
955
+ show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, **kwargs).title(None)
956
+
957
+ if show:
958
+ plt.show()
959
+ return
960
+
961
+ return plt
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/lti.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (182 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to handle gamma matrices expressed as tensor objects.
3
+
4
+ Examples
5
+ ========
6
+
7
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
8
+ >>> from sympy.tensor.tensor import tensor_indices
9
+ >>> i = tensor_indices('i', LorentzIndex)
10
+ >>> G(i)
11
+ GammaMatrix(i)
12
+
13
+ Note that there is already an instance of GammaMatrixHead in four dimensions:
14
+ GammaMatrix, which is simply declare as
15
+
16
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix
17
+ >>> from sympy.tensor.tensor import tensor_indices
18
+ >>> i = tensor_indices('i', LorentzIndex)
19
+ >>> GammaMatrix(i)
20
+ GammaMatrix(i)
21
+
22
+ To access the metric tensor
23
+
24
+ >>> LorentzIndex.metric
25
+ metric(LorentzIndex,LorentzIndex)
26
+
27
+ """
28
+ from sympy.core.mul import Mul
29
+ from sympy.core.singleton import S
30
+ from sympy.matrices.dense import eye
31
+ from sympy.matrices.expressions.trace import trace
32
+ from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
33
+ TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
34
+
35
+
36
+ # DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
37
+
38
+
39
+ LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
40
+
41
+
42
+ GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
43
+ TensorSymmetry.no_symmetry(1), comm=None)
44
+
45
+
46
+ def extract_type_tens(expression, component):
47
+ """
48
+ Extract from a ``TensExpr`` all tensors with `component`.
49
+
50
+ Returns two tensor expressions:
51
+
52
+ * the first contains all ``Tensor`` of having `component`.
53
+ * the second contains all remaining.
54
+
55
+
56
+ """
57
+ if isinstance(expression, Tensor):
58
+ sp = [expression]
59
+ elif isinstance(expression, TensMul):
60
+ sp = expression.args
61
+ else:
62
+ raise ValueError('wrong type')
63
+
64
+ # Collect all gamma matrices of the same dimension
65
+ new_expr = S.One
66
+ residual_expr = S.One
67
+ for i in sp:
68
+ if isinstance(i, Tensor) and i.component == component:
69
+ new_expr *= i
70
+ else:
71
+ residual_expr *= i
72
+ return new_expr, residual_expr
73
+
74
+
75
+ def simplify_gamma_expression(expression):
76
+ extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
77
+ res_expr = _simplify_single_line(extracted_expr)
78
+ return res_expr * residual_expr
79
+
80
+
81
+ def simplify_gpgp(ex, sort=True):
82
+ """
83
+ simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
89
+ LorentzIndex, simplify_gpgp
90
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
91
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
92
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
93
+ >>> ps = p(i0)*G(-i0)
94
+ >>> qs = q(i0)*G(-i0)
95
+ >>> simplify_gpgp(ps*qs*qs)
96
+ GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
97
+ """
98
+ def _simplify_gpgp(ex):
99
+ components = ex.components
100
+ a = []
101
+ comp_map = []
102
+ for i, comp in enumerate(components):
103
+ comp_map.extend([i]*comp.rank)
104
+ dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
105
+ for i in range(len(components)):
106
+ if components[i] != GammaMatrix:
107
+ continue
108
+ for dx in dum:
109
+ if dx[2] == i:
110
+ p_pos1 = dx[3]
111
+ elif dx[3] == i:
112
+ p_pos1 = dx[2]
113
+ else:
114
+ continue
115
+ comp1 = components[p_pos1]
116
+ if comp1.comm == 0 and comp1.rank == 1:
117
+ a.append((i, p_pos1))
118
+ if not a:
119
+ return ex
120
+ elim = set()
121
+ tv = []
122
+ hit = True
123
+ coeff = S.One
124
+ ta = None
125
+ while hit:
126
+ hit = False
127
+ for i, ai in enumerate(a[:-1]):
128
+ if ai[0] in elim:
129
+ continue
130
+ if ai[0] != a[i + 1][0] - 1:
131
+ continue
132
+ if components[ai[1]] != components[a[i + 1][1]]:
133
+ continue
134
+ elim.add(ai[0])
135
+ elim.add(ai[1])
136
+ elim.add(a[i + 1][0])
137
+ elim.add(a[i + 1][1])
138
+ if not ta:
139
+ ta = ex.split()
140
+ mu = TensorIndex('mu', LorentzIndex)
141
+ hit = True
142
+ if i == 0:
143
+ coeff = ex.coeff
144
+ tx = components[ai[1]](mu)*components[ai[1]](-mu)
145
+ if len(a) == 2:
146
+ tx *= 4 # eye(4)
147
+ tv.append(tx)
148
+ break
149
+
150
+ if tv:
151
+ a = [x for j, x in enumerate(ta) if j not in elim]
152
+ a.extend(tv)
153
+ t = tensor_mul(*a)*coeff
154
+ # t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
155
+ return t
156
+ else:
157
+ return ex
158
+
159
+ if sort:
160
+ ex = ex.sorted_components()
161
+ # this would be better off with pattern matching
162
+ while 1:
163
+ t = _simplify_gpgp(ex)
164
+ if t != ex:
165
+ ex = t
166
+ else:
167
+ return t
168
+
169
+
170
+ def gamma_trace(t):
171
+ """
172
+ trace of a single line of gamma matrices
173
+
174
+ Examples
175
+ ========
176
+
177
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
178
+ gamma_trace, LorentzIndex
179
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
180
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
181
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
182
+ >>> ps = p(i0)*G(-i0)
183
+ >>> qs = q(i0)*G(-i0)
184
+ >>> gamma_trace(G(i0)*G(i1))
185
+ 4*metric(i0, i1)
186
+ >>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
187
+ 0
188
+ >>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
189
+ 0
190
+
191
+ """
192
+ if isinstance(t, TensAdd):
193
+ res = TensAdd(*[gamma_trace(x) for x in t.args])
194
+ return res
195
+ t = _simplify_single_line(t)
196
+ res = _trace_single_line(t)
197
+ return res
198
+
199
+
200
+ def _simplify_single_line(expression):
201
+ """
202
+ Simplify single-line product of gamma matrices.
203
+
204
+ Examples
205
+ ========
206
+
207
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
208
+ LorentzIndex, _simplify_single_line
209
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
210
+ >>> p = TensorHead('p', [LorentzIndex])
211
+ >>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
212
+ >>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
213
+ 0
214
+
215
+ """
216
+ t1, t2 = extract_type_tens(expression, GammaMatrix)
217
+ if t1 != 1:
218
+ t1 = kahane_simplify(t1)
219
+ res = t1*t2
220
+ return res
221
+
222
+
223
+ def _trace_single_line(t):
224
+ """
225
+ Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
226
+
227
+ Notes
228
+ =====
229
+
230
+ If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
231
+ indices trace over them; otherwise traces are not implied (explain)
232
+
233
+
234
+ Examples
235
+ ========
236
+
237
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
238
+ LorentzIndex, _trace_single_line
239
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
240
+ >>> p = TensorHead('p', [LorentzIndex])
241
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
242
+ >>> _trace_single_line(G(i0)*G(i1))
243
+ 4*metric(i0, i1)
244
+ >>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
245
+ 0
246
+
247
+ """
248
+ def _trace_single_line1(t):
249
+ t = t.sorted_components()
250
+ components = t.components
251
+ ncomps = len(components)
252
+ g = LorentzIndex.metric
253
+ # gamma matirices are in a[i:j]
254
+ hit = 0
255
+ for i in range(ncomps):
256
+ if components[i] == GammaMatrix:
257
+ hit = 1
258
+ break
259
+
260
+ for j in range(i + hit, ncomps):
261
+ if components[j] != GammaMatrix:
262
+ break
263
+ else:
264
+ j = ncomps
265
+ numG = j - i
266
+ if numG == 0:
267
+ tcoeff = t.coeff
268
+ return t.nocoeff if tcoeff else t
269
+ if numG % 2 == 1:
270
+ return TensMul.from_data(S.Zero, [], [], [])
271
+ elif numG > 4:
272
+ # find the open matrix indices and connect them:
273
+ a = t.split()
274
+ ind1 = a[i].get_indices()[0]
275
+ ind2 = a[i + 1].get_indices()[0]
276
+ aa = a[:i] + a[i + 2:]
277
+ t1 = tensor_mul(*aa)*g(ind1, ind2)
278
+ t1 = t1.contract_metric(g)
279
+ args = [t1]
280
+ sign = 1
281
+ for k in range(i + 2, j):
282
+ sign = -sign
283
+ ind2 = a[k].get_indices()[0]
284
+ aa = a[:i] + a[i + 1:k] + a[k + 1:]
285
+ t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
286
+ t2 = t2.contract_metric(g)
287
+ t2 = simplify_gpgp(t2, False)
288
+ args.append(t2)
289
+ t3 = TensAdd(*args)
290
+ t3 = _trace_single_line(t3)
291
+ return t3
292
+ else:
293
+ a = t.split()
294
+ t1 = _gamma_trace1(*a[i:j])
295
+ a2 = a[:i] + a[j:]
296
+ t2 = tensor_mul(*a2)
297
+ t3 = t1*t2
298
+ if not t3:
299
+ return t3
300
+ t3 = t3.contract_metric(g)
301
+ return t3
302
+
303
+ t = t.expand()
304
+ if isinstance(t, TensAdd):
305
+ a = [_trace_single_line1(x)*x.coeff for x in t.args]
306
+ return TensAdd(*a)
307
+ elif isinstance(t, (Tensor, TensMul)):
308
+ r = t.coeff*_trace_single_line1(t)
309
+ return r
310
+ else:
311
+ return trace(t)
312
+
313
+
314
+ def _gamma_trace1(*a):
315
+ gctr = 4 # FIXME specific for d=4
316
+ g = LorentzIndex.metric
317
+ if not a:
318
+ return gctr
319
+ n = len(a)
320
+ if n%2 == 1:
321
+ #return TensMul.from_data(S.Zero, [], [], [])
322
+ return S.Zero
323
+ if n == 2:
324
+ ind0 = a[0].get_indices()[0]
325
+ ind1 = a[1].get_indices()[0]
326
+ return gctr*g(ind0, ind1)
327
+ if n == 4:
328
+ ind0 = a[0].get_indices()[0]
329
+ ind1 = a[1].get_indices()[0]
330
+ ind2 = a[2].get_indices()[0]
331
+ ind3 = a[3].get_indices()[0]
332
+
333
+ return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
334
+ g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
335
+
336
+
337
+ def kahane_simplify(expression):
338
+ r"""
339
+ This function cancels contracted elements in a product of four
340
+ dimensional gamma matrices, resulting in an expression equal to the given
341
+ one, without the contracted gamma matrices.
342
+
343
+ Parameters
344
+ ==========
345
+
346
+ `expression` the tensor expression containing the gamma matrices to simplify.
347
+
348
+ Notes
349
+ =====
350
+
351
+ If spinor indices are given, the matrices must be given in
352
+ the order given in the product.
353
+
354
+ Algorithm
355
+ =========
356
+
357
+ The idea behind the algorithm is to use some well-known identities,
358
+ i.e., for contractions enclosing an even number of `\gamma` matrices
359
+
360
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
361
+
362
+ for an odd number of `\gamma` matrices
363
+
364
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
365
+
366
+ Instead of repeatedly applying these identities to cancel out all contracted indices,
367
+ it is possible to recognize the links that would result from such an operation,
368
+ the problem is thus reduced to a simple rearrangement of free gamma matrices.
369
+
370
+ Examples
371
+ ========
372
+
373
+ When using, always remember that the original expression coefficient
374
+ has to be handled separately
375
+
376
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
377
+ >>> from sympy.physics.hep.gamma_matrices import kahane_simplify
378
+ >>> from sympy.tensor.tensor import tensor_indices
379
+ >>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
380
+ >>> ta = G(i0)*G(-i0)
381
+ >>> kahane_simplify(ta)
382
+ Matrix([
383
+ [4, 0, 0, 0],
384
+ [0, 4, 0, 0],
385
+ [0, 0, 4, 0],
386
+ [0, 0, 0, 4]])
387
+ >>> tb = G(i0)*G(i1)*G(-i0)
388
+ >>> kahane_simplify(tb)
389
+ -2*GammaMatrix(i1)
390
+ >>> t = G(i0)*G(-i0)
391
+ >>> kahane_simplify(t)
392
+ Matrix([
393
+ [4, 0, 0, 0],
394
+ [0, 4, 0, 0],
395
+ [0, 0, 4, 0],
396
+ [0, 0, 0, 4]])
397
+ >>> t = G(i0)*G(-i0)
398
+ >>> kahane_simplify(t)
399
+ Matrix([
400
+ [4, 0, 0, 0],
401
+ [0, 4, 0, 0],
402
+ [0, 0, 4, 0],
403
+ [0, 0, 0, 4]])
404
+
405
+ If there are no contractions, the same expression is returned
406
+
407
+ >>> tc = G(i0)*G(i1)
408
+ >>> kahane_simplify(tc)
409
+ GammaMatrix(i0)*GammaMatrix(i1)
410
+
411
+ References
412
+ ==========
413
+
414
+ [1] Algorithm for Reducing Contracted Products of gamma Matrices,
415
+ Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
416
+ """
417
+
418
+ if isinstance(expression, Mul):
419
+ return expression
420
+ if isinstance(expression, TensAdd):
421
+ return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
422
+
423
+ if isinstance(expression, Tensor):
424
+ return expression
425
+
426
+ assert isinstance(expression, TensMul)
427
+
428
+ gammas = expression.args
429
+
430
+ for gamma in gammas:
431
+ assert gamma.component == GammaMatrix
432
+
433
+ free = expression.free
434
+ # spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
435
+
436
+ # if len(spinor_free) == 2:
437
+ # spinor_free.sort(key=lambda x: x[2])
438
+ # assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
439
+ # assert spinor_free[0][2] == 0
440
+ # elif spinor_free:
441
+ # raise ValueError('spinor indices do not match')
442
+
443
+ dum = []
444
+ for dum_pair in expression.dum:
445
+ if expression.index_types[dum_pair[0]] == LorentzIndex:
446
+ dum.append((dum_pair[0], dum_pair[1]))
447
+
448
+ dum = sorted(dum)
449
+
450
+ if len(dum) == 0: # or GammaMatrixHead:
451
+ # no contractions in `expression`, just return it.
452
+ return expression
453
+
454
+ # find the `first_dum_pos`, i.e. the position of the first contracted
455
+ # gamma matrix, Kahane's algorithm as described in his paper requires the
456
+ # gamma matrix expression to start with a contracted gamma matrix, this is
457
+ # a workaround which ignores possible initial free indices, and re-adds
458
+ # them later.
459
+
460
+ first_dum_pos = min(map(min, dum))
461
+
462
+ # for p1, p2, a1, a2 in expression.dum_in_args:
463
+ # if p1 != 0 or p2 != 0:
464
+ # # only Lorentz indices, skip Dirac indices:
465
+ # continue
466
+ # first_dum_pos = min(p1, p2)
467
+ # break
468
+
469
+ total_number = len(free) + len(dum)*2
470
+ number_of_contractions = len(dum)
471
+
472
+ free_pos = [None]*total_number
473
+ for i in free:
474
+ free_pos[i[1]] = i[0]
475
+
476
+ # `index_is_free` is a list of booleans, to identify index position
477
+ # and whether that index is free or dummy.
478
+ index_is_free = [False]*total_number
479
+
480
+ for i, indx in enumerate(free):
481
+ index_is_free[indx[1]] = True
482
+
483
+ # `links` is a dictionary containing the graph described in Kahane's paper,
484
+ # to every key correspond one or two values, representing the linked indices.
485
+ # All values in `links` are integers, negative numbers are used in the case
486
+ # where it is necessary to insert gamma matrices between free indices, in
487
+ # order to make Kahane's algorithm work (see paper).
488
+ links = {i: [] for i in range(first_dum_pos, total_number)}
489
+
490
+ # `cum_sign` is a step variable to mark the sign of every index, see paper.
491
+ cum_sign = -1
492
+ # `cum_sign_list` keeps storage for all `cum_sign` (every index).
493
+ cum_sign_list = [None]*total_number
494
+ block_free_count = 0
495
+
496
+ # multiply `resulting_coeff` by the coefficient parameter, the rest
497
+ # of the algorithm ignores a scalar coefficient.
498
+ resulting_coeff = S.One
499
+
500
+ # initialize a list of lists of indices. The outer list will contain all
501
+ # additive tensor expressions, while the inner list will contain the
502
+ # free indices (rearranged according to the algorithm).
503
+ resulting_indices = [[]]
504
+
505
+ # start to count the `connected_components`, which together with the number
506
+ # of contractions, determines a -1 or +1 factor to be multiplied.
507
+ connected_components = 1
508
+
509
+ # First loop: here we fill `cum_sign_list`, and draw the links
510
+ # among consecutive indices (they are stored in `links`). Links among
511
+ # non-consecutive indices will be drawn later.
512
+ for i, is_free in enumerate(index_is_free):
513
+ # if `expression` starts with free indices, they are ignored here;
514
+ # they are later added as they are to the beginning of all
515
+ # `resulting_indices` list of lists of indices.
516
+ if i < first_dum_pos:
517
+ continue
518
+
519
+ if is_free:
520
+ block_free_count += 1
521
+ # if previous index was free as well, draw an arch in `links`.
522
+ if block_free_count > 1:
523
+ links[i - 1].append(i)
524
+ links[i].append(i - 1)
525
+ else:
526
+ # Change the sign of the index (`cum_sign`) if the number of free
527
+ # indices preceding it is even.
528
+ cum_sign *= 1 if (block_free_count % 2) else -1
529
+ if block_free_count == 0 and i != first_dum_pos:
530
+ # check if there are two consecutive dummy indices:
531
+ # in this case create virtual indices with negative position,
532
+ # these "virtual" indices represent the insertion of two
533
+ # gamma^0 matrices to separate consecutive dummy indices, as
534
+ # Kahane's algorithm requires dummy indices to be separated by
535
+ # free indices. The product of two gamma^0 matrices is unity,
536
+ # so the new expression being examined is the same as the
537
+ # original one.
538
+ if cum_sign == -1:
539
+ links[-1-i] = [-1-i+1]
540
+ links[-1-i+1] = [-1-i]
541
+ if (i - cum_sign) in links:
542
+ if i != first_dum_pos:
543
+ links[i].append(i - cum_sign)
544
+ if block_free_count != 0:
545
+ if i - cum_sign < len(index_is_free):
546
+ if index_is_free[i - cum_sign]:
547
+ links[i - cum_sign].append(i)
548
+ block_free_count = 0
549
+
550
+ cum_sign_list[i] = cum_sign
551
+
552
+ # The previous loop has only created links between consecutive free indices,
553
+ # it is necessary to properly create links among dummy (contracted) indices,
554
+ # according to the rules described in Kahane's paper. There is only one exception
555
+ # to Kahane's rules: the negative indices, which handle the case of some
556
+ # consecutive free indices (Kahane's paper just describes dummy indices
557
+ # separated by free indices, hinting that free indices can be added without
558
+ # altering the expression result).
559
+ for i in dum:
560
+ # get the positions of the two contracted indices:
561
+ pos1 = i[0]
562
+ pos2 = i[1]
563
+
564
+ # create Kahane's upper links, i.e. the upper arcs between dummy
565
+ # (i.e. contracted) indices:
566
+ links[pos1].append(pos2)
567
+ links[pos2].append(pos1)
568
+
569
+ # create Kahane's lower links, this corresponds to the arcs below
570
+ # the line described in the paper:
571
+
572
+ # first we move `pos1` and `pos2` according to the sign of the indices:
573
+ linkpos1 = pos1 + cum_sign_list[pos1]
574
+ linkpos2 = pos2 + cum_sign_list[pos2]
575
+
576
+ # otherwise, perform some checks before creating the lower arcs:
577
+
578
+ # make sure we are not exceeding the total number of indices:
579
+ if linkpos1 >= total_number:
580
+ continue
581
+ if linkpos2 >= total_number:
582
+ continue
583
+
584
+ # make sure we are not below the first dummy index in `expression`:
585
+ if linkpos1 < first_dum_pos:
586
+ continue
587
+ if linkpos2 < first_dum_pos:
588
+ continue
589
+
590
+ # check if the previous loop created "virtual" indices between dummy
591
+ # indices, in such a case relink `linkpos1` and `linkpos2`:
592
+ if (-1-linkpos1) in links:
593
+ linkpos1 = -1-linkpos1
594
+ if (-1-linkpos2) in links:
595
+ linkpos2 = -1-linkpos2
596
+
597
+ # move only if not next to free index:
598
+ if linkpos1 >= 0 and not index_is_free[linkpos1]:
599
+ linkpos1 = pos1
600
+
601
+ if linkpos2 >=0 and not index_is_free[linkpos2]:
602
+ linkpos2 = pos2
603
+
604
+ # create the lower arcs:
605
+ if linkpos2 not in links[linkpos1]:
606
+ links[linkpos1].append(linkpos2)
607
+ if linkpos1 not in links[linkpos2]:
608
+ links[linkpos2].append(linkpos1)
609
+
610
+ # This loop starts from the `first_dum_pos` index (first dummy index)
611
+ # walks through the graph deleting the visited indices from `links`,
612
+ # it adds a gamma matrix for every free index in encounters, while it
613
+ # completely ignores dummy indices and virtual indices.
614
+ pointer = first_dum_pos
615
+ previous_pointer = 0
616
+ while True:
617
+ if pointer in links:
618
+ next_ones = links.pop(pointer)
619
+ else:
620
+ break
621
+
622
+ if previous_pointer in next_ones:
623
+ next_ones.remove(previous_pointer)
624
+
625
+ previous_pointer = pointer
626
+
627
+ if next_ones:
628
+ pointer = next_ones[0]
629
+ else:
630
+ break
631
+
632
+ if pointer == previous_pointer:
633
+ break
634
+ if pointer >=0 and free_pos[pointer] is not None:
635
+ for ri in resulting_indices:
636
+ ri.append(free_pos[pointer])
637
+
638
+ # The following loop removes the remaining connected components in `links`.
639
+ # If there are free indices inside a connected component, it gives a
640
+ # contribution to the resulting expression given by the factor
641
+ # `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
642
+ # paper represented as {gamma_a, gamma_b, ... , gamma_z},
643
+ # virtual indices are ignored. The variable `connected_components` is
644
+ # increased by one for every connected component this loop encounters.
645
+
646
+ # If the connected component has virtual and dummy indices only
647
+ # (no free indices), it contributes to `resulting_indices` by a factor of two.
648
+ # The multiplication by two is a result of the
649
+ # factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
650
+ # Note: curly brackets are meant as in the paper, as a generalized
651
+ # multi-element anticommutator!
652
+
653
+ while links:
654
+ connected_components += 1
655
+ pointer = min(links.keys())
656
+ previous_pointer = pointer
657
+ # the inner loop erases the visited indices from `links`, and it adds
658
+ # all free indices to `prepend_indices` list, virtual indices are
659
+ # ignored.
660
+ prepend_indices = []
661
+ while True:
662
+ if pointer in links:
663
+ next_ones = links.pop(pointer)
664
+ else:
665
+ break
666
+
667
+ if previous_pointer in next_ones:
668
+ if len(next_ones) > 1:
669
+ next_ones.remove(previous_pointer)
670
+
671
+ previous_pointer = pointer
672
+
673
+ if next_ones:
674
+ pointer = next_ones[0]
675
+
676
+ if pointer >= first_dum_pos and free_pos[pointer] is not None:
677
+ prepend_indices.insert(0, free_pos[pointer])
678
+ # if `prepend_indices` is void, it means there are no free indices
679
+ # in the loop (and it can be shown that there must be a virtual index),
680
+ # loops of virtual indices only contribute by a factor of two:
681
+ if len(prepend_indices) == 0:
682
+ resulting_coeff *= 2
683
+ # otherwise, add the free indices in `prepend_indices` to
684
+ # the `resulting_indices`:
685
+ else:
686
+ expr1 = prepend_indices
687
+ expr2 = list(reversed(prepend_indices))
688
+ resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
689
+
690
+ # sign correction, as described in Kahane's paper:
691
+ resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
692
+ # power of two factor, as described in Kahane's paper:
693
+ resulting_coeff *= 2**(number_of_contractions)
694
+
695
+ # If `first_dum_pos` is not zero, it means that there are trailing free gamma
696
+ # matrices in front of `expression`, so multiply by them:
697
+ resulting_indices = [ free_pos[0:first_dum_pos] + ri for ri in resulting_indices ]
698
+
699
+ resulting_expr = S.Zero
700
+ for i in resulting_indices:
701
+ temp_expr = S.One
702
+ for j in i:
703
+ temp_expr *= GammaMatrix(j)
704
+ resulting_expr += temp_expr
705
+
706
+ t = resulting_coeff * resulting_expr
707
+ t1 = None
708
+ if isinstance(t, TensAdd):
709
+ t1 = t.args[0]
710
+ elif isinstance(t, TensMul):
711
+ t1 = t
712
+ if t1:
713
+ pass
714
+ else:
715
+ t = eye(4)*t
716
+ return t
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.dense import eye, Matrix
2
+ from sympy.tensor.tensor import tensor_indices, TensorHead, tensor_heads, \
3
+ TensExpr, canon_bp
4
+ from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex, \
5
+ kahane_simplify, gamma_trace, _simplify_single_line, simplify_gamma_expression
6
+ from sympy import Symbol
7
+
8
+
9
+ def _is_tensor_eq(arg1, arg2):
10
+ arg1 = canon_bp(arg1)
11
+ arg2 = canon_bp(arg2)
12
+ if isinstance(arg1, TensExpr):
13
+ return arg1.equals(arg2)
14
+ elif isinstance(arg2, TensExpr):
15
+ return arg2.equals(arg1)
16
+ return arg1 == arg2
17
+
18
+ def execute_gamma_simplify_tests_for_function(tfunc, D):
19
+ """
20
+ Perform tests to check if sfunc is able to simplify gamma matrix expressions.
21
+
22
+ Parameters
23
+ ==========
24
+
25
+ `sfunc` a function to simplify a `TIDS`, shall return the simplified `TIDS`.
26
+ `D` the number of dimension (in most cases `D=4`).
27
+
28
+ """
29
+
30
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
31
+ a1, a2, a3, a4, a5, a6 = tensor_indices("a1:7", LorentzIndex)
32
+ mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52 = tensor_indices("mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52", LorentzIndex)
33
+ mu61, mu71, mu72 = tensor_indices("mu61, mu71, mu72", LorentzIndex)
34
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices("m0:7", LorentzIndex)
35
+
36
+ def g(xx, yy):
37
+ return (G(xx)*G(yy) + G(yy)*G(xx))/2
38
+
39
+ # Some examples taken from Kahane's paper, 4 dim only:
40
+ if D == 4:
41
+ t = (G(a1)*G(mu11)*G(a2)*G(mu21)*G(-a1)*G(mu31)*G(-a2))
42
+ assert _is_tensor_eq(tfunc(t), -4*G(mu11)*G(mu31)*G(mu21) - 4*G(mu31)*G(mu11)*G(mu21))
43
+
44
+ t = (G(a1)*G(mu11)*G(mu12)*\
45
+ G(a2)*G(mu21)*\
46
+ G(a3)*G(mu31)*G(mu32)*\
47
+ G(a4)*G(mu41)*\
48
+ G(-a2)*G(mu51)*G(mu52)*\
49
+ G(-a1)*G(mu61)*\
50
+ G(-a3)*G(mu71)*G(mu72)*\
51
+ G(-a4))
52
+ assert _is_tensor_eq(tfunc(t), \
53
+ 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41))
54
+
55
+ # Fully Lorentz-contracted expressions, these return scalars:
56
+
57
+ def add_delta(ne):
58
+ return ne * eye(4) # DiracSpinorIndex.delta(DiracSpinorIndex.auto_left, -DiracSpinorIndex.auto_right)
59
+
60
+ t = (G(mu)*G(-mu))
61
+ ts = add_delta(D)
62
+ assert _is_tensor_eq(tfunc(t), ts)
63
+
64
+ t = (G(mu)*G(nu)*G(-mu)*G(-nu))
65
+ ts = add_delta(2*D - D**2) # -8
66
+ assert _is_tensor_eq(tfunc(t), ts)
67
+
68
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
69
+ ts = add_delta(D**2) # 16
70
+ assert _is_tensor_eq(tfunc(t), ts)
71
+
72
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
73
+ ts = add_delta(4*D - 4*D**2 + D**3) # 16
74
+ assert _is_tensor_eq(tfunc(t), ts)
75
+
76
+ t = (G(mu)*G(nu)*G(rho)*G(-rho)*G(-nu)*G(-mu))
77
+ ts = add_delta(D**3) # 64
78
+ assert _is_tensor_eq(tfunc(t), ts)
79
+
80
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(-a3)*G(-a1)*G(-a2)*G(-a4))
81
+ ts = add_delta(-8*D + 16*D**2 - 8*D**3 + D**4) # -32
82
+ assert _is_tensor_eq(tfunc(t), ts)
83
+
84
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
85
+ ts = add_delta(-16*D + 24*D**2 - 8*D**3 + D**4) # 64
86
+ assert _is_tensor_eq(tfunc(t), ts)
87
+
88
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
89
+ ts = add_delta(8*D - 12*D**2 + 6*D**3 - D**4) # -32
90
+ assert _is_tensor_eq(tfunc(t), ts)
91
+
92
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a2)*G(-a1)*G(-a5)*G(-a4))
93
+ ts = add_delta(64*D - 112*D**2 + 60*D**3 - 12*D**4 + D**5) # 256
94
+ assert _is_tensor_eq(tfunc(t), ts)
95
+
96
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a1)*G(-a2)*G(-a4)*G(-a5))
97
+ ts = add_delta(64*D - 120*D**2 + 72*D**3 - 16*D**4 + D**5) # -128
98
+ assert _is_tensor_eq(tfunc(t), ts)
99
+
100
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a3)*G(-a2)*G(-a1)*G(-a6)*G(-a5)*G(-a4))
101
+ ts = add_delta(416*D - 816*D**2 + 528*D**3 - 144*D**4 + 18*D**5 - D**6) # -128
102
+ assert _is_tensor_eq(tfunc(t), ts)
103
+
104
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a2)*G(-a3)*G(-a1)*G(-a6)*G(-a4)*G(-a5))
105
+ ts = add_delta(416*D - 848*D**2 + 584*D**3 - 172*D**4 + 22*D**5 - D**6) # -128
106
+ assert _is_tensor_eq(tfunc(t), ts)
107
+
108
+ # Expressions with free indices:
109
+
110
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
111
+ assert _is_tensor_eq(tfunc(t), (-2*G(sigma)*G(rho)*G(nu) + (4-D)*G(nu)*G(rho)*G(sigma)))
112
+
113
+ t = (G(mu)*G(nu)*G(-mu))
114
+ assert _is_tensor_eq(tfunc(t), (2-D)*G(nu))
115
+
116
+ t = (G(mu)*G(nu)*G(rho)*G(-mu))
117
+ assert _is_tensor_eq(tfunc(t), 2*G(nu)*G(rho) + 2*G(rho)*G(nu) - (4-D)*G(nu)*G(rho))
118
+
119
+ t = 2*G(m2)*G(m0)*G(m1)*G(-m0)*G(-m1)
120
+ st = tfunc(t)
121
+ assert _is_tensor_eq(st, (D*(-2*D + 4))*G(m2))
122
+
123
+ t = G(m2)*G(m0)*G(m1)*G(-m0)*G(-m2)
124
+ st = tfunc(t)
125
+ assert _is_tensor_eq(st, ((-D + 2)**2)*G(m1))
126
+
127
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)
128
+ st = tfunc(t)
129
+ assert _is_tensor_eq(st, (D - 4)*G(m0)*G(m2)*G(m3) + 4*G(m0)*g(m2, m3))
130
+
131
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)*G(-m0)
132
+ st = tfunc(t)
133
+ assert _is_tensor_eq(st, ((D - 4)**2)*G(m2)*G(m3) + (8*D - 16)*g(m2, m3))
134
+
135
+ t = G(m2)*G(m0)*G(m1)*G(-m2)*G(-m0)
136
+ st = tfunc(t)
137
+ assert _is_tensor_eq(st, ((-D + 2)*(D - 4) + 4)*G(m1))
138
+
139
+ t = G(m3)*G(m1)*G(m0)*G(m2)*G(-m3)*G(-m0)*G(-m2)
140
+ st = tfunc(t)
141
+ assert _is_tensor_eq(st, (-4*D + (-D + 2)**2*(D - 4) + 8)*G(m1))
142
+
143
+ t = 2*G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)
144
+ st = tfunc(t)
145
+ assert _is_tensor_eq(st, ((-2*D + 8)*G(m1)*G(m2)*G(m3) - 4*G(m3)*G(m2)*G(m1)))
146
+
147
+ t = G(m5)*G(m0)*G(m1)*G(m4)*G(m2)*G(-m4)*G(m3)*G(-m0)
148
+ st = tfunc(t)
149
+ assert _is_tensor_eq(st, (((-D + 2)*(-D + 4))*G(m5)*G(m1)*G(m2)*G(m3) + (2*D - 4)*G(m5)*G(m3)*G(m2)*G(m1)))
150
+
151
+ t = -G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)*G(m4)
152
+ st = tfunc(t)
153
+ assert _is_tensor_eq(st, ((D - 4)*G(m1)*G(m2)*G(m3)*G(m4) + 2*G(m3)*G(m2)*G(m1)*G(m4)))
154
+
155
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
156
+ st = tfunc(t)
157
+
158
+ result1 = ((-D + 4)**2 + 4)*G(m1)*G(m2)*G(m3)*G(m4) +\
159
+ (4*D - 16)*G(m3)*G(m2)*G(m1)*G(m4) + (4*D - 16)*G(m4)*G(m1)*G(m2)*G(m3)\
160
+ + 4*G(m2)*G(m1)*G(m4)*G(m3) + 4*G(m3)*G(m4)*G(m1)*G(m2) +\
161
+ 4*G(m4)*G(m3)*G(m2)*G(m1)
162
+
163
+ # Kahane's algorithm yields this result, which is equivalent to `result1`
164
+ # in four dimensions, but is not automatically recognized as equal:
165
+ result2 = 8*G(m1)*G(m2)*G(m3)*G(m4) + 8*G(m4)*G(m3)*G(m2)*G(m1)
166
+
167
+ if D == 4:
168
+ assert _is_tensor_eq(st, (result1)) or _is_tensor_eq(st, (result2))
169
+ else:
170
+ assert _is_tensor_eq(st, (result1))
171
+
172
+ # and a few very simple cases, with no contracted indices:
173
+
174
+ t = G(m0)
175
+ st = tfunc(t)
176
+ assert _is_tensor_eq(st, t)
177
+
178
+ t = -7*G(m0)
179
+ st = tfunc(t)
180
+ assert _is_tensor_eq(st, t)
181
+
182
+ t = 224*G(m0)*G(m1)*G(-m2)*G(m3)
183
+ st = tfunc(t)
184
+ assert _is_tensor_eq(st, t)
185
+
186
+
187
+ def test_kahane_algorithm():
188
+ # Wrap this function to convert to and from TIDS:
189
+
190
+ def tfunc(e):
191
+ return _simplify_single_line(e)
192
+
193
+ execute_gamma_simplify_tests_for_function(tfunc, D=4)
194
+
195
+
196
+ def test_kahane_simplify1():
197
+ i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15 = tensor_indices('i0:16', LorentzIndex)
198
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
199
+ D = 4
200
+ t = G(i0)*G(i1)
201
+ r = kahane_simplify(t)
202
+ assert r.equals(t)
203
+
204
+ t = G(i0)*G(i1)*G(-i0)
205
+ r = kahane_simplify(t)
206
+ assert r.equals(-2*G(i1))
207
+ t = G(i0)*G(i1)*G(-i0)
208
+ r = kahane_simplify(t)
209
+ assert r.equals(-2*G(i1))
210
+
211
+ t = G(i0)*G(i1)
212
+ r = kahane_simplify(t)
213
+ assert r.equals(t)
214
+ t = G(i0)*G(i1)
215
+ r = kahane_simplify(t)
216
+ assert r.equals(t)
217
+ t = G(i0)*G(-i0)
218
+ r = kahane_simplify(t)
219
+ assert r.equals(4*eye(4))
220
+ t = G(i0)*G(-i0)
221
+ r = kahane_simplify(t)
222
+ assert r.equals(4*eye(4))
223
+ t = G(i0)*G(-i0)
224
+ r = kahane_simplify(t)
225
+ assert r.equals(4*eye(4))
226
+ t = G(i0)*G(i1)*G(-i0)
227
+ r = kahane_simplify(t)
228
+ assert r.equals(-2*G(i1))
229
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
230
+ r = kahane_simplify(t)
231
+ assert r.equals((2*D - D**2)*eye(4))
232
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
233
+ r = kahane_simplify(t)
234
+ assert r.equals((2*D - D**2)*eye(4))
235
+ t = G(i0)*G(-i0)*G(i1)*G(-i1)
236
+ r = kahane_simplify(t)
237
+ assert r.equals(16*eye(4))
238
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
239
+ r = kahane_simplify(t)
240
+ assert r.equals(D**2*eye(4))
241
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
242
+ r = kahane_simplify(t)
243
+ assert r.equals(D**2*eye(4))
244
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
245
+ r = kahane_simplify(t)
246
+ assert r.equals(D**2*eye(4))
247
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
248
+ r = kahane_simplify(t)
249
+ assert r.equals((4*D - 4*D**2 + D**3)*eye(4))
250
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
251
+ r = kahane_simplify(t)
252
+ assert r.equals((-16*D + 24*D**2 - 8*D**3 + D**4)*eye(4))
253
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
254
+ r = kahane_simplify(t)
255
+ assert r.equals((8*D - 12*D**2 + 6*D**3 - D**4)*eye(4))
256
+
257
+ # Expressions with free indices:
258
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
259
+ r = kahane_simplify(t)
260
+ assert r.equals(-2*G(sigma)*G(rho)*G(nu))
261
+ t = (G(mu)*G(-mu)*G(rho)*G(sigma))
262
+ r = kahane_simplify(t)
263
+ assert r.equals(4*G(rho)*G(sigma))
264
+ t = (G(rho)*G(sigma)*G(mu)*G(-mu))
265
+ r = kahane_simplify(t)
266
+ assert r.equals(4*G(rho)*G(sigma))
267
+
268
+ def test_gamma_matrix_class():
269
+ i, j, k = tensor_indices('i,j,k', LorentzIndex)
270
+
271
+ # define another type of TensorHead to see if exprs are correctly handled:
272
+ A = TensorHead('A', [LorentzIndex])
273
+
274
+ t = A(k)*G(i)*G(-i)
275
+ ts = simplify_gamma_expression(t)
276
+ assert _is_tensor_eq(ts, Matrix([
277
+ [4, 0, 0, 0],
278
+ [0, 4, 0, 0],
279
+ [0, 0, 4, 0],
280
+ [0, 0, 0, 4]])*A(k))
281
+
282
+ t = G(i)*A(k)*G(j)
283
+ ts = simplify_gamma_expression(t)
284
+ assert _is_tensor_eq(ts, A(k)*G(i)*G(j))
285
+
286
+ execute_gamma_simplify_tests_for_function(simplify_gamma_expression, D=4)
287
+
288
+
289
+ def test_gamma_matrix_trace():
290
+ g = LorentzIndex.metric
291
+
292
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices('m0:7', LorentzIndex)
293
+ n0, n1, n2, n3, n4, n5 = tensor_indices('n0:6', LorentzIndex)
294
+
295
+ # working in D=4 dimensions
296
+ D = 4
297
+
298
+ # traces of odd number of gamma matrices are zero:
299
+ t = G(m0)
300
+ t1 = gamma_trace(t)
301
+ assert t1.equals(0)
302
+
303
+ t = G(m0)*G(m1)*G(m2)
304
+ t1 = gamma_trace(t)
305
+ assert t1.equals(0)
306
+
307
+ t = G(m0)*G(m1)*G(-m0)
308
+ t1 = gamma_trace(t)
309
+ assert t1.equals(0)
310
+
311
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)
312
+ t1 = gamma_trace(t)
313
+ assert t1.equals(0)
314
+
315
+ # traces without internal contractions:
316
+ t = G(m0)*G(m1)
317
+ t1 = gamma_trace(t)
318
+ assert _is_tensor_eq(t1, 4*g(m0, m1))
319
+
320
+ t = G(m0)*G(m1)*G(m2)*G(m3)
321
+ t1 = gamma_trace(t)
322
+ t2 = -4*g(m0, m2)*g(m1, m3) + 4*g(m0, m1)*g(m2, m3) + 4*g(m0, m3)*g(m1, m2)
323
+ assert _is_tensor_eq(t1, t2)
324
+
325
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)
326
+ t1 = gamma_trace(t)
327
+ t2 = t1*g(-m0, -m5)
328
+ t2 = t2.contract_metric(g)
329
+ assert _is_tensor_eq(t2, D*gamma_trace(G(m1)*G(m2)*G(m3)*G(m4)))
330
+
331
+ # traces of expressions with internal contractions:
332
+ t = G(m0)*G(-m0)
333
+ t1 = gamma_trace(t)
334
+ assert t1.equals(4*D)
335
+
336
+ t = G(m0)*G(m1)*G(-m0)*G(-m1)
337
+ t1 = gamma_trace(t)
338
+ assert t1.equals(8*D - 4*D**2)
339
+
340
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)
341
+ t1 = gamma_trace(t)
342
+ t2 = (-4*D)*g(m1, m3)*g(m2, m4) + (4*D)*g(m1, m2)*g(m3, m4) + \
343
+ (4*D)*g(m1, m4)*g(m2, m3)
344
+ assert _is_tensor_eq(t1, t2)
345
+
346
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
347
+ t1 = gamma_trace(t)
348
+ t2 = (32*D + 4*(-D + 4)**2 - 64)*(g(m1, m2)*g(m3, m4) - \
349
+ g(m1, m3)*g(m2, m4) + g(m1, m4)*g(m2, m3))
350
+ assert _is_tensor_eq(t1, t2)
351
+
352
+ t = G(m0)*G(m1)*G(-m0)*G(m3)
353
+ t1 = gamma_trace(t)
354
+ assert t1.equals((-4*D + 8)*g(m1, m3))
355
+
356
+ # p, q = S1('p,q')
357
+ # ps = p(m0)*G(-m0)
358
+ # qs = q(m0)*G(-m0)
359
+ # t = ps*qs*ps*qs
360
+ # t1 = gamma_trace(t)
361
+ # assert t1 == 8*p(m0)*q(-m0)*p(m1)*q(-m1) - 4*p(m0)*p(-m0)*q(m1)*q(-m1)
362
+
363
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)*G(-m5)
364
+ t1 = gamma_trace(t)
365
+ assert t1.equals(-4*D**6 + 120*D**5 - 1040*D**4 + 3360*D**3 - 4480*D**2 + 2048*D)
366
+
367
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(-n2)*G(-n1)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
368
+ t1 = gamma_trace(t)
369
+ tresu = -7168*D + 16768*D**2 - 14400*D**3 + 5920*D**4 - 1232*D**5 + 120*D**6 - 4*D**7
370
+ assert t1.equals(tresu)
371
+
372
+ # checked with Mathematica
373
+ # In[1]:= <<Tracer.m
374
+ # In[2]:= Spur[l];
375
+ # In[3]:= GammaTrace[l, {m0},{m1},{n1},{m2},{n2},{m3},{m4},{n3},{n4},{m0},{m1},{m2},{m3},{m4}]
376
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(n3)*G(n4)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
377
+ t1 = gamma_trace(t)
378
+ # t1 = t1.expand_coeff()
379
+ c1 = -4*D**5 + 120*D**4 - 1200*D**3 + 5280*D**2 - 10560*D + 7808
380
+ c2 = -4*D**5 + 88*D**4 - 560*D**3 + 1440*D**2 - 1600*D + 640
381
+ assert _is_tensor_eq(t1, c1*g(n1, n4)*g(n2, n3) + c2*g(n1, n2)*g(n3, n4) + \
382
+ (-c1)*g(n1, n3)*g(n2, n4))
383
+
384
+ p, q = tensor_heads('p,q', [LorentzIndex])
385
+ ps = p(m0)*G(-m0)
386
+ qs = q(m0)*G(-m0)
387
+ p2 = p(m0)*p(-m0)
388
+ q2 = q(m0)*q(-m0)
389
+ pq = p(m0)*q(-m0)
390
+ t = ps*qs*ps*qs
391
+ r = gamma_trace(t)
392
+ assert _is_tensor_eq(r, 8*pq*pq - 4*p2*q2)
393
+ t = ps*qs*ps*qs*ps*qs
394
+ r = gamma_trace(t)
395
+ assert _is_tensor_eq(r, -12*p2*pq*q2 + 16*pq*pq*pq)
396
+ t = ps*qs*ps*qs*ps*qs*ps*qs
397
+ r = gamma_trace(t)
398
+ assert _is_tensor_eq(r, -32*pq*pq*p2*q2 + 32*pq*pq*pq*pq + 4*p2*p2*q2*q2)
399
+
400
+ t = 4*p(m1)*p(m0)*p(-m0)*q(-m1)*q(m2)*q(-m2)
401
+ assert _is_tensor_eq(gamma_trace(t), t)
402
+ t = ps*ps*ps*ps*ps*ps*ps*ps
403
+ r = gamma_trace(t)
404
+ assert r.equals(4*p2*p2*p2*p2)
405
+
406
+
407
+ def test_bug_13636():
408
+ """Test issue 13636 regarding handling traces of sums of products
409
+ of GammaMatrix mixed with other factors."""
410
+ pi, ki, pf = tensor_heads("pi, ki, pf", [LorentzIndex])
411
+ i0, i1, i2, i3, i4 = tensor_indices("i0:5", LorentzIndex)
412
+ x = Symbol("x")
413
+ pis = pi(i2) * G(-i2)
414
+ kis = ki(i3) * G(-i3)
415
+ pfs = pf(i4) * G(-i4)
416
+
417
+ a = pfs * G(i0) * kis * G(i1) * pis * G(-i1) * kis * G(-i0)
418
+ b = pfs * G(i0) * kis * G(i1) * pis * x * G(-i0) * pi(-i1)
419
+ ta = gamma_trace(a)
420
+ tb = gamma_trace(b)
421
+ t_a_plus_b = gamma_trace(a + b)
422
+ assert ta == 4 * (
423
+ -4 * ki(i0) * ki(-i0) * pf(i1) * pi(-i1)
424
+ + 8 * ki(i0) * ki(i1) * pf(-i0) * pi(-i1)
425
+ )
426
+ assert tb == -8 * x * ki(i0) * pf(-i0) * pi(i1) * pi(-i1)
427
+ assert t_a_plus_b == ta + tb
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_fermion.cpython-310.pyc ADDED
Binary file (1.17 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_matrixutils.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_cg.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Wigner6j(1, 2, 3, 2, 1, 2).doit() == sqrt(21)/105
175
+ assert Wigner6j(3, 1, 2, 2, 2, 1).doit() == sqrt(21) / 105
176
+ assert Wigner9j(
177
+ 2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0).doit() == sqrt(2)/12
178
+ assert CG(S.Half, S.Half, S.Half, Rational(-1, 2), 1, 0).doit() == sqrt(2)/2
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_constants.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+
3
+ from sympy.physics.quantum.constants import hbar
4
+
5
+
6
+ def test_hbar():
7
+ assert hbar.is_commutative is True
8
+ assert hbar.is_real is True
9
+ assert hbar.is_positive is True
10
+ assert hbar.is_negative is False
11
+ assert hbar.is_irrational is True
12
+
13
+ assert hbar.evalf() == Float(1.05457162e-34)
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_fermion.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.quantum import Dagger, AntiCommutator, qapply
2
+ from sympy.physics.quantum.fermion import FermionOp
3
+ from sympy.physics.quantum.fermion import FermionFockKet, FermionFockBra
4
+
5
+
6
+ def test_fermionoperator():
7
+ c = FermionOp('c')
8
+ d = FermionOp('d')
9
+
10
+ assert isinstance(c, FermionOp)
11
+ assert isinstance(Dagger(c), FermionOp)
12
+
13
+ assert c.is_annihilation
14
+ assert not Dagger(c).is_annihilation
15
+
16
+ assert FermionOp("c") == FermionOp("c", True)
17
+ assert FermionOp("c") != FermionOp("d")
18
+ assert FermionOp("c", True) != FermionOp("c", False)
19
+
20
+ assert AntiCommutator(c, Dagger(c)).doit() == 1
21
+
22
+ assert AntiCommutator(c, Dagger(d)).doit() == c * Dagger(d) + Dagger(d) * c
23
+
24
+
25
+ def test_fermion_states():
26
+ c = FermionOp("c")
27
+
28
+ # Fock states
29
+ assert (FermionFockBra(0) * FermionFockKet(1)).doit() == 0
30
+ assert (FermionFockBra(1) * FermionFockKet(1)).doit() == 1
31
+
32
+ assert qapply(c * FermionFockKet(1)) == FermionFockKet(0)
33
+ assert qapply(c * FermionFockKet(0)) == 0
34
+
35
+ assert qapply(Dagger(c) * FermionFockKet(0)) == FermionFockKet(1)
36
+ assert qapply(Dagger(c) * FermionFockKet(1)) == 0
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_operatorordering.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.quantum import Dagger
2
+ from sympy.physics.quantum.boson import BosonOp
3
+ from sympy.physics.quantum.fermion import FermionOp
4
+ from sympy.physics.quantum.operatorordering import (normal_order,
5
+ normal_ordered_form)
6
+
7
+
8
+ def test_normal_order():
9
+ a = BosonOp('a')
10
+
11
+ c = FermionOp('c')
12
+
13
+ assert normal_order(a * Dagger(a)) == Dagger(a) * a
14
+ assert normal_order(Dagger(a) * a) == Dagger(a) * a
15
+ assert normal_order(a * Dagger(a) ** 2) == Dagger(a) ** 2 * a
16
+
17
+ assert normal_order(c * Dagger(c)) == - Dagger(c) * c
18
+ assert normal_order(Dagger(c) * c) == Dagger(c) * c
19
+ assert normal_order(c * Dagger(c) ** 2) == Dagger(c) ** 2 * c
20
+
21
+
22
+ def test_normal_ordered_form():
23
+ a = BosonOp('a')
24
+
25
+ c = FermionOp('c')
26
+
27
+ assert normal_ordered_form(Dagger(a) * a) == Dagger(a) * a
28
+ assert normal_ordered_form(a * Dagger(a)) == 1 + Dagger(a) * a
29
+ assert normal_ordered_form(a ** 2 * Dagger(a)) == \
30
+ 2 * a + Dagger(a) * a ** 2
31
+ assert normal_ordered_form(a ** 3 * Dagger(a)) == \
32
+ 3 * a ** 2 + Dagger(a) * a ** 3
33
+
34
+ assert normal_ordered_form(Dagger(c) * c) == Dagger(c) * c
35
+ assert normal_ordered_form(c * Dagger(c)) == 1 - Dagger(c) * c
36
+ assert normal_ordered_form(c ** 2 * Dagger(c)) == Dagger(c) * c ** 2
37
+ assert normal_ordered_form(c ** 3 * Dagger(c)) == \
38
+ c ** 2 - Dagger(c) * c ** 3
env-llmeval/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}'
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_qft.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi)
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.functions.elementary.exponential import exp
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.matrices.dense import Matrix
6
+
7
+ from sympy.physics.quantum.qft import QFT, IQFT, RkGate
8
+ from sympy.physics.quantum.gate import (ZGate, SwapGate, HadamardGate, CGate,
9
+ PhaseGate, TGate)
10
+ from sympy.physics.quantum.qubit import Qubit
11
+ from sympy.physics.quantum.qapply import qapply
12
+ from sympy.physics.quantum.represent import represent
13
+
14
+
15
+ def test_RkGate():
16
+ x = Symbol('x')
17
+ assert RkGate(1, x).k == x
18
+ assert RkGate(1, x).targets == (1,)
19
+ assert RkGate(1, 1) == ZGate(1)
20
+ assert RkGate(2, 2) == PhaseGate(2)
21
+ assert RkGate(3, 3) == TGate(3)
22
+
23
+ assert represent(
24
+ RkGate(0, x), nqubits=1) == Matrix([[1, 0], [0, exp(2*I*pi/2**x)]])
25
+
26
+
27
+ def test_quantum_fourier():
28
+ assert QFT(0, 3).decompose() == \
29
+ SwapGate(0, 2)*HadamardGate(0)*CGate((0,), PhaseGate(1)) * \
30
+ HadamardGate(1)*CGate((0,), TGate(2))*CGate((1,), PhaseGate(2)) * \
31
+ HadamardGate(2)
32
+
33
+ assert IQFT(0, 3).decompose() == \
34
+ HadamardGate(2)*CGate((1,), RkGate(2, -2))*CGate((0,), RkGate(2, -3)) * \
35
+ HadamardGate(1)*CGate((0,), RkGate(1, -2))*HadamardGate(0)*SwapGate(0, 2)
36
+
37
+ assert represent(QFT(0, 3), nqubits=3) == \
38
+ Matrix([[exp(2*pi*I/8)**(i*j % 8)/sqrt(8) for i in range(8)] for j in range(8)])
39
+
40
+ assert QFT(0, 4).decompose() # non-trivial decomposition
41
+ assert qapply(QFT(0, 3).decompose()*Qubit(0, 0, 0)).expand() == qapply(
42
+ HadamardGate(0)*HadamardGate(1)*HadamardGate(2)*Qubit(0, 0, 0)
43
+ ).expand()
44
+
45
+
46
+ def test_qft_represent():
47
+ c = QFT(0, 3)
48
+ a = represent(c, nqubits=3)
49
+ b = represent(c.decompose(), nqubits=3)
50
+ assert a.evalf(n=10) == b.evalf(n=10)
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_represent.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
23
+ Amat = Matrix([[1, I], [-I, 1]])
24
+ Bmat = Matrix([[1, 2], [3, 4]])
25
+ Avec = Matrix([[1], [I]])
26
+
27
+
28
+ class AKet(Ket):
29
+
30
+ @classmethod
31
+ def dual_class(self):
32
+ return ABra
33
+
34
+ def _represent_default_basis(self, **options):
35
+ return self._represent_AOp(None, **options)
36
+
37
+ def _represent_AOp(self, basis, **options):
38
+ return Avec
39
+
40
+
41
+ class ABra(Bra):
42
+
43
+ @classmethod
44
+ def dual_class(self):
45
+ return AKet
46
+
47
+
48
+ class AOp(Operator):
49
+
50
+ def _represent_default_basis(self, **options):
51
+ return self._represent_AOp(None, **options)
52
+
53
+ def _represent_AOp(self, basis, **options):
54
+ return Amat
55
+
56
+
57
+ class BOp(Operator):
58
+
59
+ def _represent_default_basis(self, **options):
60
+ return self._represent_AOp(None, **options)
61
+
62
+ def _represent_AOp(self, basis, **options):
63
+ return Bmat
64
+
65
+
66
+ k = AKet('a')
67
+ b = ABra('a')
68
+ A = AOp('A')
69
+ B = BOp('B')
70
+
71
+ _tests = [
72
+ # Bra
73
+ (b, Dagger(Avec)),
74
+ (Dagger(b), Avec),
75
+ # Ket
76
+ (k, Avec),
77
+ (Dagger(k), Dagger(Avec)),
78
+ # Operator
79
+ (A, Amat),
80
+ (Dagger(A), Dagger(Amat)),
81
+ # OuterProduct
82
+ (OuterProduct(k, b), Avec*Avec.H),
83
+ # TensorProduct
84
+ (TensorProduct(A, B), matrix_tensor_product(Amat, Bmat)),
85
+ # Pow
86
+ (A**2, Amat**2),
87
+ # Add/Mul
88
+ (A*B + 2*A, Amat*Bmat + 2*Amat),
89
+ # Commutator
90
+ (Commutator(A, B), Amat*Bmat - Bmat*Amat),
91
+ # AntiCommutator
92
+ (AntiCommutator(A, B), Amat*Bmat + Bmat*Amat),
93
+ # InnerProduct
94
+ (InnerProduct(b, k), (Avec.H*Avec)[0])
95
+ ]
96
+
97
+
98
+ def test_format_sympy():
99
+ for test in _tests:
100
+ lhs = represent(test[0], basis=A, format='sympy')
101
+ rhs = to_sympy(test[1])
102
+ assert lhs == rhs
103
+
104
+
105
+ def test_scalar_sympy():
106
+ assert represent(Integer(1)) == Integer(1)
107
+ assert represent(Float(1.0)) == Float(1.0)
108
+ assert represent(1.0 + I) == 1.0 + I
109
+
110
+
111
+ np = import_module('numpy')
112
+
113
+
114
+ def test_format_numpy():
115
+ if not np:
116
+ skip("numpy not installed.")
117
+
118
+ for test in _tests:
119
+ lhs = represent(test[0], basis=A, format='numpy')
120
+ rhs = to_numpy(test[1])
121
+ if isinstance(lhs, numpy_ndarray):
122
+ assert (lhs == rhs).all()
123
+ else:
124
+ assert lhs == rhs
125
+
126
+
127
+ def test_scalar_numpy():
128
+ if not np:
129
+ skip("numpy not installed.")
130
+
131
+ assert represent(Integer(1), format='numpy') == 1
132
+ assert represent(Float(1.0), format='numpy') == 1.0
133
+ assert represent(1.0 + I, format='numpy') == 1.0 + 1.0j
134
+
135
+
136
+ scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
137
+
138
+
139
+ def test_format_scipy_sparse():
140
+ if not np:
141
+ skip("numpy not installed.")
142
+ if not scipy:
143
+ skip("scipy not installed.")
144
+
145
+ for test in _tests:
146
+ lhs = represent(test[0], basis=A, format='scipy.sparse')
147
+ rhs = to_scipy_sparse(test[1])
148
+ if isinstance(lhs, scipy_sparse_matrix):
149
+ assert np.linalg.norm((lhs - rhs).todense()) == 0.0
150
+ else:
151
+ assert lhs == rhs
152
+
153
+
154
+ def test_scalar_scipy_sparse():
155
+ if not np:
156
+ skip("numpy not installed.")
157
+ if not scipy:
158
+ skip("scipy not installed.")
159
+
160
+ assert represent(Integer(1), format='scipy.sparse') == 1
161
+ assert represent(Float(1.0), format='scipy.sparse') == 1.0
162
+ assert represent(1.0 + I, format='scipy.sparse') == 1.0 + 1.0j
163
+
164
+ x_ket = XKet('x')
165
+ x_bra = XBra('x')
166
+ x_op = XOp('X')
167
+
168
+
169
+ def test_innerprod_represent():
170
+ assert rep_innerproduct(x_ket) == InnerProduct(XBra("x_1"), x_ket).doit()
171
+ assert rep_innerproduct(x_bra) == InnerProduct(x_bra, XKet("x_1")).doit()
172
+
173
+ try:
174
+ rep_innerproduct(x_op)
175
+ except TypeError:
176
+ return True
177
+
178
+
179
+ def test_operator_represent():
180
+ basis_kets = enumerate_states(operators_to_state(x_op), 1, 2)
181
+ assert rep_expectation(
182
+ x_op) == qapply(basis_kets[1].dual*x_op*basis_kets[0])
183
+
184
+
185
+ def test_enumerate_states():
186
+ test = XKet("foo")
187
+ assert enumerate_states(test, 1, 1) == [XKet("foo_1")]
188
+ assert enumerate_states(
189
+ test, [1, 2, 4]) == [XKet("foo_1"), XKet("foo_2"), XKet("foo_4")]
env-llmeval/lib/python3.10/site-packages/sympy/physics/quantum/tests/test_shor.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.testing.pytest import XFAIL
2
+
3
+ from sympy.physics.quantum.qapply import qapply
4
+ from sympy.physics.quantum.qubit import Qubit
5
+ from sympy.physics.quantum.shor import CMod, getr
6
+
7
+
8
+ @XFAIL
9
+ def test_CMod():
10
+ assert qapply(CMod(4, 2, 2)*Qubit(0, 0, 1, 0, 0, 0, 0, 0)) == \
11
+ Qubit(0, 0, 1, 0, 0, 0, 0, 0)
12
+ assert qapply(CMod(5, 5, 7)*Qubit(0, 0, 1, 0, 0, 0, 0, 0, 0, 0)) == \
13
+ Qubit(0, 0, 1, 0, 0, 0, 0, 0, 1, 0)
14
+ assert qapply(CMod(3, 2, 3)*Qubit(0, 1, 0, 0, 0, 0)) == \
15
+ Qubit(0, 1, 0, 0, 0, 1)
16
+
17
+
18
+ def test_continued_frac():
19
+ assert getr(513, 1024, 10) == 2
20
+ assert getr(169, 1024, 11) == 6
21
+ assert getr(314, 4096, 16) == 13
env-llmeval/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
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__init__.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'CoordinateSym', 'ReferenceFrame',
3
+
4
+ 'Dyadic',
5
+
6
+ 'Vector',
7
+
8
+ 'Point',
9
+
10
+ 'cross', 'dot', 'express', 'time_derivative', 'outer',
11
+ 'kinematic_equations', 'get_motion_params', 'partial_velocity',
12
+ 'dynamicsymbols',
13
+
14
+ 'vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting',
15
+
16
+ 'curl', 'divergence', 'gradient', 'is_conservative', 'is_solenoidal',
17
+ 'scalar_potential', 'scalar_potential_difference',
18
+
19
+ ]
20
+ from .frame import CoordinateSym, ReferenceFrame
21
+
22
+ from .dyadic import Dyadic
23
+
24
+ from .vector import Vector
25
+
26
+ from .point import Point
27
+
28
+ from .functions import (cross, dot, express, time_derivative, outer,
29
+ kinematic_equations, get_motion_params, partial_velocity,
30
+ dynamicsymbols)
31
+
32
+ from .printing import (vprint, vsstrrepr, vsprint, vpprint, vlatex,
33
+ init_vprinting)
34
+
35
+ from .fieldfunctions import (curl, divergence, gradient, is_conservative,
36
+ is_solenoidal, scalar_potential, scalar_potential_difference)
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/dyadic.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/fieldfunctions.cpython-310.pyc ADDED
Binary file (7.74 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/frame.cpython-310.pyc ADDED
Binary file (45.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/functions.cpython-310.pyc ADDED
Binary file (19.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/point.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/printing.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/vector/__pycache__/vector.cpython-310.pyc ADDED
Binary file (24.8 kB). View file