Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py +5 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py +782 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py +108 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py +735 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_body.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_functions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_linearize.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_method.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_rigidbody.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_body.py +319 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py +292 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py +532 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane2.py +462 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane3.py +293 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange.py +247 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_linearize.py +334 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_particle.py +63 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_rigidbody.py +161 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/boson.py +259 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py +341 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/cg.py +754 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py +488 -0
- llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py +239 -0
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__all__ = ['Beam',
|
2 |
+
'Truss']
|
3 |
+
|
4 |
+
from .beam import Beam
|
5 |
+
from .truss import Truss
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (307 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc
ADDED
Binary file (120 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc
ADDED
Binary file (22.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (212 Bytes). View file
|
|
llmeval-env/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")
|
llmeval-env/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
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py
ADDED
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module can be used to solve problems related
|
3 |
+
to 2D Trusses.
|
4 |
+
"""
|
5 |
+
|
6 |
+
from cmath import inf
|
7 |
+
from sympy.core.add import Add
|
8 |
+
from sympy.core.mul import Mul
|
9 |
+
from sympy.core.symbol import Symbol
|
10 |
+
from sympy.core.sympify import sympify
|
11 |
+
from sympy import Matrix, pi
|
12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
13 |
+
from sympy.matrices.dense import zeros
|
14 |
+
from sympy import sin, cos
|
15 |
+
|
16 |
+
|
17 |
+
|
18 |
+
class Truss:
|
19 |
+
"""
|
20 |
+
A Truss is an assembly of members such as beams,
|
21 |
+
connected by nodes, that create a rigid structure.
|
22 |
+
In engineering, a truss is a structure that
|
23 |
+
consists of two-force members only.
|
24 |
+
|
25 |
+
Trusses are extremely important in engineering applications
|
26 |
+
and can be seen in numerous real-world applications like bridges.
|
27 |
+
|
28 |
+
Examples
|
29 |
+
========
|
30 |
+
|
31 |
+
There is a Truss consisting of four nodes and five
|
32 |
+
members connecting the nodes. A force P acts
|
33 |
+
downward on the node D and there also exist pinned
|
34 |
+
and roller joints on the nodes A and B respectively.
|
35 |
+
|
36 |
+
.. image:: truss_example.png
|
37 |
+
|
38 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
39 |
+
>>> t = Truss()
|
40 |
+
>>> t.add_node("node_1", 0, 0)
|
41 |
+
>>> t.add_node("node_2", 6, 0)
|
42 |
+
>>> t.add_node("node_3", 2, 2)
|
43 |
+
>>> t.add_node("node_4", 2, 0)
|
44 |
+
>>> t.add_member("member_1", "node_1", "node_4")
|
45 |
+
>>> t.add_member("member_2", "node_2", "node_4")
|
46 |
+
>>> t.add_member("member_3", "node_1", "node_3")
|
47 |
+
>>> t.add_member("member_4", "node_2", "node_3")
|
48 |
+
>>> t.add_member("member_5", "node_3", "node_4")
|
49 |
+
>>> t.apply_load("node_4", magnitude=10, direction=270)
|
50 |
+
>>> t.apply_support("node_1", type="fixed")
|
51 |
+
>>> t.apply_support("node_2", type="roller")
|
52 |
+
"""
|
53 |
+
|
54 |
+
def __init__(self):
|
55 |
+
"""
|
56 |
+
Initializes the class
|
57 |
+
"""
|
58 |
+
self._nodes = []
|
59 |
+
self._members = {}
|
60 |
+
self._loads = {}
|
61 |
+
self._supports = {}
|
62 |
+
self._node_labels = []
|
63 |
+
self._node_positions = []
|
64 |
+
self._node_position_x = []
|
65 |
+
self._node_position_y = []
|
66 |
+
self._nodes_occupied = {}
|
67 |
+
self._reaction_loads = {}
|
68 |
+
self._internal_forces = {}
|
69 |
+
self._node_coordinates = {}
|
70 |
+
|
71 |
+
@property
|
72 |
+
def nodes(self):
|
73 |
+
"""
|
74 |
+
Returns the nodes of the truss along with their positions.
|
75 |
+
"""
|
76 |
+
return self._nodes
|
77 |
+
|
78 |
+
@property
|
79 |
+
def node_labels(self):
|
80 |
+
"""
|
81 |
+
Returns the node labels of the truss.
|
82 |
+
"""
|
83 |
+
return self._node_labels
|
84 |
+
|
85 |
+
@property
|
86 |
+
def node_positions(self):
|
87 |
+
"""
|
88 |
+
Returns the positions of the nodes of the truss.
|
89 |
+
"""
|
90 |
+
return self._node_positions
|
91 |
+
|
92 |
+
@property
|
93 |
+
def members(self):
|
94 |
+
"""
|
95 |
+
Returns the members of the truss along with the start and end points.
|
96 |
+
"""
|
97 |
+
return self._members
|
98 |
+
|
99 |
+
@property
|
100 |
+
def member_labels(self):
|
101 |
+
"""
|
102 |
+
Returns the members of the truss along with the start and end points.
|
103 |
+
"""
|
104 |
+
return self._member_labels
|
105 |
+
|
106 |
+
@property
|
107 |
+
def supports(self):
|
108 |
+
"""
|
109 |
+
Returns the nodes with provided supports along with the kind of support provided i.e.
|
110 |
+
pinned or roller.
|
111 |
+
"""
|
112 |
+
return self._supports
|
113 |
+
|
114 |
+
@property
|
115 |
+
def loads(self):
|
116 |
+
"""
|
117 |
+
Returns the loads acting on the truss.
|
118 |
+
"""
|
119 |
+
return self._loads
|
120 |
+
|
121 |
+
@property
|
122 |
+
def reaction_loads(self):
|
123 |
+
"""
|
124 |
+
Returns the reaction forces for all supports which are all initialized to 0.
|
125 |
+
"""
|
126 |
+
return self._reaction_loads
|
127 |
+
|
128 |
+
@property
|
129 |
+
def internal_forces(self):
|
130 |
+
"""
|
131 |
+
Returns the internal forces for all members which are all initialized to 0.
|
132 |
+
"""
|
133 |
+
return self._internal_forces
|
134 |
+
|
135 |
+
def add_node(self, label, x, y):
|
136 |
+
"""
|
137 |
+
This method adds a node to the truss along with its name/label and its location.
|
138 |
+
|
139 |
+
Parameters
|
140 |
+
==========
|
141 |
+
label: String or a Symbol
|
142 |
+
The label for a node. It is the only way to identify a particular node.
|
143 |
+
|
144 |
+
x: Sympifyable
|
145 |
+
The x-coordinate of the position of the node.
|
146 |
+
|
147 |
+
y: Sympifyable
|
148 |
+
The y-coordinate of the position of the node.
|
149 |
+
|
150 |
+
Examples
|
151 |
+
========
|
152 |
+
|
153 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
154 |
+
>>> t = Truss()
|
155 |
+
>>> t.add_node('A', 0, 0)
|
156 |
+
>>> t.nodes
|
157 |
+
[('A', 0, 0)]
|
158 |
+
>>> t.add_node('B', 3, 0)
|
159 |
+
>>> t.nodes
|
160 |
+
[('A', 0, 0), ('B', 3, 0)]
|
161 |
+
"""
|
162 |
+
x = sympify(x)
|
163 |
+
y = sympify(y)
|
164 |
+
|
165 |
+
if label in self._node_labels:
|
166 |
+
raise ValueError("Node needs to have a unique label")
|
167 |
+
|
168 |
+
elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y):
|
169 |
+
raise ValueError("A node already exists at the given position")
|
170 |
+
|
171 |
+
else :
|
172 |
+
self._nodes.append((label, x, y))
|
173 |
+
self._node_labels.append(label)
|
174 |
+
self._node_positions.append((x, y))
|
175 |
+
self._node_position_x.append(x)
|
176 |
+
self._node_position_y.append(y)
|
177 |
+
self._node_coordinates[label] = [x, y]
|
178 |
+
|
179 |
+
def remove_node(self, label):
|
180 |
+
"""
|
181 |
+
This method removes a node from the truss.
|
182 |
+
|
183 |
+
Parameters
|
184 |
+
==========
|
185 |
+
label: String or Symbol
|
186 |
+
The label of the node to be removed.
|
187 |
+
|
188 |
+
Examples
|
189 |
+
========
|
190 |
+
|
191 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
192 |
+
>>> t = Truss()
|
193 |
+
>>> t.add_node('A', 0, 0)
|
194 |
+
>>> t.nodes
|
195 |
+
[('A', 0, 0)]
|
196 |
+
>>> t.add_node('B', 3, 0)
|
197 |
+
>>> t.nodes
|
198 |
+
[('A', 0, 0), ('B', 3, 0)]
|
199 |
+
>>> t.remove_node('A')
|
200 |
+
>>> t.nodes
|
201 |
+
[('B', 3, 0)]
|
202 |
+
"""
|
203 |
+
for i in range(len(self.nodes)):
|
204 |
+
if self._node_labels[i] == label:
|
205 |
+
x = self._node_position_x[i]
|
206 |
+
y = self._node_position_y[i]
|
207 |
+
|
208 |
+
if label not in self._node_labels:
|
209 |
+
raise ValueError("No such node exists in the truss")
|
210 |
+
|
211 |
+
else:
|
212 |
+
members_duplicate = self._members.copy()
|
213 |
+
for member in members_duplicate:
|
214 |
+
if label == self._members[member][0] or label == self._members[member][1]:
|
215 |
+
raise ValueError("The node given has members already attached to it")
|
216 |
+
self._nodes.remove((label, x, y))
|
217 |
+
self._node_labels.remove(label)
|
218 |
+
self._node_positions.remove((x, y))
|
219 |
+
self._node_position_x.remove(x)
|
220 |
+
self._node_position_y.remove(y)
|
221 |
+
if label in list(self._loads):
|
222 |
+
self._loads.pop(label)
|
223 |
+
if label in list(self._supports):
|
224 |
+
self._supports.pop(label)
|
225 |
+
self._node_coordinates.pop(label)
|
226 |
+
|
227 |
+
def add_member(self, label, start, end):
|
228 |
+
"""
|
229 |
+
This method adds a member between any two nodes in the given truss.
|
230 |
+
|
231 |
+
Parameters
|
232 |
+
==========
|
233 |
+
label: String or Symbol
|
234 |
+
The label for a member. It is the only way to identify a particular member.
|
235 |
+
|
236 |
+
start: String or Symbol
|
237 |
+
The label of the starting point/node of the member.
|
238 |
+
|
239 |
+
end: String or Symbol
|
240 |
+
The label of the ending point/node of the member.
|
241 |
+
|
242 |
+
Examples
|
243 |
+
========
|
244 |
+
|
245 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
246 |
+
>>> t = Truss()
|
247 |
+
>>> t.add_node('A', 0, 0)
|
248 |
+
>>> t.add_node('B', 3, 0)
|
249 |
+
>>> t.add_node('C', 2, 2)
|
250 |
+
>>> t.add_member('AB', 'A', 'B')
|
251 |
+
>>> t.members
|
252 |
+
{'AB': ['A', 'B']}
|
253 |
+
"""
|
254 |
+
|
255 |
+
if start not in self._node_labels or end not in self._node_labels or start==end:
|
256 |
+
raise ValueError("The start and end points of the member must be unique nodes")
|
257 |
+
|
258 |
+
elif label in list(self._members):
|
259 |
+
raise ValueError("A member with the same label already exists for the truss")
|
260 |
+
|
261 |
+
elif self._nodes_occupied.get((start, end)):
|
262 |
+
raise ValueError("A member already exists between the two nodes")
|
263 |
+
|
264 |
+
else:
|
265 |
+
self._members[label] = [start, end]
|
266 |
+
self._nodes_occupied[start, end] = True
|
267 |
+
self._nodes_occupied[end, start] = True
|
268 |
+
self._internal_forces[label] = 0
|
269 |
+
|
270 |
+
def remove_member(self, label):
|
271 |
+
"""
|
272 |
+
This method removes a member from the given truss.
|
273 |
+
|
274 |
+
Parameters
|
275 |
+
==========
|
276 |
+
label: String or Symbol
|
277 |
+
The label for the member to be removed.
|
278 |
+
|
279 |
+
Examples
|
280 |
+
========
|
281 |
+
|
282 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
283 |
+
>>> t = Truss()
|
284 |
+
>>> t.add_node('A', 0, 0)
|
285 |
+
>>> t.add_node('B', 3, 0)
|
286 |
+
>>> t.add_node('C', 2, 2)
|
287 |
+
>>> t.add_member('AB', 'A', 'B')
|
288 |
+
>>> t.add_member('AC', 'A', 'C')
|
289 |
+
>>> t.add_member('BC', 'B', 'C')
|
290 |
+
>>> t.members
|
291 |
+
{'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']}
|
292 |
+
>>> t.remove_member('AC')
|
293 |
+
>>> t.members
|
294 |
+
{'AB': ['A', 'B'], 'BC': ['B', 'C']}
|
295 |
+
"""
|
296 |
+
if label not in list(self._members):
|
297 |
+
raise ValueError("No such member exists in the Truss")
|
298 |
+
|
299 |
+
else:
|
300 |
+
self._nodes_occupied.pop((self._members[label][0], self._members[label][1]))
|
301 |
+
self._nodes_occupied.pop((self._members[label][1], self._members[label][0]))
|
302 |
+
self._members.pop(label)
|
303 |
+
self._internal_forces.pop(label)
|
304 |
+
|
305 |
+
def change_node_label(self, label, new_label):
|
306 |
+
"""
|
307 |
+
This method changes the label of a node.
|
308 |
+
|
309 |
+
Parameters
|
310 |
+
==========
|
311 |
+
label: String or Symbol
|
312 |
+
The label of the node for which the label has
|
313 |
+
to be changed.
|
314 |
+
|
315 |
+
new_label: String or Symbol
|
316 |
+
The new label of the node.
|
317 |
+
|
318 |
+
Examples
|
319 |
+
========
|
320 |
+
|
321 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
322 |
+
>>> t = Truss()
|
323 |
+
>>> t.add_node('A', 0, 0)
|
324 |
+
>>> t.add_node('B', 3, 0)
|
325 |
+
>>> t.nodes
|
326 |
+
[('A', 0, 0), ('B', 3, 0)]
|
327 |
+
>>> t.change_node_label('A', 'C')
|
328 |
+
>>> t.nodes
|
329 |
+
[('C', 0, 0), ('B', 3, 0)]
|
330 |
+
"""
|
331 |
+
if label not in self._node_labels:
|
332 |
+
raise ValueError("No such node exists for the Truss")
|
333 |
+
elif new_label in self._node_labels:
|
334 |
+
raise ValueError("A node with the given label already exists")
|
335 |
+
else:
|
336 |
+
for node in self._nodes:
|
337 |
+
if node[0] == label:
|
338 |
+
self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2])
|
339 |
+
self._node_labels[self._node_labels.index(node[0])] = new_label
|
340 |
+
self._node_coordinates[new_label] = self._node_coordinates[label]
|
341 |
+
self._node_coordinates.pop(label)
|
342 |
+
if node[0] in list(self._supports):
|
343 |
+
self._supports[new_label] = self._supports[node[0]]
|
344 |
+
self._supports.pop(node[0])
|
345 |
+
if new_label in list(self._supports):
|
346 |
+
if self._supports[new_label] == 'pinned':
|
347 |
+
if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads):
|
348 |
+
self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x']
|
349 |
+
self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y']
|
350 |
+
self._reaction_loads.pop('R_'+str(label)+'_x')
|
351 |
+
self._reaction_loads.pop('R_'+str(label)+'_y')
|
352 |
+
self._loads[new_label] = self._loads[label]
|
353 |
+
for load in self._loads[new_label]:
|
354 |
+
if load[1] == 90:
|
355 |
+
load[0] -= Symbol('R_'+str(label)+'_y')
|
356 |
+
if load[0] == 0:
|
357 |
+
self._loads[label].remove(load)
|
358 |
+
break
|
359 |
+
for load in self._loads[new_label]:
|
360 |
+
if load[1] == 0:
|
361 |
+
load[0] -= Symbol('R_'+str(label)+'_x')
|
362 |
+
if load[0] == 0:
|
363 |
+
self._loads[label].remove(load)
|
364 |
+
break
|
365 |
+
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0)
|
366 |
+
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
|
367 |
+
self._loads.pop(label)
|
368 |
+
elif self._supports[new_label] == 'roller':
|
369 |
+
self._loads[new_label] = self._loads[label]
|
370 |
+
for load in self._loads[label]:
|
371 |
+
if load[1] == 90:
|
372 |
+
load[0] -= Symbol('R_'+str(label)+'_y')
|
373 |
+
if load[0] == 0:
|
374 |
+
self._loads[label].remove(load)
|
375 |
+
break
|
376 |
+
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
|
377 |
+
self._loads.pop(label)
|
378 |
+
else:
|
379 |
+
if label in list(self._loads):
|
380 |
+
self._loads[new_label] = self._loads[label]
|
381 |
+
self._loads.pop(label)
|
382 |
+
for member in list(self._members):
|
383 |
+
if self._members[member][0] == node[0]:
|
384 |
+
self._members[member][0] = new_label
|
385 |
+
self._nodes_occupied[(new_label, self._members[member][1])] = True
|
386 |
+
self._nodes_occupied[(self._members[member][1], new_label)] = True
|
387 |
+
self._nodes_occupied.pop((label, self._members[member][1]))
|
388 |
+
self._nodes_occupied.pop((self._members[member][1], label))
|
389 |
+
elif self._members[member][1] == node[0]:
|
390 |
+
self._members[member][1] = new_label
|
391 |
+
self._nodes_occupied[(self._members[member][0], new_label)] = True
|
392 |
+
self._nodes_occupied[(new_label, self._members[member][0])] = True
|
393 |
+
self._nodes_occupied.pop((self._members[member][0], label))
|
394 |
+
self._nodes_occupied.pop((label, self._members[member][0]))
|
395 |
+
|
396 |
+
def change_member_label(self, label, new_label):
|
397 |
+
"""
|
398 |
+
This method changes the label of a member.
|
399 |
+
|
400 |
+
Parameters
|
401 |
+
==========
|
402 |
+
label: String or Symbol
|
403 |
+
The label of the member for which the label has
|
404 |
+
to be changed.
|
405 |
+
|
406 |
+
new_label: String or Symbol
|
407 |
+
The new label of the member.
|
408 |
+
|
409 |
+
Examples
|
410 |
+
========
|
411 |
+
|
412 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
413 |
+
>>> t = Truss()
|
414 |
+
>>> t.add_node('A', 0, 0)
|
415 |
+
>>> t.add_node('B', 3, 0)
|
416 |
+
>>> t.nodes
|
417 |
+
[('A', 0, 0), ('B', 3, 0)]
|
418 |
+
>>> t.change_node_label('A', 'C')
|
419 |
+
>>> t.nodes
|
420 |
+
[('C', 0, 0), ('B', 3, 0)]
|
421 |
+
>>> t.add_member('BC', 'B', 'C')
|
422 |
+
>>> t.members
|
423 |
+
{'BC': ['B', 'C']}
|
424 |
+
>>> t.change_member_label('BC', 'BC_new')
|
425 |
+
>>> t.members
|
426 |
+
{'BC_new': ['B', 'C']}
|
427 |
+
"""
|
428 |
+
if label not in list(self._members):
|
429 |
+
raise ValueError("No such member exists for the Truss")
|
430 |
+
|
431 |
+
else:
|
432 |
+
members_duplicate = list(self._members).copy()
|
433 |
+
for member in members_duplicate:
|
434 |
+
if member == label:
|
435 |
+
self._members[new_label] = [self._members[member][0], self._members[member][1]]
|
436 |
+
self._members.pop(label)
|
437 |
+
self._internal_forces[new_label] = self._internal_forces[label]
|
438 |
+
self._internal_forces.pop(label)
|
439 |
+
|
440 |
+
def apply_load(self, location, magnitude, direction):
|
441 |
+
"""
|
442 |
+
This method applies an external load at a particular node
|
443 |
+
|
444 |
+
Parameters
|
445 |
+
==========
|
446 |
+
location: String or Symbol
|
447 |
+
Label of the Node at which load is applied.
|
448 |
+
|
449 |
+
magnitude: Sympifyable
|
450 |
+
Magnitude of the load applied. It must always be positive and any changes in
|
451 |
+
the direction of the load are not reflected here.
|
452 |
+
|
453 |
+
direction: Sympifyable
|
454 |
+
The angle, in degrees, that the load vector makes with the horizontal
|
455 |
+
in the counter-clockwise direction. It takes the values 0 to 360,
|
456 |
+
inclusive.
|
457 |
+
|
458 |
+
Examples
|
459 |
+
========
|
460 |
+
|
461 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
462 |
+
>>> from sympy import symbols
|
463 |
+
>>> t = Truss()
|
464 |
+
>>> t.add_node('A', 0, 0)
|
465 |
+
>>> t.add_node('B', 3, 0)
|
466 |
+
>>> P = symbols('P')
|
467 |
+
>>> t.apply_load('A', P, 90)
|
468 |
+
>>> t.apply_load('A', P/2, 45)
|
469 |
+
>>> t.apply_load('A', P/4, 90)
|
470 |
+
>>> t.loads
|
471 |
+
{'A': [[P, 90], [P/2, 45], [P/4, 90]]}
|
472 |
+
"""
|
473 |
+
magnitude = sympify(magnitude)
|
474 |
+
direction = sympify(direction)
|
475 |
+
|
476 |
+
if location not in self.node_labels:
|
477 |
+
raise ValueError("Load must be applied at a known node")
|
478 |
+
|
479 |
+
else:
|
480 |
+
if location in list(self._loads):
|
481 |
+
self._loads[location].append([magnitude, direction])
|
482 |
+
else:
|
483 |
+
self._loads[location] = [[magnitude, direction]]
|
484 |
+
|
485 |
+
def remove_load(self, location, magnitude, direction):
|
486 |
+
"""
|
487 |
+
This method removes an already
|
488 |
+
present external load at a particular node
|
489 |
+
|
490 |
+
Parameters
|
491 |
+
==========
|
492 |
+
location: String or Symbol
|
493 |
+
Label of the Node at which load is applied and is to be removed.
|
494 |
+
|
495 |
+
magnitude: Sympifyable
|
496 |
+
Magnitude of the load applied.
|
497 |
+
|
498 |
+
direction: Sympifyable
|
499 |
+
The angle, in degrees, that the load vector makes with the horizontal
|
500 |
+
in the counter-clockwise direction. It takes the values 0 to 360,
|
501 |
+
inclusive.
|
502 |
+
|
503 |
+
Examples
|
504 |
+
========
|
505 |
+
|
506 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
507 |
+
>>> from sympy import symbols
|
508 |
+
>>> t = Truss()
|
509 |
+
>>> t.add_node('A', 0, 0)
|
510 |
+
>>> t.add_node('B', 3, 0)
|
511 |
+
>>> P = symbols('P')
|
512 |
+
>>> t.apply_load('A', P, 90)
|
513 |
+
>>> t.apply_load('A', P/2, 45)
|
514 |
+
>>> t.apply_load('A', P/4, 90)
|
515 |
+
>>> t.loads
|
516 |
+
{'A': [[P, 90], [P/2, 45], [P/4, 90]]}
|
517 |
+
>>> t.remove_load('A', P/4, 90)
|
518 |
+
>>> t.loads
|
519 |
+
{'A': [[P, 90], [P/2, 45]]}
|
520 |
+
"""
|
521 |
+
magnitude = sympify(magnitude)
|
522 |
+
direction = sympify(direction)
|
523 |
+
|
524 |
+
if location not in self.node_labels:
|
525 |
+
raise ValueError("Load must be removed from a known node")
|
526 |
+
|
527 |
+
else:
|
528 |
+
if [magnitude, direction] not in self._loads[location]:
|
529 |
+
raise ValueError("No load of this magnitude and direction has been applied at this node")
|
530 |
+
else:
|
531 |
+
self._loads[location].remove([magnitude, direction])
|
532 |
+
if self._loads[location] == []:
|
533 |
+
self._loads.pop(location)
|
534 |
+
|
535 |
+
def apply_support(self, location, type):
|
536 |
+
"""
|
537 |
+
This method adds a pinned or roller support at a particular node
|
538 |
+
|
539 |
+
Parameters
|
540 |
+
==========
|
541 |
+
|
542 |
+
location: String or Symbol
|
543 |
+
Label of the Node at which support is added.
|
544 |
+
|
545 |
+
type: String
|
546 |
+
Type of the support being provided at the node.
|
547 |
+
|
548 |
+
Examples
|
549 |
+
========
|
550 |
+
|
551 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
552 |
+
>>> t = Truss()
|
553 |
+
>>> t.add_node('A', 0, 0)
|
554 |
+
>>> t.add_node('B', 3, 0)
|
555 |
+
>>> t.apply_support('A', 'pinned')
|
556 |
+
>>> t.supports
|
557 |
+
{'A': 'pinned'}
|
558 |
+
"""
|
559 |
+
if location not in self._node_labels:
|
560 |
+
raise ValueError("Support must be added on a known node")
|
561 |
+
|
562 |
+
else:
|
563 |
+
if location not in list(self._supports):
|
564 |
+
if type == 'pinned':
|
565 |
+
self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
|
566 |
+
self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
|
567 |
+
elif type == 'roller':
|
568 |
+
self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
|
569 |
+
elif self._supports[location] == 'pinned':
|
570 |
+
if type == 'roller':
|
571 |
+
self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
|
572 |
+
elif self._supports[location] == 'roller':
|
573 |
+
if type == 'pinned':
|
574 |
+
self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
|
575 |
+
self._supports[location] = type
|
576 |
+
|
577 |
+
def remove_support(self, location):
|
578 |
+
"""
|
579 |
+
This method removes support from a particular node
|
580 |
+
|
581 |
+
Parameters
|
582 |
+
==========
|
583 |
+
|
584 |
+
location: String or Symbol
|
585 |
+
Label of the Node at which support is to be removed.
|
586 |
+
|
587 |
+
Examples
|
588 |
+
========
|
589 |
+
|
590 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
591 |
+
>>> t = Truss()
|
592 |
+
>>> t.add_node('A', 0, 0)
|
593 |
+
>>> t.add_node('B', 3, 0)
|
594 |
+
>>> t.apply_support('A', 'pinned')
|
595 |
+
>>> t.supports
|
596 |
+
{'A': 'pinned'}
|
597 |
+
>>> t.remove_support('A')
|
598 |
+
>>> t.supports
|
599 |
+
{}
|
600 |
+
"""
|
601 |
+
if location not in self._node_labels:
|
602 |
+
raise ValueError("No such node exists in the Truss")
|
603 |
+
|
604 |
+
elif location not in list(self._supports):
|
605 |
+
raise ValueError("No support has been added to the given node")
|
606 |
+
|
607 |
+
else:
|
608 |
+
if self._supports[location] == 'pinned':
|
609 |
+
self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
|
610 |
+
self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
|
611 |
+
elif self._supports[location] == 'roller':
|
612 |
+
self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
|
613 |
+
self._supports.pop(location)
|
614 |
+
|
615 |
+
def solve(self):
|
616 |
+
"""
|
617 |
+
This method solves for all reaction forces of all supports and all internal forces
|
618 |
+
of all the members in the truss, provided the Truss is solvable.
|
619 |
+
|
620 |
+
A Truss is solvable if the following condition is met,
|
621 |
+
|
622 |
+
2n >= r + m
|
623 |
+
|
624 |
+
Where n is the number of nodes, r is the number of reaction forces, where each pinned
|
625 |
+
support has 2 reaction forces and each roller has 1, and m is the number of members.
|
626 |
+
|
627 |
+
The given condition is derived from the fact that a system of equations is solvable
|
628 |
+
only when the number of variables is lesser than or equal to the number of equations.
|
629 |
+
Equilibrium Equations in x and y directions give two equations per node giving 2n number
|
630 |
+
equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m.
|
631 |
+
The number of variables is simply the sum of the number of reaction forces and member
|
632 |
+
forces.
|
633 |
+
|
634 |
+
.. note::
|
635 |
+
The sign convention for the internal forces present in a member revolves around whether each
|
636 |
+
force is compressive or tensile. While forming equations for each node, internal force due
|
637 |
+
to a member on the node is assumed to be away from the node i.e. each force is assumed to
|
638 |
+
be compressive by default. Hence, a positive value for an internal force implies the
|
639 |
+
presence of compressive force in the member and a negative value implies a tensile force.
|
640 |
+
|
641 |
+
Examples
|
642 |
+
========
|
643 |
+
|
644 |
+
>>> from sympy.physics.continuum_mechanics.truss import Truss
|
645 |
+
>>> t = Truss()
|
646 |
+
>>> t.add_node("node_1", 0, 0)
|
647 |
+
>>> t.add_node("node_2", 6, 0)
|
648 |
+
>>> t.add_node("node_3", 2, 2)
|
649 |
+
>>> t.add_node("node_4", 2, 0)
|
650 |
+
>>> t.add_member("member_1", "node_1", "node_4")
|
651 |
+
>>> t.add_member("member_2", "node_2", "node_4")
|
652 |
+
>>> t.add_member("member_3", "node_1", "node_3")
|
653 |
+
>>> t.add_member("member_4", "node_2", "node_3")
|
654 |
+
>>> t.add_member("member_5", "node_3", "node_4")
|
655 |
+
>>> t.apply_load("node_4", magnitude=10, direction=270)
|
656 |
+
>>> t.apply_support("node_1", type="pinned")
|
657 |
+
>>> t.apply_support("node_2", type="roller")
|
658 |
+
>>> t.solve()
|
659 |
+
>>> t.reaction_loads
|
660 |
+
{'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3}
|
661 |
+
>>> t.internal_forces
|
662 |
+
{'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10}
|
663 |
+
"""
|
664 |
+
count_reaction_loads = 0
|
665 |
+
for node in self._nodes:
|
666 |
+
if node[0] in list(self._supports):
|
667 |
+
if self._supports[node[0]]=='pinned':
|
668 |
+
count_reaction_loads += 2
|
669 |
+
elif self._supports[node[0]]=='roller':
|
670 |
+
count_reaction_loads += 1
|
671 |
+
if 2*len(self._nodes) != len(self._members) + count_reaction_loads:
|
672 |
+
raise ValueError("The given truss cannot be solved")
|
673 |
+
coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))]
|
674 |
+
load_matrix = zeros(2*len(self.nodes), 1)
|
675 |
+
load_matrix_row = 0
|
676 |
+
for node in self._nodes:
|
677 |
+
if node[0] in list(self._loads):
|
678 |
+
for load in self._loads[node[0]]:
|
679 |
+
if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'):
|
680 |
+
load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180)
|
681 |
+
load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180)
|
682 |
+
load_matrix_row += 2
|
683 |
+
cols = 0
|
684 |
+
row = 0
|
685 |
+
for node in self._nodes:
|
686 |
+
if node[0] in list(self._supports):
|
687 |
+
if self._supports[node[0]]=='pinned':
|
688 |
+
coefficients_matrix[row][cols] += 1
|
689 |
+
coefficients_matrix[row+1][cols+1] += 1
|
690 |
+
cols += 2
|
691 |
+
elif self._supports[node[0]]=='roller':
|
692 |
+
coefficients_matrix[row+1][cols] += 1
|
693 |
+
cols += 1
|
694 |
+
row += 2
|
695 |
+
for member in list(self._members):
|
696 |
+
start = self._members[member][0]
|
697 |
+
end = self._members[member][1]
|
698 |
+
length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2)
|
699 |
+
start_index = self._node_labels.index(start)
|
700 |
+
end_index = self._node_labels.index(end)
|
701 |
+
horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length
|
702 |
+
vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length
|
703 |
+
horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length
|
704 |
+
vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length
|
705 |
+
coefficients_matrix[start_index*2][cols] += horizontal_component_start
|
706 |
+
coefficients_matrix[start_index*2+1][cols] += vertical_component_start
|
707 |
+
coefficients_matrix[end_index*2][cols] += horizontal_component_end
|
708 |
+
coefficients_matrix[end_index*2+1][cols] += vertical_component_end
|
709 |
+
cols += 1
|
710 |
+
forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix
|
711 |
+
self._reaction_loads = {}
|
712 |
+
i = 0
|
713 |
+
min_load = inf
|
714 |
+
for node in self._nodes:
|
715 |
+
if node[0] in list(self._loads):
|
716 |
+
for load in self._loads[node[0]]:
|
717 |
+
if type(load[0]) not in [Symbol, Mul, Add]:
|
718 |
+
min_load = min(min_load, load[0])
|
719 |
+
for j in range(len(forces_matrix)):
|
720 |
+
if type(forces_matrix[j]) not in [Symbol, Mul, Add]:
|
721 |
+
if abs(forces_matrix[j]/min_load) <1E-10:
|
722 |
+
forces_matrix[j] = 0
|
723 |
+
for node in self._nodes:
|
724 |
+
if node[0] in list(self._supports):
|
725 |
+
if self._supports[node[0]]=='pinned':
|
726 |
+
self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i]
|
727 |
+
self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1]
|
728 |
+
i += 2
|
729 |
+
elif self._supports[node[0]]=='roller':
|
730 |
+
self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i]
|
731 |
+
i += 1
|
732 |
+
for member in list(self._members):
|
733 |
+
self._internal_forces[member] = forces_matrix[i]
|
734 |
+
i += 1
|
735 |
+
return
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.01 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc
ADDED
Binary file (18.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc
ADDED
Binary file (23.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc
ADDED
Binary file (79.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc
ADDED
Binary file (8.78 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc
ADDED
Binary file (25.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc
ADDED
Binary file (16.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc
ADDED
Binary file (10.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc
ADDED
Binary file (1.59 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc
ADDED
Binary file (5.59 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc
ADDED
Binary file (8.46 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc
ADDED
Binary file (11.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc
ADDED
Binary file (16.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (202 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_body.cpython-310.pyc
ADDED
Binary file (9.44 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_functions.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc
ADDED
Binary file (8.35 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc
ADDED
Binary file (12.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc
ADDED
Binary file (11.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc
ADDED
Binary file (5.45 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc
ADDED
Binary file (2.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange.cpython-310.pyc
ADDED
Binary file (6.15 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_linearize.cpython-310.pyc
ADDED
Binary file (9.15 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_method.cpython-310.pyc
ADDED
Binary file (568 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_rigidbody.cpython-310.pyc
ADDED
Binary file (5.73 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_body.py
ADDED
@@ -0,0 +1,319 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.backend import (Symbol, symbols, sin, cos, Matrix, zeros,
|
2 |
+
_simplify_matrix)
|
3 |
+
from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols, Dyadic
|
4 |
+
from sympy.physics.mechanics import inertia, Body
|
5 |
+
from sympy.testing.pytest import raises
|
6 |
+
|
7 |
+
|
8 |
+
def test_default():
|
9 |
+
body = Body('body')
|
10 |
+
assert body.name == 'body'
|
11 |
+
assert body.loads == []
|
12 |
+
point = Point('body_masscenter')
|
13 |
+
point.set_vel(body.frame, 0)
|
14 |
+
com = body.masscenter
|
15 |
+
frame = body.frame
|
16 |
+
assert com.vel(frame) == point.vel(frame)
|
17 |
+
assert body.mass == Symbol('body_mass')
|
18 |
+
ixx, iyy, izz = symbols('body_ixx body_iyy body_izz')
|
19 |
+
ixy, iyz, izx = symbols('body_ixy body_iyz body_izx')
|
20 |
+
assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx),
|
21 |
+
body.masscenter)
|
22 |
+
|
23 |
+
|
24 |
+
def test_custom_rigid_body():
|
25 |
+
# Body with RigidBody.
|
26 |
+
rigidbody_masscenter = Point('rigidbody_masscenter')
|
27 |
+
rigidbody_mass = Symbol('rigidbody_mass')
|
28 |
+
rigidbody_frame = ReferenceFrame('rigidbody_frame')
|
29 |
+
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
|
30 |
+
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
|
31 |
+
rigidbody_frame, body_inertia)
|
32 |
+
com = rigid_body.masscenter
|
33 |
+
frame = rigid_body.frame
|
34 |
+
rigidbody_masscenter.set_vel(rigidbody_frame, 0)
|
35 |
+
assert com.vel(frame) == rigidbody_masscenter.vel(frame)
|
36 |
+
assert com.pos_from(com) == rigidbody_masscenter.pos_from(com)
|
37 |
+
|
38 |
+
assert rigid_body.mass == rigidbody_mass
|
39 |
+
assert rigid_body.inertia == (body_inertia, rigidbody_masscenter)
|
40 |
+
|
41 |
+
assert rigid_body.is_rigidbody
|
42 |
+
|
43 |
+
assert hasattr(rigid_body, 'masscenter')
|
44 |
+
assert hasattr(rigid_body, 'mass')
|
45 |
+
assert hasattr(rigid_body, 'frame')
|
46 |
+
assert hasattr(rigid_body, 'inertia')
|
47 |
+
|
48 |
+
|
49 |
+
def test_particle_body():
|
50 |
+
# Body with Particle
|
51 |
+
particle_masscenter = Point('particle_masscenter')
|
52 |
+
particle_mass = Symbol('particle_mass')
|
53 |
+
particle_frame = ReferenceFrame('particle_frame')
|
54 |
+
particle_body = Body('particle_body', particle_masscenter, particle_mass,
|
55 |
+
particle_frame)
|
56 |
+
com = particle_body.masscenter
|
57 |
+
frame = particle_body.frame
|
58 |
+
particle_masscenter.set_vel(particle_frame, 0)
|
59 |
+
assert com.vel(frame) == particle_masscenter.vel(frame)
|
60 |
+
assert com.pos_from(com) == particle_masscenter.pos_from(com)
|
61 |
+
|
62 |
+
assert particle_body.mass == particle_mass
|
63 |
+
assert not hasattr(particle_body, "_inertia")
|
64 |
+
assert hasattr(particle_body, 'frame')
|
65 |
+
assert hasattr(particle_body, 'masscenter')
|
66 |
+
assert hasattr(particle_body, 'mass')
|
67 |
+
assert particle_body.inertia == (Dyadic(0), particle_body.masscenter)
|
68 |
+
assert particle_body.central_inertia == Dyadic(0)
|
69 |
+
assert not particle_body.is_rigidbody
|
70 |
+
|
71 |
+
particle_body.central_inertia = inertia(particle_frame, 1, 1, 1)
|
72 |
+
assert particle_body.central_inertia == inertia(particle_frame, 1, 1, 1)
|
73 |
+
assert particle_body.is_rigidbody
|
74 |
+
|
75 |
+
particle_body = Body('particle_body', mass=particle_mass)
|
76 |
+
assert not particle_body.is_rigidbody
|
77 |
+
point = particle_body.masscenter.locatenew('point', particle_body.x)
|
78 |
+
point_inertia = particle_mass * inertia(particle_body.frame, 0, 1, 1)
|
79 |
+
particle_body.inertia = (point_inertia, point)
|
80 |
+
assert particle_body.inertia == (point_inertia, point)
|
81 |
+
assert particle_body.central_inertia == Dyadic(0)
|
82 |
+
assert particle_body.is_rigidbody
|
83 |
+
|
84 |
+
|
85 |
+
def test_particle_body_add_force():
|
86 |
+
# Body with Particle
|
87 |
+
particle_masscenter = Point('particle_masscenter')
|
88 |
+
particle_mass = Symbol('particle_mass')
|
89 |
+
particle_frame = ReferenceFrame('particle_frame')
|
90 |
+
particle_body = Body('particle_body', particle_masscenter, particle_mass,
|
91 |
+
particle_frame)
|
92 |
+
|
93 |
+
a = Symbol('a')
|
94 |
+
force_vector = a * particle_body.frame.x
|
95 |
+
particle_body.apply_force(force_vector, particle_body.masscenter)
|
96 |
+
assert len(particle_body.loads) == 1
|
97 |
+
point = particle_body.masscenter.locatenew(
|
98 |
+
particle_body._name + '_point0', 0)
|
99 |
+
point.set_vel(particle_body.frame, 0)
|
100 |
+
force_point = particle_body.loads[0][0]
|
101 |
+
|
102 |
+
frame = particle_body.frame
|
103 |
+
assert force_point.vel(frame) == point.vel(frame)
|
104 |
+
assert force_point.pos_from(force_point) == point.pos_from(force_point)
|
105 |
+
|
106 |
+
assert particle_body.loads[0][1] == force_vector
|
107 |
+
|
108 |
+
|
109 |
+
def test_body_add_force():
|
110 |
+
# Body with RigidBody.
|
111 |
+
rigidbody_masscenter = Point('rigidbody_masscenter')
|
112 |
+
rigidbody_mass = Symbol('rigidbody_mass')
|
113 |
+
rigidbody_frame = ReferenceFrame('rigidbody_frame')
|
114 |
+
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
|
115 |
+
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
|
116 |
+
rigidbody_frame, body_inertia)
|
117 |
+
|
118 |
+
l = Symbol('l')
|
119 |
+
Fa = Symbol('Fa')
|
120 |
+
point = rigid_body.masscenter.locatenew(
|
121 |
+
'rigidbody_body_point0',
|
122 |
+
l * rigid_body.frame.x)
|
123 |
+
point.set_vel(rigid_body.frame, 0)
|
124 |
+
force_vector = Fa * rigid_body.frame.z
|
125 |
+
# apply_force with point
|
126 |
+
rigid_body.apply_force(force_vector, point)
|
127 |
+
assert len(rigid_body.loads) == 1
|
128 |
+
force_point = rigid_body.loads[0][0]
|
129 |
+
frame = rigid_body.frame
|
130 |
+
assert force_point.vel(frame) == point.vel(frame)
|
131 |
+
assert force_point.pos_from(force_point) == point.pos_from(force_point)
|
132 |
+
assert rigid_body.loads[0][1] == force_vector
|
133 |
+
# apply_force without point
|
134 |
+
rigid_body.apply_force(force_vector)
|
135 |
+
assert len(rigid_body.loads) == 2
|
136 |
+
assert rigid_body.loads[1][1] == force_vector
|
137 |
+
# passing something else than point
|
138 |
+
raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0))
|
139 |
+
raises(TypeError, lambda: rigid_body.apply_force(0))
|
140 |
+
|
141 |
+
def test_body_add_torque():
|
142 |
+
body = Body('body')
|
143 |
+
torque_vector = body.frame.x
|
144 |
+
body.apply_torque(torque_vector)
|
145 |
+
|
146 |
+
assert len(body.loads) == 1
|
147 |
+
assert body.loads[0] == (body.frame, torque_vector)
|
148 |
+
raises(TypeError, lambda: body.apply_torque(0))
|
149 |
+
|
150 |
+
def test_body_masscenter_vel():
|
151 |
+
A = Body('A')
|
152 |
+
N = ReferenceFrame('N')
|
153 |
+
B = Body('B', frame=N)
|
154 |
+
A.masscenter.set_vel(N, N.z)
|
155 |
+
assert A.masscenter_vel(B) == N.z
|
156 |
+
assert A.masscenter_vel(N) == N.z
|
157 |
+
|
158 |
+
def test_body_ang_vel():
|
159 |
+
A = Body('A')
|
160 |
+
N = ReferenceFrame('N')
|
161 |
+
B = Body('B', frame=N)
|
162 |
+
A.frame.set_ang_vel(N, N.y)
|
163 |
+
assert A.ang_vel_in(B) == N.y
|
164 |
+
assert B.ang_vel_in(A) == -N.y
|
165 |
+
assert A.ang_vel_in(N) == N.y
|
166 |
+
|
167 |
+
def test_body_dcm():
|
168 |
+
A = Body('A')
|
169 |
+
B = Body('B')
|
170 |
+
A.frame.orient_axis(B.frame, B.frame.z, 10)
|
171 |
+
assert A.dcm(B) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
|
172 |
+
assert A.dcm(B.frame) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
|
173 |
+
|
174 |
+
def test_body_axis():
|
175 |
+
N = ReferenceFrame('N')
|
176 |
+
B = Body('B', frame=N)
|
177 |
+
assert B.x == N.x
|
178 |
+
assert B.y == N.y
|
179 |
+
assert B.z == N.z
|
180 |
+
|
181 |
+
def test_apply_force_multiple_one_point():
|
182 |
+
a, b = symbols('a b')
|
183 |
+
P = Point('P')
|
184 |
+
B = Body('B')
|
185 |
+
f1 = a*B.x
|
186 |
+
f2 = b*B.y
|
187 |
+
B.apply_force(f1, P)
|
188 |
+
assert B.loads == [(P, f1)]
|
189 |
+
B.apply_force(f2, P)
|
190 |
+
assert B.loads == [(P, f1+f2)]
|
191 |
+
|
192 |
+
def test_apply_force():
|
193 |
+
f, g = symbols('f g')
|
194 |
+
q, x, v1, v2 = dynamicsymbols('q x v1 v2')
|
195 |
+
P1 = Point('P1')
|
196 |
+
P2 = Point('P2')
|
197 |
+
B1 = Body('B1')
|
198 |
+
B2 = Body('B2')
|
199 |
+
N = ReferenceFrame('N')
|
200 |
+
|
201 |
+
P1.set_vel(B1.frame, v1*B1.x)
|
202 |
+
P2.set_vel(B2.frame, v2*B2.x)
|
203 |
+
force = f*q*N.z # time varying force
|
204 |
+
|
205 |
+
B1.apply_force(force, P1, B2, P2) #applying equal and opposite force on moving points
|
206 |
+
assert B1.loads == [(P1, force)]
|
207 |
+
assert B2.loads == [(P2, -force)]
|
208 |
+
|
209 |
+
g1 = B1.mass*g*N.y
|
210 |
+
g2 = B2.mass*g*N.y
|
211 |
+
|
212 |
+
B1.apply_force(g1) #applying gravity on B1 masscenter
|
213 |
+
B2.apply_force(g2) #applying gravity on B2 masscenter
|
214 |
+
|
215 |
+
assert B1.loads == [(P1,force), (B1.masscenter, g1)]
|
216 |
+
assert B2.loads == [(P2, -force), (B2.masscenter, g2)]
|
217 |
+
|
218 |
+
force2 = x*N.x
|
219 |
+
|
220 |
+
B1.apply_force(force2, reaction_body=B2) #Applying time varying force on masscenter
|
221 |
+
|
222 |
+
assert B1.loads == [(P1, force), (B1.masscenter, force2+g1)]
|
223 |
+
assert B2.loads == [(P2, -force), (B2.masscenter, -force2+g2)]
|
224 |
+
|
225 |
+
def test_apply_torque():
|
226 |
+
t = symbols('t')
|
227 |
+
q = dynamicsymbols('q')
|
228 |
+
B1 = Body('B1')
|
229 |
+
B2 = Body('B2')
|
230 |
+
N = ReferenceFrame('N')
|
231 |
+
torque = t*q*N.x
|
232 |
+
|
233 |
+
B1.apply_torque(torque, B2) #Applying equal and opposite torque
|
234 |
+
assert B1.loads == [(B1.frame, torque)]
|
235 |
+
assert B2.loads == [(B2.frame, -torque)]
|
236 |
+
|
237 |
+
torque2 = t*N.y
|
238 |
+
B1.apply_torque(torque2)
|
239 |
+
assert B1.loads == [(B1.frame, torque+torque2)]
|
240 |
+
|
241 |
+
def test_clear_load():
|
242 |
+
a = symbols('a')
|
243 |
+
P = Point('P')
|
244 |
+
B = Body('B')
|
245 |
+
force = a*B.z
|
246 |
+
B.apply_force(force, P)
|
247 |
+
assert B.loads == [(P, force)]
|
248 |
+
B.clear_loads()
|
249 |
+
assert B.loads == []
|
250 |
+
|
251 |
+
def test_remove_load():
|
252 |
+
P1 = Point('P1')
|
253 |
+
P2 = Point('P2')
|
254 |
+
B = Body('B')
|
255 |
+
f1 = B.x
|
256 |
+
f2 = B.y
|
257 |
+
B.apply_force(f1, P1)
|
258 |
+
B.apply_force(f2, P2)
|
259 |
+
assert B.loads == [(P1, f1), (P2, f2)]
|
260 |
+
B.remove_load(P2)
|
261 |
+
assert B.loads == [(P1, f1)]
|
262 |
+
B.apply_torque(f1.cross(f2))
|
263 |
+
assert B.loads == [(P1, f1), (B.frame, f1.cross(f2))]
|
264 |
+
B.remove_load()
|
265 |
+
assert B.loads == [(P1, f1)]
|
266 |
+
|
267 |
+
def test_apply_loads_on_multi_degree_freedom_holonomic_system():
|
268 |
+
"""Example based on: https://pydy.readthedocs.io/en/latest/examples/multidof-holonomic.html"""
|
269 |
+
W = Body('W') #Wall
|
270 |
+
B = Body('B') #Block
|
271 |
+
P = Body('P') #Pendulum
|
272 |
+
b = Body('b') #bob
|
273 |
+
q1, q2 = dynamicsymbols('q1 q2') #generalized coordinates
|
274 |
+
k, c, g, kT = symbols('k c g kT') #constants
|
275 |
+
F, T = dynamicsymbols('F T') #Specified forces
|
276 |
+
|
277 |
+
#Applying forces
|
278 |
+
B.apply_force(F*W.x)
|
279 |
+
W.apply_force(k*q1*W.x, reaction_body=B) #Spring force
|
280 |
+
W.apply_force(c*q1.diff()*W.x, reaction_body=B) #dampner
|
281 |
+
P.apply_force(P.mass*g*W.y)
|
282 |
+
b.apply_force(b.mass*g*W.y)
|
283 |
+
|
284 |
+
#Applying torques
|
285 |
+
P.apply_torque(kT*q2*W.z, reaction_body=b)
|
286 |
+
P.apply_torque(T*W.z)
|
287 |
+
|
288 |
+
assert B.loads == [(B.masscenter, (F - k*q1 - c*q1.diff())*W.x)]
|
289 |
+
assert P.loads == [(P.masscenter, P.mass*g*W.y), (P.frame, (T + kT*q2)*W.z)]
|
290 |
+
assert b.loads == [(b.masscenter, b.mass*g*W.y), (b.frame, -kT*q2*W.z)]
|
291 |
+
assert W.loads == [(W.masscenter, (c*q1.diff() + k*q1)*W.x)]
|
292 |
+
|
293 |
+
|
294 |
+
def test_parallel_axis():
|
295 |
+
N = ReferenceFrame('N')
|
296 |
+
m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
|
297 |
+
Io = inertia(N, Ix, Iy, Iz)
|
298 |
+
# Test RigidBody
|
299 |
+
o = Point('o')
|
300 |
+
p = o.locatenew('p', a * N.x + b * N.y)
|
301 |
+
R = Body('R', masscenter=o, frame=N, mass=m, central_inertia=Io)
|
302 |
+
Ip = R.parallel_axis(p)
|
303 |
+
Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2,
|
304 |
+
Iz + m * (a**2 + b**2), ixy=-m * a * b)
|
305 |
+
assert Ip == Ip_expected
|
306 |
+
# Reference frame from which the parallel axis is viewed should not matter
|
307 |
+
A = ReferenceFrame('A')
|
308 |
+
A.orient_axis(N, N.z, 1)
|
309 |
+
assert _simplify_matrix(
|
310 |
+
(R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3)
|
311 |
+
# Test Particle
|
312 |
+
o = Point('o')
|
313 |
+
p = o.locatenew('p', a * N.x + b * N.y)
|
314 |
+
P = Body('P', masscenter=o, mass=m, frame=N)
|
315 |
+
Ip = P.parallel_axis(p, N)
|
316 |
+
Ip_expected = inertia(N, m * b ** 2, m * a ** 2, m * (a ** 2 + b ** 2),
|
317 |
+
ixy=-m * a * b)
|
318 |
+
assert not P.is_rigidbody
|
319 |
+
assert Ip == Ip_expected
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py
ADDED
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, S, Function
|
2 |
+
from sympy.physics.mechanics import (Particle, Point, ReferenceFrame,
|
3 |
+
RigidBody)
|
4 |
+
from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
|
5 |
+
inertia, inertia_of_point_mass,
|
6 |
+
kinetic_energy, linear_momentum,
|
7 |
+
outer, potential_energy, msubs,
|
8 |
+
find_dynamicsymbols, Lagrangian)
|
9 |
+
|
10 |
+
from sympy.physics.mechanics.functions import (gravity, center_of_mass,
|
11 |
+
_validate_coordinates)
|
12 |
+
from sympy.testing.pytest import raises
|
13 |
+
|
14 |
+
|
15 |
+
q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
|
16 |
+
N = ReferenceFrame('N')
|
17 |
+
A = N.orientnew('A', 'Axis', [q1, N.z])
|
18 |
+
B = A.orientnew('B', 'Axis', [q2, A.x])
|
19 |
+
C = B.orientnew('C', 'Axis', [q3, B.y])
|
20 |
+
|
21 |
+
|
22 |
+
def test_inertia():
|
23 |
+
N = ReferenceFrame('N')
|
24 |
+
ixx, iyy, izz = symbols('ixx iyy izz')
|
25 |
+
ixy, iyz, izx = symbols('ixy iyz izx')
|
26 |
+
assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy *
|
27 |
+
(N.y | N.y) + izz * (N.z | N.z))
|
28 |
+
assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x)
|
29 |
+
raises(TypeError, lambda: inertia(0, 0, 0, 0))
|
30 |
+
assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) +
|
31 |
+
ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy *
|
32 |
+
(N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z |
|
33 |
+
N.y) + izz * (N.z | N.z))
|
34 |
+
|
35 |
+
|
36 |
+
def test_inertia_of_point_mass():
|
37 |
+
r, s, t, m = symbols('r s t m')
|
38 |
+
N = ReferenceFrame('N')
|
39 |
+
|
40 |
+
px = r * N.x
|
41 |
+
I = inertia_of_point_mass(m, px, N)
|
42 |
+
assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z)
|
43 |
+
|
44 |
+
py = s * N.y
|
45 |
+
I = inertia_of_point_mass(m, py, N)
|
46 |
+
assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z)
|
47 |
+
|
48 |
+
pz = t * N.z
|
49 |
+
I = inertia_of_point_mass(m, pz, N)
|
50 |
+
assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y)
|
51 |
+
|
52 |
+
p = px + py + pz
|
53 |
+
I = inertia_of_point_mass(m, p, N)
|
54 |
+
assert I == (m * (s**2 + t**2) * (N.x | N.x) -
|
55 |
+
m * r * s * (N.x | N.y) -
|
56 |
+
m * r * t * (N.x | N.z) -
|
57 |
+
m * r * s * (N.y | N.x) +
|
58 |
+
m * (r**2 + t**2) * (N.y | N.y) -
|
59 |
+
m * s * t * (N.y | N.z) -
|
60 |
+
m * r * t * (N.z | N.x) -
|
61 |
+
m * s * t * (N.z | N.y) +
|
62 |
+
m * (r**2 + s**2) * (N.z | N.z))
|
63 |
+
|
64 |
+
|
65 |
+
def test_linear_momentum():
|
66 |
+
N = ReferenceFrame('N')
|
67 |
+
Ac = Point('Ac')
|
68 |
+
Ac.set_vel(N, 25 * N.y)
|
69 |
+
I = outer(N.x, N.x)
|
70 |
+
A = RigidBody('A', Ac, N, 20, (I, Ac))
|
71 |
+
P = Point('P')
|
72 |
+
Pa = Particle('Pa', P, 1)
|
73 |
+
Pa.point.set_vel(N, 10 * N.x)
|
74 |
+
raises(TypeError, lambda: linear_momentum(A, A, Pa))
|
75 |
+
raises(TypeError, lambda: linear_momentum(N, N, Pa))
|
76 |
+
assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y
|
77 |
+
|
78 |
+
|
79 |
+
def test_angular_momentum_and_linear_momentum():
|
80 |
+
"""A rod with length 2l, centroidal inertia I, and mass M along with a
|
81 |
+
particle of mass m fixed to the end of the rod rotate with an angular rate
|
82 |
+
of omega about point O which is fixed to the non-particle end of the rod.
|
83 |
+
The rod's reference frame is A and the inertial frame is N."""
|
84 |
+
m, M, l, I = symbols('m, M, l, I')
|
85 |
+
omega = dynamicsymbols('omega')
|
86 |
+
N = ReferenceFrame('N')
|
87 |
+
a = ReferenceFrame('a')
|
88 |
+
O = Point('O')
|
89 |
+
Ac = O.locatenew('Ac', l * N.x)
|
90 |
+
P = Ac.locatenew('P', l * N.x)
|
91 |
+
O.set_vel(N, 0 * N.x)
|
92 |
+
a.set_ang_vel(N, omega * N.z)
|
93 |
+
Ac.v2pt_theory(O, N, a)
|
94 |
+
P.v2pt_theory(O, N, a)
|
95 |
+
Pa = Particle('Pa', P, m)
|
96 |
+
A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac))
|
97 |
+
expected = 2 * m * omega * l * N.y + M * l * omega * N.y
|
98 |
+
assert linear_momentum(N, A, Pa) == expected
|
99 |
+
raises(TypeError, lambda: angular_momentum(N, N, A, Pa))
|
100 |
+
raises(TypeError, lambda: angular_momentum(O, O, A, Pa))
|
101 |
+
raises(TypeError, lambda: angular_momentum(O, N, O, Pa))
|
102 |
+
expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z
|
103 |
+
assert angular_momentum(O, N, A, Pa) == expected
|
104 |
+
|
105 |
+
|
106 |
+
def test_kinetic_energy():
|
107 |
+
m, M, l1 = symbols('m M l1')
|
108 |
+
omega = dynamicsymbols('omega')
|
109 |
+
N = ReferenceFrame('N')
|
110 |
+
O = Point('O')
|
111 |
+
O.set_vel(N, 0 * N.x)
|
112 |
+
Ac = O.locatenew('Ac', l1 * N.x)
|
113 |
+
P = Ac.locatenew('P', l1 * N.x)
|
114 |
+
a = ReferenceFrame('a')
|
115 |
+
a.set_ang_vel(N, omega * N.z)
|
116 |
+
Ac.v2pt_theory(O, N, a)
|
117 |
+
P.v2pt_theory(O, N, a)
|
118 |
+
Pa = Particle('Pa', P, m)
|
119 |
+
I = outer(N.z, N.z)
|
120 |
+
A = RigidBody('A', Ac, a, M, (I, Ac))
|
121 |
+
raises(TypeError, lambda: kinetic_energy(Pa, Pa, A))
|
122 |
+
raises(TypeError, lambda: kinetic_energy(N, N, A))
|
123 |
+
assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2
|
124 |
+
+ 2*l1**2*m*omega**2 + omega**2/2)).expand()
|
125 |
+
|
126 |
+
|
127 |
+
def test_potential_energy():
|
128 |
+
m, M, l1, g, h, H = symbols('m M l1 g h H')
|
129 |
+
omega = dynamicsymbols('omega')
|
130 |
+
N = ReferenceFrame('N')
|
131 |
+
O = Point('O')
|
132 |
+
O.set_vel(N, 0 * N.x)
|
133 |
+
Ac = O.locatenew('Ac', l1 * N.x)
|
134 |
+
P = Ac.locatenew('P', l1 * N.x)
|
135 |
+
a = ReferenceFrame('a')
|
136 |
+
a.set_ang_vel(N, omega * N.z)
|
137 |
+
Ac.v2pt_theory(O, N, a)
|
138 |
+
P.v2pt_theory(O, N, a)
|
139 |
+
Pa = Particle('Pa', P, m)
|
140 |
+
I = outer(N.z, N.z)
|
141 |
+
A = RigidBody('A', Ac, a, M, (I, Ac))
|
142 |
+
Pa.potential_energy = m * g * h
|
143 |
+
A.potential_energy = M * g * H
|
144 |
+
assert potential_energy(A, Pa) == m * g * h + M * g * H
|
145 |
+
|
146 |
+
|
147 |
+
def test_Lagrangian():
|
148 |
+
M, m, g, h = symbols('M m g h')
|
149 |
+
N = ReferenceFrame('N')
|
150 |
+
O = Point('O')
|
151 |
+
O.set_vel(N, 0 * N.x)
|
152 |
+
P = O.locatenew('P', 1 * N.x)
|
153 |
+
P.set_vel(N, 10 * N.x)
|
154 |
+
Pa = Particle('Pa', P, 1)
|
155 |
+
Ac = O.locatenew('Ac', 2 * N.y)
|
156 |
+
Ac.set_vel(N, 5 * N.y)
|
157 |
+
a = ReferenceFrame('a')
|
158 |
+
a.set_ang_vel(N, 10 * N.z)
|
159 |
+
I = outer(N.z, N.z)
|
160 |
+
A = RigidBody('A', Ac, a, 20, (I, Ac))
|
161 |
+
Pa.potential_energy = m * g * h
|
162 |
+
A.potential_energy = M * g * h
|
163 |
+
raises(TypeError, lambda: Lagrangian(A, A, Pa))
|
164 |
+
raises(TypeError, lambda: Lagrangian(N, N, Pa))
|
165 |
+
|
166 |
+
|
167 |
+
def test_msubs():
|
168 |
+
a, b = symbols('a, b')
|
169 |
+
x, y, z = dynamicsymbols('x, y, z')
|
170 |
+
# Test simple substitution
|
171 |
+
expr = Matrix([[a*x + b, x*y.diff() + y],
|
172 |
+
[x.diff().diff(), z + sin(z.diff())]])
|
173 |
+
sol = Matrix([[a + b, y],
|
174 |
+
[x.diff().diff(), 1]])
|
175 |
+
sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0}
|
176 |
+
assert msubs(expr, sd) == sol
|
177 |
+
# Test smart substitution
|
178 |
+
expr = cos(x + y)*tan(x + y) + b*x.diff()
|
179 |
+
sd = {x: 0, y: pi/2, x.diff(): 1}
|
180 |
+
assert msubs(expr, sd, smart=True) == b + 1
|
181 |
+
N = ReferenceFrame('N')
|
182 |
+
v = x*N.x + y*N.y
|
183 |
+
d = x*(N.x|N.x) + y*(N.y|N.y)
|
184 |
+
v_sol = 1*N.y
|
185 |
+
d_sol = 1*(N.y|N.y)
|
186 |
+
sd = {x: 0, y: 1}
|
187 |
+
assert msubs(v, sd) == v_sol
|
188 |
+
assert msubs(d, sd) == d_sol
|
189 |
+
|
190 |
+
|
191 |
+
def test_find_dynamicsymbols():
|
192 |
+
a, b = symbols('a, b')
|
193 |
+
x, y, z = dynamicsymbols('x, y, z')
|
194 |
+
expr = Matrix([[a*x + b, x*y.diff() + y],
|
195 |
+
[x.diff().diff(), z + sin(z.diff())]])
|
196 |
+
# Test finding all dynamicsymbols
|
197 |
+
sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()}
|
198 |
+
assert find_dynamicsymbols(expr) == sol
|
199 |
+
# Test finding all but those in sym_list
|
200 |
+
exclude_list = [x, y, z]
|
201 |
+
sol = {y.diff(), x.diff().diff(), z.diff()}
|
202 |
+
assert find_dynamicsymbols(expr, exclude=exclude_list) == sol
|
203 |
+
# Test finding all dynamicsymbols in a vector with a given reference frame
|
204 |
+
d, e, f = dynamicsymbols('d, e, f')
|
205 |
+
A = ReferenceFrame('A')
|
206 |
+
v = d * A.x + e * A.y + f * A.z
|
207 |
+
sol = {d, e, f}
|
208 |
+
assert find_dynamicsymbols(v, reference_frame=A) == sol
|
209 |
+
# Test if a ValueError is raised on supplying only a vector as input
|
210 |
+
raises(ValueError, lambda: find_dynamicsymbols(v))
|
211 |
+
|
212 |
+
|
213 |
+
def test_gravity():
|
214 |
+
N = ReferenceFrame('N')
|
215 |
+
m, M, g = symbols('m M g')
|
216 |
+
F1, F2 = dynamicsymbols('F1 F2')
|
217 |
+
po = Point('po')
|
218 |
+
pa = Particle('pa', po, m)
|
219 |
+
A = ReferenceFrame('A')
|
220 |
+
P = Point('P')
|
221 |
+
I = outer(A.x, A.x)
|
222 |
+
B = RigidBody('B', P, A, M, (I, P))
|
223 |
+
forceList = [(po, F1), (P, F2)]
|
224 |
+
forceList.extend(gravity(g*N.y, pa, B))
|
225 |
+
l = [(po, F1), (P, F2), (po, g*m*N.y), (P, g*M*N.y)]
|
226 |
+
|
227 |
+
for i in range(len(l)):
|
228 |
+
for j in range(len(l[i])):
|
229 |
+
assert forceList[i][j] == l[i][j]
|
230 |
+
|
231 |
+
# This function tests the center_of_mass() function
|
232 |
+
# that was added in PR #14758 to compute the center of
|
233 |
+
# mass of a system of bodies.
|
234 |
+
def test_center_of_mass():
|
235 |
+
a = ReferenceFrame('a')
|
236 |
+
m = symbols('m', real=True)
|
237 |
+
p1 = Particle('p1', Point('p1_pt'), S.One)
|
238 |
+
p2 = Particle('p2', Point('p2_pt'), S(2))
|
239 |
+
p3 = Particle('p3', Point('p3_pt'), S(3))
|
240 |
+
p4 = Particle('p4', Point('p4_pt'), m)
|
241 |
+
b_f = ReferenceFrame('b_f')
|
242 |
+
b_cm = Point('b_cm')
|
243 |
+
mb = symbols('mb')
|
244 |
+
b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
|
245 |
+
p2.point.set_pos(p1.point, a.x)
|
246 |
+
p3.point.set_pos(p1.point, a.x + a.y)
|
247 |
+
p4.point.set_pos(p1.point, a.y)
|
248 |
+
b.masscenter.set_pos(p1.point, a.y + a.z)
|
249 |
+
point_o=Point('o')
|
250 |
+
point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
|
251 |
+
expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
|
252 |
+
assert point_o.pos_from(p1.point)-expr == 0
|
253 |
+
|
254 |
+
|
255 |
+
def test_validate_coordinates():
|
256 |
+
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4 u1:4')
|
257 |
+
s1, s2, s3 = symbols('s1:4')
|
258 |
+
# Test normal
|
259 |
+
_validate_coordinates([q1, q2, q3], [u1, u2, u3])
|
260 |
+
# Test not equal number of coordinates and speeds
|
261 |
+
_validate_coordinates([q1, q2])
|
262 |
+
_validate_coordinates([q1, q2], [u1])
|
263 |
+
_validate_coordinates(speeds=[u1, u2])
|
264 |
+
# Test duplicate
|
265 |
+
_validate_coordinates([q1, q2, q2], [u1, u2, u3], check_duplicates=False)
|
266 |
+
raises(ValueError, lambda: _validate_coordinates(
|
267 |
+
[q1, q2, q2], [u1, u2, u3]))
|
268 |
+
_validate_coordinates([q1, q2, q3], [u1, u2, u2], check_duplicates=False)
|
269 |
+
raises(ValueError, lambda: _validate_coordinates(
|
270 |
+
[q1, q2, q3], [u1, u2, u2], check_duplicates=True))
|
271 |
+
raises(ValueError, lambda: _validate_coordinates(
|
272 |
+
[q1, q2, q3], [q1, u2, u3], check_duplicates=True))
|
273 |
+
# Test is_dynamicsymbols
|
274 |
+
_validate_coordinates([q1 + q2, q3], is_dynamicsymbols=False)
|
275 |
+
raises(ValueError, lambda: _validate_coordinates([q1 + q2, q3]))
|
276 |
+
_validate_coordinates([s1, q1, q2], [0, u1, u2], is_dynamicsymbols=False)
|
277 |
+
raises(ValueError, lambda: _validate_coordinates(
|
278 |
+
[s1, q1, q2], [0, u1, u2], is_dynamicsymbols=True))
|
279 |
+
_validate_coordinates([s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=False)
|
280 |
+
raises(ValueError, lambda: _validate_coordinates(
|
281 |
+
[s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=True))
|
282 |
+
# Test normal function
|
283 |
+
t = dynamicsymbols._t
|
284 |
+
a = symbols('a')
|
285 |
+
f1, f2 = symbols('f1:3', cls=Function)
|
286 |
+
_validate_coordinates([f1(a), f2(a)], is_dynamicsymbols=False)
|
287 |
+
raises(ValueError, lambda: _validate_coordinates([f1(a), f2(a)]))
|
288 |
+
raises(ValueError, lambda: _validate_coordinates(speeds=[f1(a), f2(a)]))
|
289 |
+
dynamicsymbols._t = a
|
290 |
+
_validate_coordinates([f1(a), f2(a)])
|
291 |
+
raises(ValueError, lambda: _validate_coordinates([f1(t), f2(t)]))
|
292 |
+
dynamicsymbols._t = t
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py
ADDED
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy import solve
|
2 |
+
from sympy.core.backend import (cos, expand, Matrix, sin, symbols, tan, sqrt, S,
|
3 |
+
zeros, eye)
|
4 |
+
from sympy.simplify.simplify import simplify
|
5 |
+
from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
|
6 |
+
RigidBody, KanesMethod, inertia, Particle,
|
7 |
+
dot)
|
8 |
+
from sympy.testing.pytest import raises
|
9 |
+
from sympy.core.backend import USE_SYMENGINE
|
10 |
+
|
11 |
+
|
12 |
+
def test_invalid_coordinates():
|
13 |
+
# Simple pendulum, but use symbols instead of dynamicsymbols
|
14 |
+
l, m, g = symbols('l m g')
|
15 |
+
q, u = symbols('q u') # Generalized coordinate
|
16 |
+
kd = [q.diff(dynamicsymbols._t) - u]
|
17 |
+
N, O = ReferenceFrame('N'), Point('O')
|
18 |
+
O.set_vel(N, 0)
|
19 |
+
P = Particle('P', Point('P'), m)
|
20 |
+
P.point.set_pos(O, l * (sin(q) * N.x - cos(q) * N.y))
|
21 |
+
F = (P.point, -m * g * N.y)
|
22 |
+
raises(ValueError, lambda: KanesMethod(N, [q], [u], kd, bodies=[P],
|
23 |
+
forcelist=[F]))
|
24 |
+
|
25 |
+
|
26 |
+
def test_one_dof():
|
27 |
+
# This is for a 1 dof spring-mass-damper case.
|
28 |
+
# It is described in more detail in the KanesMethod docstring.
|
29 |
+
q, u = dynamicsymbols('q u')
|
30 |
+
qd, ud = dynamicsymbols('q u', 1)
|
31 |
+
m, c, k = symbols('m c k')
|
32 |
+
N = ReferenceFrame('N')
|
33 |
+
P = Point('P')
|
34 |
+
P.set_vel(N, u * N.x)
|
35 |
+
|
36 |
+
kd = [qd - u]
|
37 |
+
FL = [(P, (-k * q - c * u) * N.x)]
|
38 |
+
pa = Particle('pa', P, m)
|
39 |
+
BL = [pa]
|
40 |
+
|
41 |
+
KM = KanesMethod(N, [q], [u], kd)
|
42 |
+
KM.kanes_equations(BL, FL)
|
43 |
+
|
44 |
+
assert KM.bodies == BL
|
45 |
+
assert KM.loads == FL
|
46 |
+
|
47 |
+
MM = KM.mass_matrix
|
48 |
+
forcing = KM.forcing
|
49 |
+
rhs = MM.inv() * forcing
|
50 |
+
assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
|
51 |
+
|
52 |
+
assert simplify(KM.rhs() -
|
53 |
+
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
|
54 |
+
|
55 |
+
assert (KM.linearize(A_and_B=True, )[0] == Matrix([[0, 1], [-k/m, -c/m]]))
|
56 |
+
|
57 |
+
|
58 |
+
def test_two_dof():
|
59 |
+
# This is for a 2 d.o.f., 2 particle spring-mass-damper.
|
60 |
+
# The first coordinate is the displacement of the first particle, and the
|
61 |
+
# second is the relative displacement between the first and second
|
62 |
+
# particles. Speeds are defined as the time derivatives of the particles.
|
63 |
+
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
|
64 |
+
q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
|
65 |
+
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
|
66 |
+
N = ReferenceFrame('N')
|
67 |
+
P1 = Point('P1')
|
68 |
+
P2 = Point('P2')
|
69 |
+
P1.set_vel(N, u1 * N.x)
|
70 |
+
P2.set_vel(N, (u1 + u2) * N.x)
|
71 |
+
# Note we multiply the kinematic equation by an arbitrary factor
|
72 |
+
# to test the implicit vs explicit kinematics attribute
|
73 |
+
kd = [q1d/2 - u1/2, 2*q2d - 2*u2]
|
74 |
+
|
75 |
+
# Now we create the list of forces, then assign properties to each
|
76 |
+
# particle, then create a list of all particles.
|
77 |
+
FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
|
78 |
+
q2 - c2 * u2) * N.x)]
|
79 |
+
pa1 = Particle('pa1', P1, m)
|
80 |
+
pa2 = Particle('pa2', P2, m)
|
81 |
+
BL = [pa1, pa2]
|
82 |
+
|
83 |
+
# Finally we create the KanesMethod object, specify the inertial frame,
|
84 |
+
# pass relevant information, and form Fr & Fr*. Then we calculate the mass
|
85 |
+
# matrix and forcing terms, and finally solve for the udots.
|
86 |
+
KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
|
87 |
+
KM.kanes_equations(BL, FL)
|
88 |
+
MM = KM.mass_matrix
|
89 |
+
forcing = KM.forcing
|
90 |
+
rhs = MM.inv() * forcing
|
91 |
+
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
|
92 |
+
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
|
93 |
+
c2 * u2) / m)
|
94 |
+
|
95 |
+
# Check that the explicit form is the default and kinematic mass matrix is identity
|
96 |
+
assert KM.explicit_kinematics
|
97 |
+
assert KM.mass_matrix_kin == eye(2)
|
98 |
+
|
99 |
+
# Check that for the implicit form the mass matrix is not identity
|
100 |
+
KM.explicit_kinematics = False
|
101 |
+
assert KM.mass_matrix_kin == Matrix([[S(1)/2, 0], [0, 2]])
|
102 |
+
|
103 |
+
# Check that whether using implicit or explicit kinematics the RHS
|
104 |
+
# equations are consistent with the matrix form
|
105 |
+
for explicit_kinematics in [False, True]:
|
106 |
+
KM.explicit_kinematics = explicit_kinematics
|
107 |
+
assert simplify(KM.rhs() -
|
108 |
+
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(4, 1)
|
109 |
+
|
110 |
+
# Make sure an error is raised if nonlinear kinematic differential
|
111 |
+
# equations are supplied.
|
112 |
+
kd = [q1d - u1**2, sin(q2d) - cos(u2)]
|
113 |
+
raises(ValueError, lambda: KanesMethod(N, q_ind=[q1, q2],
|
114 |
+
u_ind=[u1, u2], kd_eqs=kd))
|
115 |
+
|
116 |
+
def test_pend():
|
117 |
+
q, u = dynamicsymbols('q u')
|
118 |
+
qd, ud = dynamicsymbols('q u', 1)
|
119 |
+
m, l, g = symbols('m l g')
|
120 |
+
N = ReferenceFrame('N')
|
121 |
+
P = Point('P')
|
122 |
+
P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
|
123 |
+
kd = [qd - u]
|
124 |
+
|
125 |
+
FL = [(P, m * g * N.x)]
|
126 |
+
pa = Particle('pa', P, m)
|
127 |
+
BL = [pa]
|
128 |
+
|
129 |
+
KM = KanesMethod(N, [q], [u], kd)
|
130 |
+
KM.kanes_equations(BL, FL)
|
131 |
+
MM = KM.mass_matrix
|
132 |
+
forcing = KM.forcing
|
133 |
+
rhs = MM.inv() * forcing
|
134 |
+
rhs.simplify()
|
135 |
+
assert expand(rhs[0]) == expand(-g / l * sin(q))
|
136 |
+
assert simplify(KM.rhs() -
|
137 |
+
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
|
138 |
+
|
139 |
+
|
140 |
+
def test_rolling_disc():
|
141 |
+
# Rolling Disc Example
|
142 |
+
# Here the rolling disc is formed from the contact point up, removing the
|
143 |
+
# need to introduce generalized speeds. Only 3 configuration and three
|
144 |
+
# speed variables are need to describe this system, along with the disc's
|
145 |
+
# mass and radius, and the local gravity (note that mass will drop out).
|
146 |
+
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
|
147 |
+
q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
|
148 |
+
r, m, g = symbols('r m g')
|
149 |
+
|
150 |
+
# The kinematics are formed by a series of simple rotations. Each simple
|
151 |
+
# rotation creates a new frame, and the next rotation is defined by the new
|
152 |
+
# frame's basis vectors. This example uses a 3-1-2 series of rotations, or
|
153 |
+
# Z, X, Y series of rotations. Angular velocity for this is defined using
|
154 |
+
# the second frame's basis (the lean frame).
|
155 |
+
N = ReferenceFrame('N')
|
156 |
+
Y = N.orientnew('Y', 'Axis', [q1, N.z])
|
157 |
+
L = Y.orientnew('L', 'Axis', [q2, Y.x])
|
158 |
+
R = L.orientnew('R', 'Axis', [q3, L.y])
|
159 |
+
w_R_N_qd = R.ang_vel_in(N)
|
160 |
+
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
|
161 |
+
|
162 |
+
# This is the translational kinematics. We create a point with no velocity
|
163 |
+
# in N; this is the contact point between the disc and ground. Next we form
|
164 |
+
# the position vector from the contact point to the disc's center of mass.
|
165 |
+
# Finally we form the velocity and acceleration of the disc.
|
166 |
+
C = Point('C')
|
167 |
+
C.set_vel(N, 0)
|
168 |
+
Dmc = C.locatenew('Dmc', r * L.z)
|
169 |
+
Dmc.v2pt_theory(C, N, R)
|
170 |
+
|
171 |
+
# This is a simple way to form the inertia dyadic.
|
172 |
+
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
|
173 |
+
|
174 |
+
# Kinematic differential equations; how the generalized coordinate time
|
175 |
+
# derivatives relate to generalized speeds.
|
176 |
+
kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
|
177 |
+
|
178 |
+
# Creation of the force list; it is the gravitational force at the mass
|
179 |
+
# center of the disc. Then we create the disc by assigning a Point to the
|
180 |
+
# center of mass attribute, a ReferenceFrame to the frame attribute, and mass
|
181 |
+
# and inertia. Then we form the body list.
|
182 |
+
ForceList = [(Dmc, - m * g * Y.z)]
|
183 |
+
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
|
184 |
+
BodyList = [BodyD]
|
185 |
+
|
186 |
+
# Finally we form the equations of motion, using the same steps we did
|
187 |
+
# before. Specify inertial frame, supply generalized speeds, supply
|
188 |
+
# kinematic differential equation dictionary, compute Fr from the force
|
189 |
+
# list and Fr* from the body list, compute the mass matrix and forcing
|
190 |
+
# terms, then solve for the u dots (time derivatives of the generalized
|
191 |
+
# speeds).
|
192 |
+
KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd)
|
193 |
+
KM.kanes_equations(BodyList, ForceList)
|
194 |
+
MM = KM.mass_matrix
|
195 |
+
forcing = KM.forcing
|
196 |
+
rhs = MM.inv() * forcing
|
197 |
+
kdd = KM.kindiffdict()
|
198 |
+
rhs = rhs.subs(kdd)
|
199 |
+
rhs.simplify()
|
200 |
+
assert rhs.expand() == Matrix([(6*u2*u3*r - u3**2*r*tan(q2) +
|
201 |
+
4*g*sin(q2))/(5*r), -2*u1*u3/3, u1*(-2*u2 + u3*tan(q2))]).expand()
|
202 |
+
assert simplify(KM.rhs() -
|
203 |
+
KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(6, 1)
|
204 |
+
|
205 |
+
# This code tests our output vs. benchmark values. When r=g=m=1, the
|
206 |
+
# critical speed (where all eigenvalues of the linearized equations are 0)
|
207 |
+
# is 1 / sqrt(3) for the upright case.
|
208 |
+
A = KM.linearize(A_and_B=True)[0]
|
209 |
+
A_upright = A.subs({r: 1, g: 1, m: 1}).subs({q1: 0, q2: 0, q3: 0, u1: 0, u3: 0})
|
210 |
+
import sympy
|
211 |
+
assert sympy.sympify(A_upright.subs({u2: 1 / sqrt(3)})).eigenvals() == {S.Zero: 6}
|
212 |
+
|
213 |
+
|
214 |
+
def test_aux():
|
215 |
+
# Same as above, except we have 2 auxiliary speeds for the ground contact
|
216 |
+
# point, which is known to be zero. In one case, we go through then
|
217 |
+
# substitute the aux. speeds in at the end (they are zero, as well as their
|
218 |
+
# derivative), in the other case, we use the built-in auxiliary speed part
|
219 |
+
# of KanesMethod. The equations from each should be the same.
|
220 |
+
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
|
221 |
+
q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
|
222 |
+
u4, u5, f1, f2 = dynamicsymbols('u4, u5, f1, f2')
|
223 |
+
u4d, u5d = dynamicsymbols('u4, u5', 1)
|
224 |
+
r, m, g = symbols('r m g')
|
225 |
+
|
226 |
+
N = ReferenceFrame('N')
|
227 |
+
Y = N.orientnew('Y', 'Axis', [q1, N.z])
|
228 |
+
L = Y.orientnew('L', 'Axis', [q2, Y.x])
|
229 |
+
R = L.orientnew('R', 'Axis', [q3, L.y])
|
230 |
+
w_R_N_qd = R.ang_vel_in(N)
|
231 |
+
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
|
232 |
+
|
233 |
+
C = Point('C')
|
234 |
+
C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
|
235 |
+
Dmc = C.locatenew('Dmc', r * L.z)
|
236 |
+
Dmc.v2pt_theory(C, N, R)
|
237 |
+
Dmc.a2pt_theory(C, N, R)
|
238 |
+
|
239 |
+
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
|
240 |
+
|
241 |
+
kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
|
242 |
+
|
243 |
+
ForceList = [(Dmc, - m * g * Y.z), (C, f1 * L.x + f2 * (Y.z ^ L.x))]
|
244 |
+
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
|
245 |
+
BodyList = [BodyD]
|
246 |
+
|
247 |
+
KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3, u4, u5],
|
248 |
+
kd_eqs=kd)
|
249 |
+
(fr, frstar) = KM.kanes_equations(BodyList, ForceList)
|
250 |
+
fr = fr.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
|
251 |
+
frstar = frstar.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
|
252 |
+
|
253 |
+
KM2 = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd,
|
254 |
+
u_auxiliary=[u4, u5])
|
255 |
+
(fr2, frstar2) = KM2.kanes_equations(BodyList, ForceList)
|
256 |
+
fr2 = fr2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
|
257 |
+
frstar2 = frstar2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
|
258 |
+
|
259 |
+
frstar.simplify()
|
260 |
+
frstar2.simplify()
|
261 |
+
|
262 |
+
assert (fr - fr2).expand() == Matrix([0, 0, 0, 0, 0])
|
263 |
+
assert (frstar - frstar2).expand() == Matrix([0, 0, 0, 0, 0])
|
264 |
+
|
265 |
+
|
266 |
+
def test_parallel_axis():
|
267 |
+
# This is for a 2 dof inverted pendulum on a cart.
|
268 |
+
# This tests the parallel axis code in KanesMethod. The inertia of the
|
269 |
+
# pendulum is defined about the hinge, not about the center of mass.
|
270 |
+
|
271 |
+
# Defining the constants and knowns of the system
|
272 |
+
gravity = symbols('g')
|
273 |
+
k, ls = symbols('k ls')
|
274 |
+
a, mA, mC = symbols('a mA mC')
|
275 |
+
F = dynamicsymbols('F')
|
276 |
+
Ix, Iy, Iz = symbols('Ix Iy Iz')
|
277 |
+
|
278 |
+
# Declaring the Generalized coordinates and speeds
|
279 |
+
q1, q2 = dynamicsymbols('q1 q2')
|
280 |
+
q1d, q2d = dynamicsymbols('q1 q2', 1)
|
281 |
+
u1, u2 = dynamicsymbols('u1 u2')
|
282 |
+
u1d, u2d = dynamicsymbols('u1 u2', 1)
|
283 |
+
|
284 |
+
# Creating reference frames
|
285 |
+
N = ReferenceFrame('N')
|
286 |
+
A = ReferenceFrame('A')
|
287 |
+
|
288 |
+
A.orient(N, 'Axis', [-q2, N.z])
|
289 |
+
A.set_ang_vel(N, -u2 * N.z)
|
290 |
+
|
291 |
+
# Origin of Newtonian reference frame
|
292 |
+
O = Point('O')
|
293 |
+
|
294 |
+
# Creating and Locating the positions of the cart, C, and the
|
295 |
+
# center of mass of the pendulum, A
|
296 |
+
C = O.locatenew('C', q1 * N.x)
|
297 |
+
Ao = C.locatenew('Ao', a * A.y)
|
298 |
+
|
299 |
+
# Defining velocities of the points
|
300 |
+
O.set_vel(N, 0)
|
301 |
+
C.set_vel(N, u1 * N.x)
|
302 |
+
Ao.v2pt_theory(C, N, A)
|
303 |
+
Cart = Particle('Cart', C, mC)
|
304 |
+
Pendulum = RigidBody('Pendulum', Ao, A, mA, (inertia(A, Ix, Iy, Iz), C))
|
305 |
+
|
306 |
+
# kinematical differential equations
|
307 |
+
|
308 |
+
kindiffs = [q1d - u1, q2d - u2]
|
309 |
+
|
310 |
+
bodyList = [Cart, Pendulum]
|
311 |
+
|
312 |
+
forceList = [(Ao, -N.y * gravity * mA),
|
313 |
+
(C, -N.y * gravity * mC),
|
314 |
+
(C, -N.x * k * (q1 - ls)),
|
315 |
+
(C, N.x * F)]
|
316 |
+
|
317 |
+
km = KanesMethod(N, [q1, q2], [u1, u2], kindiffs)
|
318 |
+
(fr, frstar) = km.kanes_equations(bodyList, forceList)
|
319 |
+
mm = km.mass_matrix_full
|
320 |
+
assert mm[3, 3] == Iz
|
321 |
+
|
322 |
+
def test_input_format():
|
323 |
+
# 1 dof problem from test_one_dof
|
324 |
+
q, u = dynamicsymbols('q u')
|
325 |
+
qd, ud = dynamicsymbols('q u', 1)
|
326 |
+
m, c, k = symbols('m c k')
|
327 |
+
N = ReferenceFrame('N')
|
328 |
+
P = Point('P')
|
329 |
+
P.set_vel(N, u * N.x)
|
330 |
+
|
331 |
+
kd = [qd - u]
|
332 |
+
FL = [(P, (-k * q - c * u) * N.x)]
|
333 |
+
pa = Particle('pa', P, m)
|
334 |
+
BL = [pa]
|
335 |
+
|
336 |
+
KM = KanesMethod(N, [q], [u], kd)
|
337 |
+
# test for input format kane.kanes_equations((body1, body2, particle1))
|
338 |
+
assert KM.kanes_equations(BL)[0] == Matrix([0])
|
339 |
+
# test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2))
|
340 |
+
assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0])
|
341 |
+
# test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None)
|
342 |
+
assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0])
|
343 |
+
# test for input format kane.kanes_equations(bodies=(body1, body 2))
|
344 |
+
assert KM.kanes_equations(BL)[0] == Matrix([0])
|
345 |
+
# test for input format kane.kanes_equations(bodies=(body1, body2), loads=[])
|
346 |
+
assert KM.kanes_equations(BL, [])[0] == Matrix([0])
|
347 |
+
# test for error raised when a wrong force list (in this case a string) is provided
|
348 |
+
raises(ValueError, lambda: KM._form_fr('bad input'))
|
349 |
+
|
350 |
+
# 1 dof problem from test_one_dof with FL & BL in instance
|
351 |
+
KM = KanesMethod(N, [q], [u], kd, bodies=BL, forcelist=FL)
|
352 |
+
assert KM.kanes_equations()[0] == Matrix([-c*u - k*q])
|
353 |
+
|
354 |
+
# 2 dof problem from test_two_dof
|
355 |
+
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
|
356 |
+
q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
|
357 |
+
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
|
358 |
+
N = ReferenceFrame('N')
|
359 |
+
P1 = Point('P1')
|
360 |
+
P2 = Point('P2')
|
361 |
+
P1.set_vel(N, u1 * N.x)
|
362 |
+
P2.set_vel(N, (u1 + u2) * N.x)
|
363 |
+
kd = [q1d - u1, q2d - u2]
|
364 |
+
|
365 |
+
FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
|
366 |
+
q2 - c2 * u2) * N.x))
|
367 |
+
pa1 = Particle('pa1', P1, m)
|
368 |
+
pa2 = Particle('pa2', P2, m)
|
369 |
+
BL = (pa1, pa2)
|
370 |
+
|
371 |
+
KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
|
372 |
+
# test for input format
|
373 |
+
# kane.kanes_equations((body1, body2), (load1, load2))
|
374 |
+
KM.kanes_equations(BL, FL)
|
375 |
+
MM = KM.mass_matrix
|
376 |
+
forcing = KM.forcing
|
377 |
+
rhs = MM.inv() * forcing
|
378 |
+
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
|
379 |
+
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
|
380 |
+
c2 * u2) / m)
|
381 |
+
|
382 |
+
|
383 |
+
def test_implicit_kinematics():
|
384 |
+
# Test that implicit kinematics can handle complicated
|
385 |
+
# equations that explicit form struggles with
|
386 |
+
# See https://github.com/sympy/sympy/issues/22626
|
387 |
+
|
388 |
+
# Inertial frame
|
389 |
+
NED = ReferenceFrame('NED')
|
390 |
+
NED_o = Point('NED_o')
|
391 |
+
NED_o.set_vel(NED, 0)
|
392 |
+
|
393 |
+
# body frame
|
394 |
+
q_att = dynamicsymbols('lambda_0:4', real=True)
|
395 |
+
B = NED.orientnew('B', 'Quaternion', q_att)
|
396 |
+
|
397 |
+
# Generalized coordinates
|
398 |
+
q_pos = dynamicsymbols('B_x:z')
|
399 |
+
B_cm = NED_o.locatenew('B_cm', q_pos[0]*B.x + q_pos[1]*B.y + q_pos[2]*B.z)
|
400 |
+
|
401 |
+
q_ind = q_att[1:] + q_pos
|
402 |
+
q_dep = [q_att[0]]
|
403 |
+
|
404 |
+
kinematic_eqs = []
|
405 |
+
|
406 |
+
# Generalized velocities
|
407 |
+
B_ang_vel = B.ang_vel_in(NED)
|
408 |
+
P, Q, R = dynamicsymbols('P Q R')
|
409 |
+
B.set_ang_vel(NED, P*B.x + Q*B.y + R*B.z)
|
410 |
+
|
411 |
+
B_ang_vel_kd = (B.ang_vel_in(NED) - B_ang_vel).simplify()
|
412 |
+
|
413 |
+
# Equating the two gives us the kinematic equation
|
414 |
+
kinematic_eqs += [
|
415 |
+
B_ang_vel_kd & B.x,
|
416 |
+
B_ang_vel_kd & B.y,
|
417 |
+
B_ang_vel_kd & B.z
|
418 |
+
]
|
419 |
+
|
420 |
+
B_cm_vel = B_cm.vel(NED)
|
421 |
+
U, V, W = dynamicsymbols('U V W')
|
422 |
+
B_cm.set_vel(NED, U*B.x + V*B.y + W*B.z)
|
423 |
+
|
424 |
+
# Compute the velocity of the point using the two methods
|
425 |
+
B_ref_vel_kd = (B_cm.vel(NED) - B_cm_vel)
|
426 |
+
|
427 |
+
# taking dot product with unit vectors to get kinematic equations
|
428 |
+
# relating body coordinates and velocities
|
429 |
+
|
430 |
+
# Note, there is a choice to dot with NED.xyz here. That makes
|
431 |
+
# the implicit form have some bigger terms but is still fine, the
|
432 |
+
# explicit form still struggles though
|
433 |
+
kinematic_eqs += [
|
434 |
+
B_ref_vel_kd & B.x,
|
435 |
+
B_ref_vel_kd & B.y,
|
436 |
+
B_ref_vel_kd & B.z,
|
437 |
+
]
|
438 |
+
|
439 |
+
u_ind = [U, V, W, P, Q, R]
|
440 |
+
|
441 |
+
# constraints
|
442 |
+
q_att_vec = Matrix(q_att)
|
443 |
+
config_cons = [(q_att_vec.T*q_att_vec)[0] - 1] #unit norm
|
444 |
+
kinematic_eqs = kinematic_eqs + [(q_att_vec.T * q_att_vec.diff())[0]]
|
445 |
+
|
446 |
+
try:
|
447 |
+
KM = KanesMethod(NED, q_ind, u_ind,
|
448 |
+
q_dependent= q_dep,
|
449 |
+
kd_eqs = kinematic_eqs,
|
450 |
+
configuration_constraints = config_cons,
|
451 |
+
velocity_constraints= [],
|
452 |
+
u_dependent= [], #no dependent speeds
|
453 |
+
u_auxiliary = [], # No auxiliary speeds
|
454 |
+
explicit_kinematics = False # implicit kinematics
|
455 |
+
)
|
456 |
+
except Exception as e:
|
457 |
+
# symengine struggles with these kinematic equations
|
458 |
+
if USE_SYMENGINE and 'Matrix is rank deficient' in str(e):
|
459 |
+
return
|
460 |
+
else:
|
461 |
+
raise e
|
462 |
+
|
463 |
+
# mass and inertia dyadic relative to CM
|
464 |
+
M_B = symbols('M_B')
|
465 |
+
J_B = inertia(B, *[S(f'J_B_{ax}')*(1 if ax[0] == ax[1] else -1)
|
466 |
+
for ax in ['xx', 'yy', 'zz', 'xy', 'yz', 'xz']])
|
467 |
+
J_B = J_B.subs({S('J_B_xy'): 0, S('J_B_yz'): 0})
|
468 |
+
RB = RigidBody('RB', B_cm, B, M_B, (J_B, B_cm))
|
469 |
+
|
470 |
+
rigid_bodies = [RB]
|
471 |
+
# Forces
|
472 |
+
force_list = [
|
473 |
+
#gravity pointing down
|
474 |
+
(RB.masscenter, RB.mass*S('g')*NED.z),
|
475 |
+
#generic forces and torques in body frame(inputs)
|
476 |
+
(RB.frame, dynamicsymbols('T_z')*B.z),
|
477 |
+
(RB.masscenter, dynamicsymbols('F_z')*B.z)
|
478 |
+
]
|
479 |
+
|
480 |
+
KM.kanes_equations(rigid_bodies, force_list)
|
481 |
+
|
482 |
+
# Expecting implicit form to be less than 5% of the flops
|
483 |
+
n_ops_implicit = sum(
|
484 |
+
[x.count_ops() for x in KM.forcing_full] +
|
485 |
+
[x.count_ops() for x in KM.mass_matrix_full]
|
486 |
+
)
|
487 |
+
# Save implicit kinematic matrices to use later
|
488 |
+
mass_matrix_kin_implicit = KM.mass_matrix_kin
|
489 |
+
forcing_kin_implicit = KM.forcing_kin
|
490 |
+
|
491 |
+
KM.explicit_kinematics = True
|
492 |
+
n_ops_explicit = sum(
|
493 |
+
[x.count_ops() for x in KM.forcing_full] +
|
494 |
+
[x.count_ops() for x in KM.mass_matrix_full]
|
495 |
+
)
|
496 |
+
forcing_kin_explicit = KM.forcing_kin
|
497 |
+
|
498 |
+
assert n_ops_implicit / n_ops_explicit < .05
|
499 |
+
|
500 |
+
# Ideally we would check that implicit and explicit equations give the same result as done in test_one_dof
|
501 |
+
# But the whole raison-d'etre of the implicit equations is to deal with problems such
|
502 |
+
# as this one where the explicit form is too complicated to handle, especially the angular part
|
503 |
+
# (i.e. tests would be too slow)
|
504 |
+
# Instead, we check that the kinematic equations are correct using more fundamental tests:
|
505 |
+
#
|
506 |
+
# (1) that we recover the kinematic equations we have provided
|
507 |
+
assert (mass_matrix_kin_implicit * KM.q.diff() - forcing_kin_implicit) == Matrix(kinematic_eqs)
|
508 |
+
|
509 |
+
# (2) that rate of quaternions matches what 'textbook' solutions give
|
510 |
+
# Note that we just use the explicit kinematics for the linear velocities
|
511 |
+
# as they are not as complicated as the angular ones
|
512 |
+
qdot_candidate = forcing_kin_explicit
|
513 |
+
|
514 |
+
quat_dot_textbook = Matrix([
|
515 |
+
[0, -P, -Q, -R],
|
516 |
+
[P, 0, R, -Q],
|
517 |
+
[Q, -R, 0, P],
|
518 |
+
[R, Q, -P, 0],
|
519 |
+
]) * q_att_vec / 2
|
520 |
+
|
521 |
+
# Again, if we don't use this "textbook" solution
|
522 |
+
# sympy will struggle to deal with the terms related to quaternion rates
|
523 |
+
# due to the number of operations involved
|
524 |
+
qdot_candidate[-1] = quat_dot_textbook[0] # lambda_0, note the [-1] as sympy's Kane puts the dependent coordinate last
|
525 |
+
qdot_candidate[0] = quat_dot_textbook[1] # lambda_1
|
526 |
+
qdot_candidate[1] = quat_dot_textbook[2] # lambda_2
|
527 |
+
qdot_candidate[2] = quat_dot_textbook[3] # lambda_3
|
528 |
+
|
529 |
+
# sub the config constraint in the candidate solution and compare to the implicit rhs
|
530 |
+
lambda_0_sol = solve(config_cons[0], q_att_vec[0])[1]
|
531 |
+
lhs_candidate = simplify(mass_matrix_kin_implicit * qdot_candidate).subs({q_att_vec[0]: lambda_0_sol})
|
532 |
+
assert lhs_candidate == forcing_kin_implicit
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane2.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.backend import cos, Matrix, sin, zeros, tan, pi, symbols
|
2 |
+
from sympy.simplify.simplify import simplify
|
3 |
+
from sympy.simplify.trigsimp import trigsimp
|
4 |
+
from sympy.solvers.solvers import solve
|
5 |
+
from sympy.physics.mechanics import (cross, dot, dynamicsymbols,
|
6 |
+
find_dynamicsymbols, KanesMethod, inertia,
|
7 |
+
inertia_of_point_mass, Point,
|
8 |
+
ReferenceFrame, RigidBody)
|
9 |
+
|
10 |
+
|
11 |
+
def test_aux_dep():
|
12 |
+
# This test is about rolling disc dynamics, comparing the results found
|
13 |
+
# with KanesMethod to those found when deriving the equations "manually"
|
14 |
+
# with SymPy.
|
15 |
+
# The terms Fr, Fr*, and Fr*_steady are all compared between the two
|
16 |
+
# methods. Here, Fr*_steady refers to the generalized inertia forces for an
|
17 |
+
# equilibrium configuration.
|
18 |
+
# Note: comparing to the test of test_rolling_disc() in test_kane.py, this
|
19 |
+
# test also tests auxiliary speeds and configuration and motion constraints
|
20 |
+
#, seen in the generalized dependent coordinates q[3], and depend speeds
|
21 |
+
# u[3], u[4] and u[5].
|
22 |
+
|
23 |
+
|
24 |
+
# First, manual derivation of Fr, Fr_star, Fr_star_steady.
|
25 |
+
|
26 |
+
# Symbols for time and constant parameters.
|
27 |
+
# Symbols for contact forces: Fx, Fy, Fz.
|
28 |
+
t, r, m, g, I, J = symbols('t r m g I J')
|
29 |
+
Fx, Fy, Fz = symbols('Fx Fy Fz')
|
30 |
+
|
31 |
+
# Configuration variables and their time derivatives:
|
32 |
+
# q[0] -- yaw
|
33 |
+
# q[1] -- lean
|
34 |
+
# q[2] -- spin
|
35 |
+
# q[3] -- dot(-r*B.z, A.z) -- distance from ground plane to disc center in
|
36 |
+
# A.z direction
|
37 |
+
# Generalized speeds and their time derivatives:
|
38 |
+
# u[0] -- disc angular velocity component, disc fixed x direction
|
39 |
+
# u[1] -- disc angular velocity component, disc fixed y direction
|
40 |
+
# u[2] -- disc angular velocity component, disc fixed z direction
|
41 |
+
# u[3] -- disc velocity component, A.x direction
|
42 |
+
# u[4] -- disc velocity component, A.y direction
|
43 |
+
# u[5] -- disc velocity component, A.z direction
|
44 |
+
# Auxiliary generalized speeds:
|
45 |
+
# ua[0] -- contact point auxiliary generalized speed, A.x direction
|
46 |
+
# ua[1] -- contact point auxiliary generalized speed, A.y direction
|
47 |
+
# ua[2] -- contact point auxiliary generalized speed, A.z direction
|
48 |
+
q = dynamicsymbols('q:4')
|
49 |
+
qd = [qi.diff(t) for qi in q]
|
50 |
+
u = dynamicsymbols('u:6')
|
51 |
+
ud = [ui.diff(t) for ui in u]
|
52 |
+
ud_zero = dict(zip(ud, [0.]*len(ud)))
|
53 |
+
ua = dynamicsymbols('ua:3')
|
54 |
+
ua_zero = dict(zip(ua, [0.]*len(ua))) # noqa:F841
|
55 |
+
|
56 |
+
# Reference frames:
|
57 |
+
# Yaw intermediate frame: A.
|
58 |
+
# Lean intermediate frame: B.
|
59 |
+
# Disc fixed frame: C.
|
60 |
+
N = ReferenceFrame('N')
|
61 |
+
A = N.orientnew('A', 'Axis', [q[0], N.z])
|
62 |
+
B = A.orientnew('B', 'Axis', [q[1], A.x])
|
63 |
+
C = B.orientnew('C', 'Axis', [q[2], B.y])
|
64 |
+
|
65 |
+
# Angular velocity and angular acceleration of disc fixed frame
|
66 |
+
# u[0], u[1] and u[2] are generalized independent speeds.
|
67 |
+
C.set_ang_vel(N, u[0]*B.x + u[1]*B.y + u[2]*B.z)
|
68 |
+
C.set_ang_acc(N, C.ang_vel_in(N).diff(t, B)
|
69 |
+
+ cross(B.ang_vel_in(N), C.ang_vel_in(N)))
|
70 |
+
|
71 |
+
# Velocity and acceleration of points:
|
72 |
+
# Disc-ground contact point: P.
|
73 |
+
# Center of disc: O, defined from point P with depend coordinate: q[3]
|
74 |
+
# u[3], u[4] and u[5] are generalized dependent speeds.
|
75 |
+
P = Point('P')
|
76 |
+
P.set_vel(N, ua[0]*A.x + ua[1]*A.y + ua[2]*A.z)
|
77 |
+
O = P.locatenew('O', q[3]*A.z + r*sin(q[1])*A.y)
|
78 |
+
O.set_vel(N, u[3]*A.x + u[4]*A.y + u[5]*A.z)
|
79 |
+
O.set_acc(N, O.vel(N).diff(t, A) + cross(A.ang_vel_in(N), O.vel(N)))
|
80 |
+
|
81 |
+
# Kinematic differential equations:
|
82 |
+
# Two equalities: one is w_c_n_qd = C.ang_vel_in(N) in three coordinates
|
83 |
+
# directions of B, for qd0, qd1 and qd2.
|
84 |
+
# the other is v_o_n_qd = O.vel(N) in A.z direction for qd3.
|
85 |
+
# Then, solve for dq/dt's in terms of u's: qd_kd.
|
86 |
+
w_c_n_qd = qd[0]*A.z + qd[1]*B.x + qd[2]*B.y
|
87 |
+
v_o_n_qd = O.pos_from(P).diff(t, A) + cross(A.ang_vel_in(N), O.pos_from(P))
|
88 |
+
kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
|
89 |
+
[dot(v_o_n_qd - O.vel(N), A.z)])
|
90 |
+
qd_kd = solve(kindiffs, qd) # noqa:F841
|
91 |
+
|
92 |
+
# Values of generalized speeds during a steady turn for later substitution
|
93 |
+
# into the Fr_star_steady.
|
94 |
+
steady_conditions = solve(kindiffs.subs({qd[1] : 0, qd[3] : 0}), u)
|
95 |
+
steady_conditions.update({qd[1] : 0, qd[3] : 0})
|
96 |
+
|
97 |
+
# Partial angular velocities and velocities.
|
98 |
+
partial_w_C = [C.ang_vel_in(N).diff(ui, N) for ui in u + ua]
|
99 |
+
partial_v_O = [O.vel(N).diff(ui, N) for ui in u + ua]
|
100 |
+
partial_v_P = [P.vel(N).diff(ui, N) for ui in u + ua]
|
101 |
+
|
102 |
+
# Configuration constraint: f_c, the projection of radius r in A.z direction
|
103 |
+
# is q[3].
|
104 |
+
# Velocity constraints: f_v, for u3, u4 and u5.
|
105 |
+
# Acceleration constraints: f_a.
|
106 |
+
f_c = Matrix([dot(-r*B.z, A.z) - q[3]])
|
107 |
+
f_v = Matrix([dot(O.vel(N) - (P.vel(N) + cross(C.ang_vel_in(N),
|
108 |
+
O.pos_from(P))), ai).expand() for ai in A])
|
109 |
+
v_o_n = cross(C.ang_vel_in(N), O.pos_from(P))
|
110 |
+
a_o_n = v_o_n.diff(t, A) + cross(A.ang_vel_in(N), v_o_n)
|
111 |
+
f_a = Matrix([dot(O.acc(N) - a_o_n, ai) for ai in A]) # noqa:F841
|
112 |
+
|
113 |
+
# Solve for constraint equations in the form of
|
114 |
+
# u_dependent = A_rs * [u_i; u_aux].
|
115 |
+
# First, obtain constraint coefficient matrix: M_v * [u; ua] = 0;
|
116 |
+
# Second, taking u[0], u[1], u[2] as independent,
|
117 |
+
# taking u[3], u[4], u[5] as dependent,
|
118 |
+
# rearranging the matrix of M_v to be A_rs for u_dependent.
|
119 |
+
# Third, u_aux ==0 for u_dep, and resulting dictionary of u_dep_dict.
|
120 |
+
M_v = zeros(3, 9)
|
121 |
+
for i in range(3):
|
122 |
+
for j, ui in enumerate(u + ua):
|
123 |
+
M_v[i, j] = f_v[i].diff(ui)
|
124 |
+
|
125 |
+
M_v_i = M_v[:, :3]
|
126 |
+
M_v_d = M_v[:, 3:6]
|
127 |
+
M_v_aux = M_v[:, 6:]
|
128 |
+
M_v_i_aux = M_v_i.row_join(M_v_aux)
|
129 |
+
A_rs = - M_v_d.inv() * M_v_i_aux
|
130 |
+
|
131 |
+
u_dep = A_rs[:, :3] * Matrix(u[:3])
|
132 |
+
u_dep_dict = dict(zip(u[3:], u_dep))
|
133 |
+
|
134 |
+
# Active forces: F_O acting on point O; F_P acting on point P.
|
135 |
+
# Generalized active forces (unconstrained): Fr_u = F_point * pv_point.
|
136 |
+
F_O = m*g*A.z
|
137 |
+
F_P = Fx * A.x + Fy * A.y + Fz * A.z
|
138 |
+
Fr_u = Matrix([dot(F_O, pv_o) + dot(F_P, pv_p) for pv_o, pv_p in
|
139 |
+
zip(partial_v_O, partial_v_P)])
|
140 |
+
|
141 |
+
# Inertia force: R_star_O.
|
142 |
+
# Inertia of disc: I_C_O, where J is a inertia component about principal axis.
|
143 |
+
# Inertia torque: T_star_C.
|
144 |
+
# Generalized inertia forces (unconstrained): Fr_star_u.
|
145 |
+
R_star_O = -m*O.acc(N)
|
146 |
+
I_C_O = inertia(B, I, J, I)
|
147 |
+
T_star_C = -(dot(I_C_O, C.ang_acc_in(N)) \
|
148 |
+
+ cross(C.ang_vel_in(N), dot(I_C_O, C.ang_vel_in(N))))
|
149 |
+
Fr_star_u = Matrix([dot(R_star_O, pv) + dot(T_star_C, pav) for pv, pav in
|
150 |
+
zip(partial_v_O, partial_w_C)])
|
151 |
+
|
152 |
+
# Form nonholonomic Fr: Fr_c, and nonholonomic Fr_star: Fr_star_c.
|
153 |
+
# Also, nonholonomic Fr_star in steady turning condition: Fr_star_steady.
|
154 |
+
Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :]
|
155 |
+
Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\
|
156 |
+
+ A_rs.T * Fr_star_u[3:6, :]
|
157 |
+
Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\
|
158 |
+
.subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand()
|
159 |
+
|
160 |
+
|
161 |
+
# Second, using KaneMethod in mechanics for fr, frstar and frstar_steady.
|
162 |
+
|
163 |
+
# Rigid Bodies: disc, with inertia I_C_O.
|
164 |
+
iner_tuple = (I_C_O, O)
|
165 |
+
disc = RigidBody('disc', O, C, m, iner_tuple)
|
166 |
+
bodyList = [disc]
|
167 |
+
|
168 |
+
# Generalized forces: Gravity: F_o; Auxiliary forces: F_p.
|
169 |
+
F_o = (O, F_O)
|
170 |
+
F_p = (P, F_P)
|
171 |
+
forceList = [F_o, F_p]
|
172 |
+
|
173 |
+
# KanesMethod.
|
174 |
+
kane = KanesMethod(
|
175 |
+
N, q_ind= q[:3], u_ind= u[:3], kd_eqs=kindiffs,
|
176 |
+
q_dependent=q[3:], configuration_constraints = f_c,
|
177 |
+
u_dependent=u[3:], velocity_constraints= f_v,
|
178 |
+
u_auxiliary=ua
|
179 |
+
)
|
180 |
+
|
181 |
+
# fr, frstar, frstar_steady and kdd(kinematic differential equations).
|
182 |
+
(fr, frstar)= kane.kanes_equations(bodyList, forceList)
|
183 |
+
frstar_steady = frstar.subs(ud_zero).subs(u_dep_dict).subs(steady_conditions)\
|
184 |
+
.subs({q[3]: -r*cos(q[1])}).expand()
|
185 |
+
kdd = kane.kindiffdict()
|
186 |
+
|
187 |
+
assert Matrix(Fr_c).expand() == fr.expand()
|
188 |
+
assert Matrix(Fr_star_c.subs(kdd)).expand() == frstar.expand()
|
189 |
+
assert (simplify(Matrix(Fr_star_steady).expand()) ==
|
190 |
+
simplify(frstar_steady.expand()))
|
191 |
+
|
192 |
+
syms_in_forcing = find_dynamicsymbols(kane.forcing)
|
193 |
+
for qdi in qd:
|
194 |
+
assert qdi not in syms_in_forcing
|
195 |
+
|
196 |
+
|
197 |
+
def test_non_central_inertia():
|
198 |
+
# This tests that the calculation of Fr* does not depend the point
|
199 |
+
# about which the inertia of a rigid body is defined. This test solves
|
200 |
+
# exercises 8.12, 8.17 from Kane 1985.
|
201 |
+
|
202 |
+
# Declare symbols
|
203 |
+
q1, q2, q3 = dynamicsymbols('q1:4')
|
204 |
+
q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
|
205 |
+
u1, u2, u3, u4, u5 = dynamicsymbols('u1:6')
|
206 |
+
u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
|
207 |
+
a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
|
208 |
+
Q1, Q2, Q3 = symbols('Q1, Q2 Q3')
|
209 |
+
IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
|
210 |
+
|
211 |
+
# Reference Frames
|
212 |
+
F = ReferenceFrame('F')
|
213 |
+
P = F.orientnew('P', 'axis', [-theta, F.y])
|
214 |
+
A = P.orientnew('A', 'axis', [q1, P.x])
|
215 |
+
A.set_ang_vel(F, u1*A.x + u3*A.z)
|
216 |
+
# define frames for wheels
|
217 |
+
B = A.orientnew('B', 'axis', [q2, A.z])
|
218 |
+
C = A.orientnew('C', 'axis', [q3, A.z])
|
219 |
+
B.set_ang_vel(A, u4 * A.z)
|
220 |
+
C.set_ang_vel(A, u5 * A.z)
|
221 |
+
|
222 |
+
# define points D, S*, Q on frame A and their velocities
|
223 |
+
pD = Point('D')
|
224 |
+
pD.set_vel(A, 0)
|
225 |
+
# u3 will not change v_D_F since wheels are still assumed to roll without slip.
|
226 |
+
pD.set_vel(F, u2 * A.y)
|
227 |
+
|
228 |
+
pS_star = pD.locatenew('S*', e*A.y)
|
229 |
+
pQ = pD.locatenew('Q', f*A.y - R*A.x)
|
230 |
+
for p in [pS_star, pQ]:
|
231 |
+
p.v2pt_theory(pD, F, A)
|
232 |
+
|
233 |
+
# masscenters of bodies A, B, C
|
234 |
+
pA_star = pD.locatenew('A*', a*A.y)
|
235 |
+
pB_star = pD.locatenew('B*', b*A.z)
|
236 |
+
pC_star = pD.locatenew('C*', -b*A.z)
|
237 |
+
for p in [pA_star, pB_star, pC_star]:
|
238 |
+
p.v2pt_theory(pD, F, A)
|
239 |
+
|
240 |
+
# points of B, C touching the plane P
|
241 |
+
pB_hat = pB_star.locatenew('B^', -R*A.x)
|
242 |
+
pC_hat = pC_star.locatenew('C^', -R*A.x)
|
243 |
+
pB_hat.v2pt_theory(pB_star, F, B)
|
244 |
+
pC_hat.v2pt_theory(pC_star, F, C)
|
245 |
+
|
246 |
+
# the velocities of B^, C^ are zero since B, C are assumed to roll without slip
|
247 |
+
kde = [q1d - u1, q2d - u4, q3d - u5]
|
248 |
+
vc = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
|
249 |
+
|
250 |
+
# inertias of bodies A, B, C
|
251 |
+
# IA22, IA23, IA33 are not specified in the problem statement, but are
|
252 |
+
# necessary to define an inertia object. Although the values of
|
253 |
+
# IA22, IA23, IA33 are not known in terms of the variables given in the
|
254 |
+
# problem statement, they do not appear in the general inertia terms.
|
255 |
+
inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
|
256 |
+
inertia_B = inertia(B, K, K, J)
|
257 |
+
inertia_C = inertia(C, K, K, J)
|
258 |
+
|
259 |
+
# define the rigid bodies A, B, C
|
260 |
+
rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
|
261 |
+
rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
|
262 |
+
rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
|
263 |
+
|
264 |
+
km = KanesMethod(F, q_ind=[q1, q2, q3], u_ind=[u1, u2], kd_eqs=kde,
|
265 |
+
u_dependent=[u4, u5], velocity_constraints=vc,
|
266 |
+
u_auxiliary=[u3])
|
267 |
+
|
268 |
+
forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
|
269 |
+
bodies = [rbA, rbB, rbC]
|
270 |
+
fr, fr_star = km.kanes_equations(bodies, forces)
|
271 |
+
vc_map = solve(vc, [u4, u5])
|
272 |
+
|
273 |
+
# KanesMethod returns the negative of Fr, Fr* as defined in Kane1985.
|
274 |
+
fr_star_expected = Matrix([
|
275 |
+
-(IA + 2*J*b**2/R**2 + 2*K +
|
276 |
+
mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
|
277 |
+
-(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
|
278 |
+
0])
|
279 |
+
t = trigsimp(fr_star.subs(vc_map).subs({u3: 0})).doit().expand()
|
280 |
+
assert ((fr_star_expected - t).expand() == zeros(3, 1))
|
281 |
+
|
282 |
+
# define inertias of rigid bodies A, B, C about point D
|
283 |
+
# I_S/O = I_S/S* + I_S*/O
|
284 |
+
bodies2 = []
|
285 |
+
for rb, I_star in zip([rbA, rbB, rbC], [inertia_A, inertia_B, inertia_C]):
|
286 |
+
I = I_star + inertia_of_point_mass(rb.mass,
|
287 |
+
rb.masscenter.pos_from(pD),
|
288 |
+
rb.frame)
|
289 |
+
bodies2.append(RigidBody('', rb.masscenter, rb.frame, rb.mass,
|
290 |
+
(I, pD)))
|
291 |
+
fr2, fr_star2 = km.kanes_equations(bodies2, forces)
|
292 |
+
|
293 |
+
t = trigsimp(fr_star2.subs(vc_map).subs({u3: 0})).doit()
|
294 |
+
assert (fr_star_expected - t).expand() == zeros(3, 1)
|
295 |
+
|
296 |
+
def test_sub_qdot():
|
297 |
+
# This test solves exercises 8.12, 8.17 from Kane 1985 and defines
|
298 |
+
# some velocities in terms of q, qdot.
|
299 |
+
|
300 |
+
## --- Declare symbols ---
|
301 |
+
q1, q2, q3 = dynamicsymbols('q1:4')
|
302 |
+
q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
|
303 |
+
u1, u2, u3 = dynamicsymbols('u1:4')
|
304 |
+
u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
|
305 |
+
a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
|
306 |
+
IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
|
307 |
+
Q1, Q2, Q3 = symbols('Q1 Q2 Q3')
|
308 |
+
|
309 |
+
# --- Reference Frames ---
|
310 |
+
F = ReferenceFrame('F')
|
311 |
+
P = F.orientnew('P', 'axis', [-theta, F.y])
|
312 |
+
A = P.orientnew('A', 'axis', [q1, P.x])
|
313 |
+
A.set_ang_vel(F, u1*A.x + u3*A.z)
|
314 |
+
# define frames for wheels
|
315 |
+
B = A.orientnew('B', 'axis', [q2, A.z])
|
316 |
+
C = A.orientnew('C', 'axis', [q3, A.z])
|
317 |
+
|
318 |
+
## --- define points D, S*, Q on frame A and their velocities ---
|
319 |
+
pD = Point('D')
|
320 |
+
pD.set_vel(A, 0)
|
321 |
+
# u3 will not change v_D_F since wheels are still assumed to roll w/o slip
|
322 |
+
pD.set_vel(F, u2 * A.y)
|
323 |
+
|
324 |
+
pS_star = pD.locatenew('S*', e*A.y)
|
325 |
+
pQ = pD.locatenew('Q', f*A.y - R*A.x)
|
326 |
+
# masscenters of bodies A, B, C
|
327 |
+
pA_star = pD.locatenew('A*', a*A.y)
|
328 |
+
pB_star = pD.locatenew('B*', b*A.z)
|
329 |
+
pC_star = pD.locatenew('C*', -b*A.z)
|
330 |
+
for p in [pS_star, pQ, pA_star, pB_star, pC_star]:
|
331 |
+
p.v2pt_theory(pD, F, A)
|
332 |
+
|
333 |
+
# points of B, C touching the plane P
|
334 |
+
pB_hat = pB_star.locatenew('B^', -R*A.x)
|
335 |
+
pC_hat = pC_star.locatenew('C^', -R*A.x)
|
336 |
+
pB_hat.v2pt_theory(pB_star, F, B)
|
337 |
+
pC_hat.v2pt_theory(pC_star, F, C)
|
338 |
+
|
339 |
+
# --- relate qdot, u ---
|
340 |
+
# the velocities of B^, C^ are zero since B, C are assumed to roll w/o slip
|
341 |
+
kde = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
|
342 |
+
kde += [u1 - q1d]
|
343 |
+
kde_map = solve(kde, [q1d, q2d, q3d])
|
344 |
+
for k, v in list(kde_map.items()):
|
345 |
+
kde_map[k.diff(t)] = v.diff(t)
|
346 |
+
|
347 |
+
# inertias of bodies A, B, C
|
348 |
+
# IA22, IA23, IA33 are not specified in the problem statement, but are
|
349 |
+
# necessary to define an inertia object. Although the values of
|
350 |
+
# IA22, IA23, IA33 are not known in terms of the variables given in the
|
351 |
+
# problem statement, they do not appear in the general inertia terms.
|
352 |
+
inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
|
353 |
+
inertia_B = inertia(B, K, K, J)
|
354 |
+
inertia_C = inertia(C, K, K, J)
|
355 |
+
|
356 |
+
# define the rigid bodies A, B, C
|
357 |
+
rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
|
358 |
+
rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
|
359 |
+
rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
|
360 |
+
|
361 |
+
## --- use kanes method ---
|
362 |
+
km = KanesMethod(F, [q1, q2, q3], [u1, u2], kd_eqs=kde, u_auxiliary=[u3])
|
363 |
+
|
364 |
+
forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
|
365 |
+
bodies = [rbA, rbB, rbC]
|
366 |
+
|
367 |
+
# Q2 = -u_prime * u2 * Q1 / sqrt(u2**2 + f**2 * u1**2)
|
368 |
+
# -u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2) = R / Q1 * Q2
|
369 |
+
fr_expected = Matrix([
|
370 |
+
f*Q3 + M*g*e*sin(theta)*cos(q1),
|
371 |
+
Q2 + M*g*sin(theta)*sin(q1),
|
372 |
+
e*M*g*cos(theta) - Q1*f - Q2*R])
|
373 |
+
#Q1 * (f - u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2)))])
|
374 |
+
fr_star_expected = Matrix([
|
375 |
+
-(IA + 2*J*b**2/R**2 + 2*K +
|
376 |
+
mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
|
377 |
+
-(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
|
378 |
+
0])
|
379 |
+
|
380 |
+
fr, fr_star = km.kanes_equations(bodies, forces)
|
381 |
+
assert (fr.expand() == fr_expected.expand())
|
382 |
+
assert ((fr_star_expected - trigsimp(fr_star)).expand() == zeros(3, 1))
|
383 |
+
|
384 |
+
def test_sub_qdot2():
|
385 |
+
# This test solves exercises 8.3 from Kane 1985 and defines
|
386 |
+
# all velocities in terms of q, qdot. We check that the generalized active
|
387 |
+
# forces are correctly computed if u terms are only defined in the
|
388 |
+
# kinematic differential equations.
|
389 |
+
#
|
390 |
+
# This functionality was added in PR 8948. Without qdot/u substitution, the
|
391 |
+
# KanesMethod constructor will fail during the constraint initialization as
|
392 |
+
# the B matrix will be poorly formed and inversion of the dependent part
|
393 |
+
# will fail.
|
394 |
+
|
395 |
+
g, m, Px, Py, Pz, R, t = symbols('g m Px Py Pz R t')
|
396 |
+
q = dynamicsymbols('q:5')
|
397 |
+
qd = dynamicsymbols('q:5', level=1)
|
398 |
+
u = dynamicsymbols('u:5')
|
399 |
+
|
400 |
+
## Define inertial, intermediate, and rigid body reference frames
|
401 |
+
A = ReferenceFrame('A')
|
402 |
+
B_prime = A.orientnew('B_prime', 'Axis', [q[0], A.z])
|
403 |
+
B = B_prime.orientnew('B', 'Axis', [pi/2 - q[1], B_prime.x])
|
404 |
+
C = B.orientnew('C', 'Axis', [q[2], B.z])
|
405 |
+
|
406 |
+
## Define points of interest and their velocities
|
407 |
+
pO = Point('O')
|
408 |
+
pO.set_vel(A, 0)
|
409 |
+
|
410 |
+
# R is the point in plane H that comes into contact with disk C.
|
411 |
+
pR = pO.locatenew('R', q[3]*A.x + q[4]*A.y)
|
412 |
+
pR.set_vel(A, pR.pos_from(pO).diff(t, A))
|
413 |
+
pR.set_vel(B, 0)
|
414 |
+
|
415 |
+
# C^ is the point in disk C that comes into contact with plane H.
|
416 |
+
pC_hat = pR.locatenew('C^', 0)
|
417 |
+
pC_hat.set_vel(C, 0)
|
418 |
+
|
419 |
+
# C* is the point at the center of disk C.
|
420 |
+
pCs = pC_hat.locatenew('C*', R*B.y)
|
421 |
+
pCs.set_vel(C, 0)
|
422 |
+
pCs.set_vel(B, 0)
|
423 |
+
|
424 |
+
# calculate velocites of points C* and C^ in frame A
|
425 |
+
pCs.v2pt_theory(pR, A, B) # points C* and R are fixed in frame B
|
426 |
+
pC_hat.v2pt_theory(pCs, A, C) # points C* and C^ are fixed in frame C
|
427 |
+
|
428 |
+
## Define forces on each point of the system
|
429 |
+
R_C_hat = Px*A.x + Py*A.y + Pz*A.z
|
430 |
+
R_Cs = -m*g*A.z
|
431 |
+
forces = [(pC_hat, R_C_hat), (pCs, R_Cs)]
|
432 |
+
|
433 |
+
## Define kinematic differential equations
|
434 |
+
# let ui = omega_C_A & bi (i = 1, 2, 3)
|
435 |
+
# u4 = qd4, u5 = qd5
|
436 |
+
u_expr = [C.ang_vel_in(A) & uv for uv in B]
|
437 |
+
u_expr += qd[3:]
|
438 |
+
kde = [ui - e for ui, e in zip(u, u_expr)]
|
439 |
+
km1 = KanesMethod(A, q, u, kde)
|
440 |
+
fr1, _ = km1.kanes_equations([], forces)
|
441 |
+
|
442 |
+
## Calculate generalized active forces if we impose the condition that the
|
443 |
+
# disk C is rolling without slipping
|
444 |
+
u_indep = u[:3]
|
445 |
+
u_dep = list(set(u) - set(u_indep))
|
446 |
+
vc = [pC_hat.vel(A) & uv for uv in [A.x, A.y]]
|
447 |
+
km2 = KanesMethod(A, q, u_indep, kde,
|
448 |
+
u_dependent=u_dep, velocity_constraints=vc)
|
449 |
+
fr2, _ = km2.kanes_equations([], forces)
|
450 |
+
|
451 |
+
fr1_expected = Matrix([
|
452 |
+
-R*g*m*sin(q[1]),
|
453 |
+
-R*(Px*cos(q[0]) + Py*sin(q[0]))*tan(q[1]),
|
454 |
+
R*(Px*cos(q[0]) + Py*sin(q[0])),
|
455 |
+
Px,
|
456 |
+
Py])
|
457 |
+
fr2_expected = Matrix([
|
458 |
+
-R*g*m*sin(q[1]),
|
459 |
+
0,
|
460 |
+
0])
|
461 |
+
assert (trigsimp(fr1.expand()) == trigsimp(fr1_expected.expand()))
|
462 |
+
assert (trigsimp(fr2.expand()) == trigsimp(fr2_expected.expand()))
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane3.py
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.evalf import evalf
|
2 |
+
from sympy.core.numbers import pi
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
5 |
+
from sympy.functions.elementary.trigonometric import acos, sin, cos
|
6 |
+
from sympy.matrices.dense import Matrix
|
7 |
+
from sympy.physics.mechanics import (ReferenceFrame, dynamicsymbols,
|
8 |
+
KanesMethod, inertia, msubs, Point, RigidBody, dot)
|
9 |
+
from sympy.testing.pytest import slow, ON_CI, skip
|
10 |
+
|
11 |
+
|
12 |
+
@slow
|
13 |
+
def test_bicycle():
|
14 |
+
if ON_CI:
|
15 |
+
skip("Too slow for CI.")
|
16 |
+
# Code to get equations of motion for a bicycle modeled as in:
|
17 |
+
# J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized
|
18 |
+
# dynamics equations for the balance and steer of a bicycle: a benchmark
|
19 |
+
# and review. Proceedings of The Royal Society (2007) 463, 1955-1982
|
20 |
+
# doi: 10.1098/rspa.2007.1857
|
21 |
+
|
22 |
+
# Note that this code has been crudely ported from Autolev, which is the
|
23 |
+
# reason for some of the unusual naming conventions. It was purposefully as
|
24 |
+
# similar as possible in order to aide debugging.
|
25 |
+
|
26 |
+
# Declare Coordinates & Speeds
|
27 |
+
# Simple definitions for qdots - qd = u
|
28 |
+
# Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame
|
29 |
+
# ang. rate (spinning motion), frame ang. rate (pitching motion), steering
|
30 |
+
# frame ang. rate, and front wheel ang. rate (spinning motion).
|
31 |
+
# Wheel positions are ignorable coordinates, so they are not introduced.
|
32 |
+
q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5')
|
33 |
+
q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1)
|
34 |
+
u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6')
|
35 |
+
u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1)
|
36 |
+
|
37 |
+
# Declare System's Parameters
|
38 |
+
WFrad, WRrad, htangle, forkoffset = symbols('WFrad WRrad htangle forkoffset')
|
39 |
+
forklength, framelength, forkcg1 = symbols('forklength framelength forkcg1')
|
40 |
+
forkcg3, framecg1, framecg3, Iwr11 = symbols('forkcg3 framecg1 framecg3 Iwr11')
|
41 |
+
Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11')
|
42 |
+
Iframe22, Iframe33, Iframe31, Ifork11 = symbols('Iframe22 Iframe33 Iframe31 Ifork11')
|
43 |
+
Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g')
|
44 |
+
mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr')
|
45 |
+
|
46 |
+
# Set up reference frames for the system
|
47 |
+
# N - inertial
|
48 |
+
# Y - yaw
|
49 |
+
# R - roll
|
50 |
+
# WR - rear wheel, rotation angle is ignorable coordinate so not oriented
|
51 |
+
# Frame - bicycle frame
|
52 |
+
# TempFrame - statically rotated frame for easier reference inertia definition
|
53 |
+
# Fork - bicycle fork
|
54 |
+
# TempFork - statically rotated frame for easier reference inertia definition
|
55 |
+
# WF - front wheel, again posses a ignorable coordinate
|
56 |
+
N = ReferenceFrame('N')
|
57 |
+
Y = N.orientnew('Y', 'Axis', [q1, N.z])
|
58 |
+
R = Y.orientnew('R', 'Axis', [q2, Y.x])
|
59 |
+
Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y])
|
60 |
+
WR = ReferenceFrame('WR')
|
61 |
+
TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y])
|
62 |
+
Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x])
|
63 |
+
TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y])
|
64 |
+
WF = ReferenceFrame('WF')
|
65 |
+
|
66 |
+
# Kinematics of the Bicycle First block of code is forming the positions of
|
67 |
+
# the relevant points
|
68 |
+
# rear wheel contact -> rear wheel mass center -> frame mass center +
|
69 |
+
# frame/fork connection -> fork mass center + front wheel mass center ->
|
70 |
+
# front wheel contact point
|
71 |
+
WR_cont = Point('WR_cont')
|
72 |
+
WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z)
|
73 |
+
Steer = WR_mc.locatenew('Steer', framelength * Frame.z)
|
74 |
+
Frame_mc = WR_mc.locatenew('Frame_mc', - framecg1 * Frame.x
|
75 |
+
+ framecg3 * Frame.z)
|
76 |
+
Fork_mc = Steer.locatenew('Fork_mc', - forkcg1 * Fork.x
|
77 |
+
+ forkcg3 * Fork.z)
|
78 |
+
WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z)
|
79 |
+
WF_cont = WF_mc.locatenew('WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y -
|
80 |
+
Y.z).normalize())
|
81 |
+
|
82 |
+
# Set the angular velocity of each frame.
|
83 |
+
# Angular accelerations end up being calculated automatically by
|
84 |
+
# differentiating the angular velocities when first needed.
|
85 |
+
# u1 is yaw rate
|
86 |
+
# u2 is roll rate
|
87 |
+
# u3 is rear wheel rate
|
88 |
+
# u4 is frame pitch rate
|
89 |
+
# u5 is fork steer rate
|
90 |
+
# u6 is front wheel rate
|
91 |
+
Y.set_ang_vel(N, u1 * Y.z)
|
92 |
+
R.set_ang_vel(Y, u2 * R.x)
|
93 |
+
WR.set_ang_vel(Frame, u3 * Frame.y)
|
94 |
+
Frame.set_ang_vel(R, u4 * Frame.y)
|
95 |
+
Fork.set_ang_vel(Frame, u5 * Fork.x)
|
96 |
+
WF.set_ang_vel(Fork, u6 * Fork.y)
|
97 |
+
|
98 |
+
# Form the velocities of the previously defined points, using the 2 - point
|
99 |
+
# theorem (written out by hand here). Accelerations again are calculated
|
100 |
+
# automatically when first needed.
|
101 |
+
WR_cont.set_vel(N, 0)
|
102 |
+
WR_mc.v2pt_theory(WR_cont, N, WR)
|
103 |
+
Steer.v2pt_theory(WR_mc, N, Frame)
|
104 |
+
Frame_mc.v2pt_theory(WR_mc, N, Frame)
|
105 |
+
Fork_mc.v2pt_theory(Steer, N, Fork)
|
106 |
+
WF_mc.v2pt_theory(Steer, N, Fork)
|
107 |
+
WF_cont.v2pt_theory(WF_mc, N, WF)
|
108 |
+
|
109 |
+
# Sets the inertias of each body. Uses the inertia frame to construct the
|
110 |
+
# inertia dyadics. Wheel inertias are only defined by principle moments of
|
111 |
+
# inertia, and are in fact constant in the frame and fork reference frames;
|
112 |
+
# it is for this reason that the orientations of the wheels does not need
|
113 |
+
# to be defined. The frame and fork inertias are defined in the 'Temp'
|
114 |
+
# frames which are fixed to the appropriate body frames; this is to allow
|
115 |
+
# easier input of the reference values of the benchmark paper. Note that
|
116 |
+
# due to slightly different orientations, the products of inertia need to
|
117 |
+
# have their signs flipped; this is done later when entering the numerical
|
118 |
+
# value.
|
119 |
+
|
120 |
+
Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc)
|
121 |
+
Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc)
|
122 |
+
WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc)
|
123 |
+
WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc)
|
124 |
+
|
125 |
+
# Declaration of the RigidBody containers. ::
|
126 |
+
|
127 |
+
BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I)
|
128 |
+
BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I)
|
129 |
+
BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I)
|
130 |
+
BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I)
|
131 |
+
|
132 |
+
# The kinematic differential equations; they are defined quite simply. Each
|
133 |
+
# entry in this list is equal to zero.
|
134 |
+
kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5]
|
135 |
+
|
136 |
+
# The nonholonomic constraints are the velocity of the front wheel contact
|
137 |
+
# point dotted into the X, Y, and Z directions; the yaw frame is used as it
|
138 |
+
# is "closer" to the front wheel (1 less DCM connecting them). These
|
139 |
+
# constraints force the velocity of the front wheel contact point to be 0
|
140 |
+
# in the inertial frame; the X and Y direction constraints enforce a
|
141 |
+
# "no-slip" condition, and the Z direction constraint forces the front
|
142 |
+
# wheel contact point to not move away from the ground frame, essentially
|
143 |
+
# replicating the holonomic constraint which does not allow the frame pitch
|
144 |
+
# to change in an invalid fashion.
|
145 |
+
|
146 |
+
conlist_speed = [WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z]
|
147 |
+
|
148 |
+
# The holonomic constraint is that the position from the rear wheel contact
|
149 |
+
# point to the front wheel contact point when dotted into the
|
150 |
+
# normal-to-ground plane direction must be zero; effectively that the front
|
151 |
+
# and rear wheel contact points are always touching the ground plane. This
|
152 |
+
# is actually not part of the dynamic equations, but instead is necessary
|
153 |
+
# for the lineraization process.
|
154 |
+
|
155 |
+
conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z]
|
156 |
+
|
157 |
+
# The force list; each body has the appropriate gravitational force applied
|
158 |
+
# at its mass center.
|
159 |
+
FL = [(Frame_mc, -mframe * g * Y.z),
|
160 |
+
(Fork_mc, -mfork * g * Y.z),
|
161 |
+
(WF_mc, -mwf * g * Y.z),
|
162 |
+
(WR_mc, -mwr * g * Y.z)]
|
163 |
+
BL = [BodyFrame, BodyFork, BodyWR, BodyWF]
|
164 |
+
|
165 |
+
|
166 |
+
# The N frame is the inertial frame, coordinates are supplied in the order
|
167 |
+
# of independent, dependent coordinates, as are the speeds. The kinematic
|
168 |
+
# differential equation are also entered here. Here the dependent speeds
|
169 |
+
# are specified, in the same order they were provided in earlier, along
|
170 |
+
# with the non-holonomic constraints. The dependent coordinate is also
|
171 |
+
# provided, with the holonomic constraint. Again, this is only provided
|
172 |
+
# for the linearization process.
|
173 |
+
|
174 |
+
KM = KanesMethod(N, q_ind=[q1, q2, q5],
|
175 |
+
q_dependent=[q4], configuration_constraints=conlist_coord,
|
176 |
+
u_ind=[u2, u3, u5],
|
177 |
+
u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed,
|
178 |
+
kd_eqs=kd)
|
179 |
+
(fr, frstar) = KM.kanes_equations(BL, FL)
|
180 |
+
|
181 |
+
# This is the start of entering in the numerical values from the benchmark
|
182 |
+
# paper to validate the eigen values of the linearized equations from this
|
183 |
+
# model to the reference eigen values. Look at the aforementioned paper for
|
184 |
+
# more information. Some of these are intermediate values, used to
|
185 |
+
# transform values from the paper into the coordinate systems used in this
|
186 |
+
# model.
|
187 |
+
PaperRadRear = 0.3
|
188 |
+
PaperRadFront = 0.35
|
189 |
+
HTA = evalf.N(pi / 2 - pi / 10)
|
190 |
+
TrailPaper = 0.08
|
191 |
+
rake = evalf.N(-(TrailPaper*sin(HTA)-(PaperRadFront*cos(HTA))))
|
192 |
+
PaperWb = 1.02
|
193 |
+
PaperFrameCgX = 0.3
|
194 |
+
PaperFrameCgZ = 0.9
|
195 |
+
PaperForkCgX = 0.9
|
196 |
+
PaperForkCgZ = 0.7
|
197 |
+
FrameLength = evalf.N(PaperWb*sin(HTA)-(rake-(PaperRadFront-PaperRadRear)*cos(HTA)))
|
198 |
+
FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear-(PaperFrameCgX/sin(HTA))*cos(HTA))*sin(HTA))
|
199 |
+
FrameCGPar = evalf.N(PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA))
|
200 |
+
tempa = evalf.N(PaperForkCgZ - PaperRadFront)
|
201 |
+
tempb = evalf.N(PaperWb-PaperForkCgX)
|
202 |
+
tempc = evalf.N(sqrt(tempa**2+tempb**2))
|
203 |
+
PaperForkL = evalf.N(PaperWb*cos(HTA)-(PaperRadFront-PaperRadRear)*sin(HTA))
|
204 |
+
ForkCGNorm = evalf.N(rake+(tempc * sin(pi/2-HTA-acos(tempa/tempc))))
|
205 |
+
ForkCGPar = evalf.N(tempc * cos((pi/2-HTA)-acos(tempa/tempc))-PaperForkL)
|
206 |
+
|
207 |
+
# Here is the final assembly of the numerical values. The symbol 'v' is the
|
208 |
+
# forward speed of the bicycle (a concept which only makes sense in the
|
209 |
+
# upright, static equilibrium case?). These are in a dictionary which will
|
210 |
+
# later be substituted in. Again the sign on the *product* of inertia
|
211 |
+
# values is flipped here, due to different orientations of coordinate
|
212 |
+
# systems.
|
213 |
+
v = symbols('v')
|
214 |
+
val_dict = {WFrad: PaperRadFront,
|
215 |
+
WRrad: PaperRadRear,
|
216 |
+
htangle: HTA,
|
217 |
+
forkoffset: rake,
|
218 |
+
forklength: PaperForkL,
|
219 |
+
framelength: FrameLength,
|
220 |
+
forkcg1: ForkCGPar,
|
221 |
+
forkcg3: ForkCGNorm,
|
222 |
+
framecg1: FrameCGNorm,
|
223 |
+
framecg3: FrameCGPar,
|
224 |
+
Iwr11: 0.0603,
|
225 |
+
Iwr22: 0.12,
|
226 |
+
Iwf11: 0.1405,
|
227 |
+
Iwf22: 0.28,
|
228 |
+
Ifork11: 0.05892,
|
229 |
+
Ifork22: 0.06,
|
230 |
+
Ifork33: 0.00708,
|
231 |
+
Ifork31: 0.00756,
|
232 |
+
Iframe11: 9.2,
|
233 |
+
Iframe22: 11,
|
234 |
+
Iframe33: 2.8,
|
235 |
+
Iframe31: -2.4,
|
236 |
+
mfork: 4,
|
237 |
+
mframe: 85,
|
238 |
+
mwf: 3,
|
239 |
+
mwr: 2,
|
240 |
+
g: 9.81,
|
241 |
+
q1: 0,
|
242 |
+
q2: 0,
|
243 |
+
q4: 0,
|
244 |
+
q5: 0,
|
245 |
+
u1: 0,
|
246 |
+
u2: 0,
|
247 |
+
u3: v / PaperRadRear,
|
248 |
+
u4: 0,
|
249 |
+
u5: 0,
|
250 |
+
u6: v / PaperRadFront}
|
251 |
+
|
252 |
+
# Linearizes the forcing vector; the equations are set up as MM udot =
|
253 |
+
# forcing, where MM is the mass matrix, udot is the vector representing the
|
254 |
+
# time derivatives of the generalized speeds, and forcing is a vector which
|
255 |
+
# contains both external forcing terms and internal forcing terms, such as
|
256 |
+
# centripital or coriolis forces. This actually returns a matrix with as
|
257 |
+
# many rows as *total* coordinates and speeds, but only as many columns as
|
258 |
+
# independent coordinates and speeds.
|
259 |
+
|
260 |
+
forcing_lin = KM.linearize()[0]
|
261 |
+
|
262 |
+
# As mentioned above, the size of the linearized forcing terms is expanded
|
263 |
+
# to include both q's and u's, so the mass matrix must have this done as
|
264 |
+
# well. This will likely be changed to be part of the linearized process,
|
265 |
+
# for future reference.
|
266 |
+
MM_full = KM.mass_matrix_full
|
267 |
+
|
268 |
+
MM_full_s = msubs(MM_full, val_dict)
|
269 |
+
forcing_lin_s = msubs(forcing_lin, KM.kindiffdict(), val_dict)
|
270 |
+
|
271 |
+
MM_full_s = MM_full_s.evalf()
|
272 |
+
forcing_lin_s = forcing_lin_s.evalf()
|
273 |
+
|
274 |
+
# Finally, we construct an "A" matrix for the form xdot = A x (x being the
|
275 |
+
# state vector, although in this case, the sizes are a little off). The
|
276 |
+
# following line extracts only the minimum entries required for eigenvalue
|
277 |
+
# analysis, which correspond to rows and columns for lean, steer, lean
|
278 |
+
# rate, and steer rate.
|
279 |
+
Amat = MM_full_s.inv() * forcing_lin_s
|
280 |
+
A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5])
|
281 |
+
|
282 |
+
# Precomputed for comparison
|
283 |
+
Res = Matrix([[ 0, 0, 1.0, 0],
|
284 |
+
[ 0, 0, 0, 1.0],
|
285 |
+
[9.48977444677355, -0.891197738059089*v**2 - 0.571523173729245, -0.105522449805691*v, -0.330515398992311*v],
|
286 |
+
[11.7194768719633, -1.97171508499972*v**2 + 30.9087533932407, 3.67680523332152*v, -3.08486552743311*v]])
|
287 |
+
|
288 |
+
|
289 |
+
# Actual eigenvalue comparison
|
290 |
+
eps = 1.e-12
|
291 |
+
for i in range(6):
|
292 |
+
error = Res.subs(v, i) - A.subs(v, i)
|
293 |
+
assert all(abs(x) < eps for x in error)
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange.py
ADDED
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
|
2 |
+
RigidBody, LagrangesMethod, Particle,
|
3 |
+
inertia, Lagrangian)
|
4 |
+
from sympy.core.function import (Derivative, Function)
|
5 |
+
from sympy.core.numbers import pi
|
6 |
+
from sympy.core.symbol import symbols
|
7 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
8 |
+
from sympy.matrices.dense import Matrix
|
9 |
+
from sympy.simplify.simplify import simplify
|
10 |
+
from sympy.testing.pytest import raises
|
11 |
+
|
12 |
+
|
13 |
+
def test_invalid_coordinates():
|
14 |
+
# Simple pendulum, but use symbol instead of dynamicsymbol
|
15 |
+
l, m, g = symbols('l m g')
|
16 |
+
q = symbols('q') # Generalized coordinate
|
17 |
+
N, O = ReferenceFrame('N'), Point('O')
|
18 |
+
O.set_vel(N, 0)
|
19 |
+
P = Particle('P', Point('P'), m)
|
20 |
+
P.point.set_pos(O, l * (sin(q) * N.x - cos(q) * N.y))
|
21 |
+
P.potential_energy = m * g * P.point.pos_from(O).dot(N.y)
|
22 |
+
L = Lagrangian(N, P)
|
23 |
+
raises(ValueError, lambda: LagrangesMethod(L, [q], bodies=P))
|
24 |
+
|
25 |
+
|
26 |
+
def test_disc_on_an_incline_plane():
|
27 |
+
# Disc rolling on an inclined plane
|
28 |
+
# First the generalized coordinates are created. The mass center of the
|
29 |
+
# disc is located from top vertex of the inclined plane by the generalized
|
30 |
+
# coordinate 'y'. The orientation of the disc is defined by the angle
|
31 |
+
# 'theta'. The mass of the disc is 'm' and its radius is 'R'. The length of
|
32 |
+
# the inclined path is 'l', the angle of inclination is 'alpha'. 'g' is the
|
33 |
+
# gravitational constant.
|
34 |
+
y, theta = dynamicsymbols('y theta')
|
35 |
+
yd, thetad = dynamicsymbols('y theta', 1)
|
36 |
+
m, g, R, l, alpha = symbols('m g R l alpha')
|
37 |
+
|
38 |
+
# Next, we create the inertial reference frame 'N'. A reference frame 'A'
|
39 |
+
# is attached to the inclined plane. Finally a frame is created which is attached to the disk.
|
40 |
+
N = ReferenceFrame('N')
|
41 |
+
A = N.orientnew('A', 'Axis', [pi/2 - alpha, N.z])
|
42 |
+
B = A.orientnew('B', 'Axis', [-theta, A.z])
|
43 |
+
|
44 |
+
# Creating the disc 'D'; we create the point that represents the mass
|
45 |
+
# center of the disc and set its velocity. The inertia dyadic of the disc
|
46 |
+
# is created. Finally, we create the disc.
|
47 |
+
Do = Point('Do')
|
48 |
+
Do.set_vel(N, yd * A.x)
|
49 |
+
I = m * R**2/2 * B.z | B.z
|
50 |
+
D = RigidBody('D', Do, B, m, (I, Do))
|
51 |
+
|
52 |
+
# To construct the Lagrangian, 'L', of the disc, we determine its kinetic
|
53 |
+
# and potential energies, T and U, respectively. L is defined as the
|
54 |
+
# difference between T and U.
|
55 |
+
D.potential_energy = m * g * (l - y) * sin(alpha)
|
56 |
+
L = Lagrangian(N, D)
|
57 |
+
|
58 |
+
# We then create the list of generalized coordinates and constraint
|
59 |
+
# equations. The constraint arises due to the disc rolling without slip on
|
60 |
+
# on the inclined path. We then invoke the 'LagrangesMethod' class and
|
61 |
+
# supply it the necessary arguments and generate the equations of motion.
|
62 |
+
# The'rhs' method solves for the q_double_dots (i.e. the second derivative
|
63 |
+
# with respect to time of the generalized coordinates and the lagrange
|
64 |
+
# multipliers.
|
65 |
+
q = [y, theta]
|
66 |
+
hol_coneqs = [y - R * theta]
|
67 |
+
m = LagrangesMethod(L, q, hol_coneqs=hol_coneqs)
|
68 |
+
m.form_lagranges_equations()
|
69 |
+
rhs = m.rhs()
|
70 |
+
rhs.simplify()
|
71 |
+
assert rhs[2] == 2*g*sin(alpha)/3
|
72 |
+
|
73 |
+
|
74 |
+
def test_simp_pen():
|
75 |
+
# This tests that the equations generated by LagrangesMethod are identical
|
76 |
+
# to those obtained by hand calculations. The system under consideration is
|
77 |
+
# the simple pendulum.
|
78 |
+
# We begin by creating the generalized coordinates as per the requirements
|
79 |
+
# of LagrangesMethod. Also we created the associate symbols
|
80 |
+
# that characterize the system: 'm' is the mass of the bob, l is the length
|
81 |
+
# of the massless rigid rod connecting the bob to a point O fixed in the
|
82 |
+
# inertial frame.
|
83 |
+
q, u = dynamicsymbols('q u')
|
84 |
+
qd, ud = dynamicsymbols('q u ', 1)
|
85 |
+
l, m, g = symbols('l m g')
|
86 |
+
|
87 |
+
# We then create the inertial frame and a frame attached to the massless
|
88 |
+
# string following which we define the inertial angular velocity of the
|
89 |
+
# string.
|
90 |
+
N = ReferenceFrame('N')
|
91 |
+
A = N.orientnew('A', 'Axis', [q, N.z])
|
92 |
+
A.set_ang_vel(N, qd * N.z)
|
93 |
+
|
94 |
+
# Next, we create the point O and fix it in the inertial frame. We then
|
95 |
+
# locate the point P to which the bob is attached. Its corresponding
|
96 |
+
# velocity is then determined by the 'two point formula'.
|
97 |
+
O = Point('O')
|
98 |
+
O.set_vel(N, 0)
|
99 |
+
P = O.locatenew('P', l * A.x)
|
100 |
+
P.v2pt_theory(O, N, A)
|
101 |
+
|
102 |
+
# The 'Particle' which represents the bob is then created and its
|
103 |
+
# Lagrangian generated.
|
104 |
+
Pa = Particle('Pa', P, m)
|
105 |
+
Pa.potential_energy = - m * g * l * cos(q)
|
106 |
+
L = Lagrangian(N, Pa)
|
107 |
+
|
108 |
+
# The 'LagrangesMethod' class is invoked to obtain equations of motion.
|
109 |
+
lm = LagrangesMethod(L, [q])
|
110 |
+
lm.form_lagranges_equations()
|
111 |
+
RHS = lm.rhs()
|
112 |
+
assert RHS[1] == -g*sin(q)/l
|
113 |
+
|
114 |
+
|
115 |
+
def test_nonminimal_pendulum():
|
116 |
+
q1, q2 = dynamicsymbols('q1:3')
|
117 |
+
q1d, q2d = dynamicsymbols('q1:3', level=1)
|
118 |
+
L, m, t = symbols('L, m, t')
|
119 |
+
g = 9.8
|
120 |
+
# Compose World Frame
|
121 |
+
N = ReferenceFrame('N')
|
122 |
+
pN = Point('N*')
|
123 |
+
pN.set_vel(N, 0)
|
124 |
+
# Create point P, the pendulum mass
|
125 |
+
P = pN.locatenew('P1', q1*N.x + q2*N.y)
|
126 |
+
P.set_vel(N, P.pos_from(pN).dt(N))
|
127 |
+
pP = Particle('pP', P, m)
|
128 |
+
# Constraint Equations
|
129 |
+
f_c = Matrix([q1**2 + q2**2 - L**2])
|
130 |
+
# Calculate the lagrangian, and form the equations of motion
|
131 |
+
Lag = Lagrangian(N, pP)
|
132 |
+
LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c,
|
133 |
+
forcelist=[(P, m*g*N.x)], frame=N)
|
134 |
+
LM.form_lagranges_equations()
|
135 |
+
# Check solution
|
136 |
+
lam1 = LM.lam_vec[0, 0]
|
137 |
+
eom_sol = Matrix([[m*Derivative(q1, t, t) - 9.8*m + 2*lam1*q1],
|
138 |
+
[m*Derivative(q2, t, t) + 2*lam1*q2]])
|
139 |
+
assert LM.eom == eom_sol
|
140 |
+
# Check multiplier solution
|
141 |
+
lam_sol = Matrix([(19.6*q1 + 2*q1d**2 + 2*q2d**2)/(4*q1**2/m + 4*q2**2/m)])
|
142 |
+
assert simplify(LM.solve_multipliers(sol_type='Matrix')) == simplify(lam_sol)
|
143 |
+
|
144 |
+
|
145 |
+
def test_dub_pen():
|
146 |
+
|
147 |
+
# The system considered is the double pendulum. Like in the
|
148 |
+
# test of the simple pendulum above, we begin by creating the generalized
|
149 |
+
# coordinates and the simple generalized speeds and accelerations which
|
150 |
+
# will be used later. Following this we create frames and points necessary
|
151 |
+
# for the kinematics. The procedure isn't explicitly explained as this is
|
152 |
+
# similar to the simple pendulum. Also this is documented on the pydy.org
|
153 |
+
# website.
|
154 |
+
q1, q2 = dynamicsymbols('q1 q2')
|
155 |
+
q1d, q2d = dynamicsymbols('q1 q2', 1)
|
156 |
+
q1dd, q2dd = dynamicsymbols('q1 q2', 2)
|
157 |
+
u1, u2 = dynamicsymbols('u1 u2')
|
158 |
+
u1d, u2d = dynamicsymbols('u1 u2', 1)
|
159 |
+
l, m, g = symbols('l m g')
|
160 |
+
|
161 |
+
N = ReferenceFrame('N')
|
162 |
+
A = N.orientnew('A', 'Axis', [q1, N.z])
|
163 |
+
B = N.orientnew('B', 'Axis', [q2, N.z])
|
164 |
+
|
165 |
+
A.set_ang_vel(N, q1d * A.z)
|
166 |
+
B.set_ang_vel(N, q2d * A.z)
|
167 |
+
|
168 |
+
O = Point('O')
|
169 |
+
P = O.locatenew('P', l * A.x)
|
170 |
+
R = P.locatenew('R', l * B.x)
|
171 |
+
|
172 |
+
O.set_vel(N, 0)
|
173 |
+
P.v2pt_theory(O, N, A)
|
174 |
+
R.v2pt_theory(P, N, B)
|
175 |
+
|
176 |
+
ParP = Particle('ParP', P, m)
|
177 |
+
ParR = Particle('ParR', R, m)
|
178 |
+
|
179 |
+
ParP.potential_energy = - m * g * l * cos(q1)
|
180 |
+
ParR.potential_energy = - m * g * l * cos(q1) - m * g * l * cos(q2)
|
181 |
+
L = Lagrangian(N, ParP, ParR)
|
182 |
+
lm = LagrangesMethod(L, [q1, q2], bodies=[ParP, ParR])
|
183 |
+
lm.form_lagranges_equations()
|
184 |
+
|
185 |
+
assert simplify(l*m*(2*g*sin(q1) + l*sin(q1)*sin(q2)*q2dd
|
186 |
+
+ l*sin(q1)*cos(q2)*q2d**2 - l*sin(q2)*cos(q1)*q2d**2
|
187 |
+
+ l*cos(q1)*cos(q2)*q2dd + 2*l*q1dd) - lm.eom[0]) == 0
|
188 |
+
assert simplify(l*m*(g*sin(q2) + l*sin(q1)*sin(q2)*q1dd
|
189 |
+
- l*sin(q1)*cos(q2)*q1d**2 + l*sin(q2)*cos(q1)*q1d**2
|
190 |
+
+ l*cos(q1)*cos(q2)*q1dd + l*q2dd) - lm.eom[1]) == 0
|
191 |
+
assert lm.bodies == [ParP, ParR]
|
192 |
+
|
193 |
+
|
194 |
+
def test_rolling_disc():
|
195 |
+
# Rolling Disc Example
|
196 |
+
# Here the rolling disc is formed from the contact point up, removing the
|
197 |
+
# need to introduce generalized speeds. Only 3 configuration and 3
|
198 |
+
# speed variables are need to describe this system, along with the
|
199 |
+
# disc's mass and radius, and the local gravity.
|
200 |
+
q1, q2, q3 = dynamicsymbols('q1 q2 q3')
|
201 |
+
q1d, q2d, q3d = dynamicsymbols('q1 q2 q3', 1)
|
202 |
+
r, m, g = symbols('r m g')
|
203 |
+
|
204 |
+
# The kinematics are formed by a series of simple rotations. Each simple
|
205 |
+
# rotation creates a new frame, and the next rotation is defined by the new
|
206 |
+
# frame's basis vectors. This example uses a 3-1-2 series of rotations, or
|
207 |
+
# Z, X, Y series of rotations. Angular velocity for this is defined using
|
208 |
+
# the second frame's basis (the lean frame).
|
209 |
+
N = ReferenceFrame('N')
|
210 |
+
Y = N.orientnew('Y', 'Axis', [q1, N.z])
|
211 |
+
L = Y.orientnew('L', 'Axis', [q2, Y.x])
|
212 |
+
R = L.orientnew('R', 'Axis', [q3, L.y])
|
213 |
+
|
214 |
+
# This is the translational kinematics. We create a point with no velocity
|
215 |
+
# in N; this is the contact point between the disc and ground. Next we form
|
216 |
+
# the position vector from the contact point to the disc's center of mass.
|
217 |
+
# Finally we form the velocity and acceleration of the disc.
|
218 |
+
C = Point('C')
|
219 |
+
C.set_vel(N, 0)
|
220 |
+
Dmc = C.locatenew('Dmc', r * L.z)
|
221 |
+
Dmc.v2pt_theory(C, N, R)
|
222 |
+
|
223 |
+
# Forming the inertia dyadic.
|
224 |
+
I = inertia(L, m/4 * r**2, m/2 * r**2, m/4 * r**2)
|
225 |
+
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
|
226 |
+
|
227 |
+
# Finally we form the equations of motion, using the same steps we did
|
228 |
+
# before. Supply the Lagrangian, the generalized speeds.
|
229 |
+
BodyD.potential_energy = - m * g * r * cos(q2)
|
230 |
+
Lag = Lagrangian(N, BodyD)
|
231 |
+
q = [q1, q2, q3]
|
232 |
+
q1 = Function('q1')
|
233 |
+
q2 = Function('q2')
|
234 |
+
q3 = Function('q3')
|
235 |
+
l = LagrangesMethod(Lag, q)
|
236 |
+
l.form_lagranges_equations()
|
237 |
+
RHS = l.rhs()
|
238 |
+
RHS.simplify()
|
239 |
+
t = symbols('t')
|
240 |
+
|
241 |
+
assert (l.mass_matrix[3:6] == [0, 5*m*r**2/4, 0])
|
242 |
+
assert RHS[4].simplify() == (
|
243 |
+
(-8*g*sin(q2(t)) + r*(5*sin(2*q2(t))*Derivative(q1(t), t) +
|
244 |
+
12*cos(q2(t))*Derivative(q3(t), t))*Derivative(q1(t), t))/(10*r))
|
245 |
+
assert RHS[5] == (-5*cos(q2(t))*Derivative(q1(t), t) + 6*tan(q2(t)
|
246 |
+
)*Derivative(q3(t), t) + 4*Derivative(q1(t), t)/cos(q2(t))
|
247 |
+
)*Derivative(q2(t), t)
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_linearize.py
ADDED
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.backend import (symbols, Matrix, cos, sin, atan, sqrt,
|
2 |
+
Rational, _simplify_matrix)
|
3 |
+
from sympy.core.sympify import sympify
|
4 |
+
from sympy.simplify.simplify import simplify
|
5 |
+
from sympy.solvers.solvers import solve
|
6 |
+
from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame, Point,\
|
7 |
+
dot, cross, inertia, KanesMethod, Particle, RigidBody, Lagrangian,\
|
8 |
+
LagrangesMethod
|
9 |
+
from sympy.testing.pytest import slow
|
10 |
+
|
11 |
+
|
12 |
+
@slow
|
13 |
+
def test_linearize_rolling_disc_kane():
|
14 |
+
# Symbols for time and constant parameters
|
15 |
+
t, r, m, g, v = symbols('t r m g v')
|
16 |
+
|
17 |
+
# Configuration variables and their time derivatives
|
18 |
+
q1, q2, q3, q4, q5, q6 = q = dynamicsymbols('q1:7')
|
19 |
+
q1d, q2d, q3d, q4d, q5d, q6d = qd = [qi.diff(t) for qi in q]
|
20 |
+
|
21 |
+
# Generalized speeds and their time derivatives
|
22 |
+
u = dynamicsymbols('u:6')
|
23 |
+
u1, u2, u3, u4, u5, u6 = u = dynamicsymbols('u1:7')
|
24 |
+
u1d, u2d, u3d, u4d, u5d, u6d = [ui.diff(t) for ui in u]
|
25 |
+
|
26 |
+
# Reference frames
|
27 |
+
N = ReferenceFrame('N') # Inertial frame
|
28 |
+
NO = Point('NO') # Inertial origin
|
29 |
+
A = N.orientnew('A', 'Axis', [q1, N.z]) # Yaw intermediate frame
|
30 |
+
B = A.orientnew('B', 'Axis', [q2, A.x]) # Lean intermediate frame
|
31 |
+
C = B.orientnew('C', 'Axis', [q3, B.y]) # Disc fixed frame
|
32 |
+
CO = NO.locatenew('CO', q4*N.x + q5*N.y + q6*N.z) # Disc center
|
33 |
+
|
34 |
+
# Disc angular velocity in N expressed using time derivatives of coordinates
|
35 |
+
w_c_n_qd = C.ang_vel_in(N)
|
36 |
+
w_b_n_qd = B.ang_vel_in(N)
|
37 |
+
|
38 |
+
# Inertial angular velocity and angular acceleration of disc fixed frame
|
39 |
+
C.set_ang_vel(N, u1*B.x + u2*B.y + u3*B.z)
|
40 |
+
|
41 |
+
# Disc center velocity in N expressed using time derivatives of coordinates
|
42 |
+
v_co_n_qd = CO.pos_from(NO).dt(N)
|
43 |
+
|
44 |
+
# Disc center velocity in N expressed using generalized speeds
|
45 |
+
CO.set_vel(N, u4*C.x + u5*C.y + u6*C.z)
|
46 |
+
|
47 |
+
# Disc Ground Contact Point
|
48 |
+
P = CO.locatenew('P', r*B.z)
|
49 |
+
P.v2pt_theory(CO, N, C)
|
50 |
+
|
51 |
+
# Configuration constraint
|
52 |
+
f_c = Matrix([q6 - dot(CO.pos_from(P), N.z)])
|
53 |
+
|
54 |
+
# Velocity level constraints
|
55 |
+
f_v = Matrix([dot(P.vel(N), uv) for uv in C])
|
56 |
+
|
57 |
+
# Kinematic differential equations
|
58 |
+
kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
|
59 |
+
[dot(v_co_n_qd - CO.vel(N), uv) for uv in N])
|
60 |
+
qdots = solve(kindiffs, qd)
|
61 |
+
|
62 |
+
# Set angular velocity of remaining frames
|
63 |
+
B.set_ang_vel(N, w_b_n_qd.subs(qdots))
|
64 |
+
C.set_ang_acc(N, C.ang_vel_in(N).dt(B) + cross(B.ang_vel_in(N), C.ang_vel_in(N)))
|
65 |
+
|
66 |
+
# Active forces
|
67 |
+
F_CO = m*g*A.z
|
68 |
+
|
69 |
+
# Create inertia dyadic of disc C about point CO
|
70 |
+
I = (m * r**2) / 4
|
71 |
+
J = (m * r**2) / 2
|
72 |
+
I_C_CO = inertia(C, I, J, I)
|
73 |
+
|
74 |
+
Disc = RigidBody('Disc', CO, C, m, (I_C_CO, CO))
|
75 |
+
BL = [Disc]
|
76 |
+
FL = [(CO, F_CO)]
|
77 |
+
KM = KanesMethod(N, [q1, q2, q3, q4, q5], [u1, u2, u3], kd_eqs=kindiffs,
|
78 |
+
q_dependent=[q6], configuration_constraints=f_c,
|
79 |
+
u_dependent=[u4, u5, u6], velocity_constraints=f_v)
|
80 |
+
(fr, fr_star) = KM.kanes_equations(BL, FL)
|
81 |
+
|
82 |
+
# Test generalized form equations
|
83 |
+
linearizer = KM.to_linearizer()
|
84 |
+
assert linearizer.f_c == f_c
|
85 |
+
assert linearizer.f_v == f_v
|
86 |
+
assert linearizer.f_a == f_v.diff(t).subs(KM.kindiffdict())
|
87 |
+
sol = solve(linearizer.f_0 + linearizer.f_1, qd)
|
88 |
+
for qi in qdots.keys():
|
89 |
+
assert sol[qi] == qdots[qi]
|
90 |
+
assert simplify(linearizer.f_2 + linearizer.f_3 - fr - fr_star) == Matrix([0, 0, 0])
|
91 |
+
|
92 |
+
# Perform the linearization
|
93 |
+
# Precomputed operating point
|
94 |
+
q_op = {q6: -r*cos(q2)}
|
95 |
+
u_op = {u1: 0,
|
96 |
+
u2: sin(q2)*q1d + q3d,
|
97 |
+
u3: cos(q2)*q1d,
|
98 |
+
u4: -r*(sin(q2)*q1d + q3d)*cos(q3),
|
99 |
+
u5: 0,
|
100 |
+
u6: -r*(sin(q2)*q1d + q3d)*sin(q3)}
|
101 |
+
qd_op = {q2d: 0,
|
102 |
+
q4d: -r*(sin(q2)*q1d + q3d)*cos(q1),
|
103 |
+
q5d: -r*(sin(q2)*q1d + q3d)*sin(q1),
|
104 |
+
q6d: 0}
|
105 |
+
ud_op = {u1d: 4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5,
|
106 |
+
u2d: 0,
|
107 |
+
u3d: 0,
|
108 |
+
u4d: r*(sin(q2)*sin(q3)*q1d*q3d + sin(q3)*q3d**2),
|
109 |
+
u5d: r*(4*g*sin(q2)/(5*r) + sin(2*q2)*q1d**2/2 + 6*cos(q2)*q1d*q3d/5),
|
110 |
+
u6d: -r*(sin(q2)*cos(q3)*q1d*q3d + cos(q3)*q3d**2)}
|
111 |
+
|
112 |
+
A, B = linearizer.linearize(op_point=[q_op, u_op, qd_op, ud_op], A_and_B=True, simplify=True)
|
113 |
+
|
114 |
+
upright_nominal = {q1d: 0, q2: 0, m: 1, r: 1, g: 1}
|
115 |
+
|
116 |
+
# Precomputed solution
|
117 |
+
A_sol = Matrix([[0, 0, 0, 0, 0, 0, 0, 1],
|
118 |
+
[0, 0, 0, 0, 0, 1, 0, 0],
|
119 |
+
[0, 0, 0, 0, 0, 0, 1, 0],
|
120 |
+
[sin(q1)*q3d, 0, 0, 0, 0, -sin(q1), -cos(q1), 0],
|
121 |
+
[-cos(q1)*q3d, 0, 0, 0, 0, cos(q1), -sin(q1), 0],
|
122 |
+
[0, Rational(4, 5), 0, 0, 0, 0, 0, 6*q3d/5],
|
123 |
+
[0, 0, 0, 0, 0, 0, 0, 0],
|
124 |
+
[0, 0, 0, 0, 0, -2*q3d, 0, 0]])
|
125 |
+
B_sol = Matrix([])
|
126 |
+
|
127 |
+
# Check that linearization is correct
|
128 |
+
assert A.subs(upright_nominal) == A_sol
|
129 |
+
assert B.subs(upright_nominal) == B_sol
|
130 |
+
|
131 |
+
# Check eigenvalues at critical speed are all zero:
|
132 |
+
assert sympify(A.subs(upright_nominal).subs(q3d, 1/sqrt(3))).eigenvals() == {0: 8}
|
133 |
+
|
134 |
+
def test_linearize_pendulum_kane_minimal():
|
135 |
+
q1 = dynamicsymbols('q1') # angle of pendulum
|
136 |
+
u1 = dynamicsymbols('u1') # Angular velocity
|
137 |
+
q1d = dynamicsymbols('q1', 1) # Angular velocity
|
138 |
+
L, m, t = symbols('L, m, t')
|
139 |
+
g = 9.8
|
140 |
+
|
141 |
+
# Compose world frame
|
142 |
+
N = ReferenceFrame('N')
|
143 |
+
pN = Point('N*')
|
144 |
+
pN.set_vel(N, 0)
|
145 |
+
|
146 |
+
# A.x is along the pendulum
|
147 |
+
A = N.orientnew('A', 'axis', [q1, N.z])
|
148 |
+
A.set_ang_vel(N, u1*N.z)
|
149 |
+
|
150 |
+
# Locate point P relative to the origin N*
|
151 |
+
P = pN.locatenew('P', L*A.x)
|
152 |
+
P.v2pt_theory(pN, N, A)
|
153 |
+
pP = Particle('pP', P, m)
|
154 |
+
|
155 |
+
# Create Kinematic Differential Equations
|
156 |
+
kde = Matrix([q1d - u1])
|
157 |
+
|
158 |
+
# Input the force resultant at P
|
159 |
+
R = m*g*N.x
|
160 |
+
|
161 |
+
# Solve for eom with kanes method
|
162 |
+
KM = KanesMethod(N, q_ind=[q1], u_ind=[u1], kd_eqs=kde)
|
163 |
+
(fr, frstar) = KM.kanes_equations([pP], [(P, R)])
|
164 |
+
|
165 |
+
# Linearize
|
166 |
+
A, B, inp_vec = KM.linearize(A_and_B=True, simplify=True)
|
167 |
+
|
168 |
+
assert A == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]])
|
169 |
+
assert B == Matrix([])
|
170 |
+
|
171 |
+
def test_linearize_pendulum_kane_nonminimal():
|
172 |
+
# Create generalized coordinates and speeds for this non-minimal realization
|
173 |
+
# q1, q2 = N.x and N.y coordinates of pendulum
|
174 |
+
# u1, u2 = N.x and N.y velocities of pendulum
|
175 |
+
q1, q2 = dynamicsymbols('q1:3')
|
176 |
+
q1d, q2d = dynamicsymbols('q1:3', level=1)
|
177 |
+
u1, u2 = dynamicsymbols('u1:3')
|
178 |
+
u1d, u2d = dynamicsymbols('u1:3', level=1)
|
179 |
+
L, m, t = symbols('L, m, t')
|
180 |
+
g = 9.8
|
181 |
+
|
182 |
+
# Compose world frame
|
183 |
+
N = ReferenceFrame('N')
|
184 |
+
pN = Point('N*')
|
185 |
+
pN.set_vel(N, 0)
|
186 |
+
|
187 |
+
# A.x is along the pendulum
|
188 |
+
theta1 = atan(q2/q1)
|
189 |
+
A = N.orientnew('A', 'axis', [theta1, N.z])
|
190 |
+
|
191 |
+
# Locate the pendulum mass
|
192 |
+
P = pN.locatenew('P1', q1*N.x + q2*N.y)
|
193 |
+
pP = Particle('pP', P, m)
|
194 |
+
|
195 |
+
# Calculate the kinematic differential equations
|
196 |
+
kde = Matrix([q1d - u1,
|
197 |
+
q2d - u2])
|
198 |
+
dq_dict = solve(kde, [q1d, q2d])
|
199 |
+
|
200 |
+
# Set velocity of point P
|
201 |
+
P.set_vel(N, P.pos_from(pN).dt(N).subs(dq_dict))
|
202 |
+
|
203 |
+
# Configuration constraint is length of pendulum
|
204 |
+
f_c = Matrix([P.pos_from(pN).magnitude() - L])
|
205 |
+
|
206 |
+
# Velocity constraint is that the velocity in the A.x direction is
|
207 |
+
# always zero (the pendulum is never getting longer).
|
208 |
+
f_v = Matrix([P.vel(N).express(A).dot(A.x)])
|
209 |
+
f_v.simplify()
|
210 |
+
|
211 |
+
# Acceleration constraints is the time derivative of the velocity constraint
|
212 |
+
f_a = f_v.diff(t)
|
213 |
+
f_a.simplify()
|
214 |
+
|
215 |
+
# Input the force resultant at P
|
216 |
+
R = m*g*N.x
|
217 |
+
|
218 |
+
# Derive the equations of motion using the KanesMethod class.
|
219 |
+
KM = KanesMethod(N, q_ind=[q2], u_ind=[u2], q_dependent=[q1],
|
220 |
+
u_dependent=[u1], configuration_constraints=f_c,
|
221 |
+
velocity_constraints=f_v, acceleration_constraints=f_a, kd_eqs=kde)
|
222 |
+
(fr, frstar) = KM.kanes_equations([pP], [(P, R)])
|
223 |
+
|
224 |
+
# Set the operating point to be straight down, and non-moving
|
225 |
+
q_op = {q1: L, q2: 0}
|
226 |
+
u_op = {u1: 0, u2: 0}
|
227 |
+
ud_op = {u1d: 0, u2d: 0}
|
228 |
+
|
229 |
+
A, B, inp_vec = KM.linearize(op_point=[q_op, u_op, ud_op], A_and_B=True,
|
230 |
+
simplify=True)
|
231 |
+
|
232 |
+
assert A.expand() == Matrix([[0, 1], [-9.8/L, 0]])
|
233 |
+
assert B == Matrix([])
|
234 |
+
|
235 |
+
def test_linearize_pendulum_lagrange_minimal():
|
236 |
+
q1 = dynamicsymbols('q1') # angle of pendulum
|
237 |
+
q1d = dynamicsymbols('q1', 1) # Angular velocity
|
238 |
+
L, m, t = symbols('L, m, t')
|
239 |
+
g = 9.8
|
240 |
+
|
241 |
+
# Compose world frame
|
242 |
+
N = ReferenceFrame('N')
|
243 |
+
pN = Point('N*')
|
244 |
+
pN.set_vel(N, 0)
|
245 |
+
|
246 |
+
# A.x is along the pendulum
|
247 |
+
A = N.orientnew('A', 'axis', [q1, N.z])
|
248 |
+
A.set_ang_vel(N, q1d*N.z)
|
249 |
+
|
250 |
+
# Locate point P relative to the origin N*
|
251 |
+
P = pN.locatenew('P', L*A.x)
|
252 |
+
P.v2pt_theory(pN, N, A)
|
253 |
+
pP = Particle('pP', P, m)
|
254 |
+
|
255 |
+
# Solve for eom with Lagranges method
|
256 |
+
Lag = Lagrangian(N, pP)
|
257 |
+
LM = LagrangesMethod(Lag, [q1], forcelist=[(P, m*g*N.x)], frame=N)
|
258 |
+
LM.form_lagranges_equations()
|
259 |
+
|
260 |
+
# Linearize
|
261 |
+
A, B, inp_vec = LM.linearize([q1], [q1d], A_and_B=True)
|
262 |
+
|
263 |
+
assert _simplify_matrix(A) == Matrix([[0, 1], [-9.8*cos(q1)/L, 0]])
|
264 |
+
assert B == Matrix([])
|
265 |
+
|
266 |
+
def test_linearize_pendulum_lagrange_nonminimal():
|
267 |
+
q1, q2 = dynamicsymbols('q1:3')
|
268 |
+
q1d, q2d = dynamicsymbols('q1:3', level=1)
|
269 |
+
L, m, t = symbols('L, m, t')
|
270 |
+
g = 9.8
|
271 |
+
# Compose World Frame
|
272 |
+
N = ReferenceFrame('N')
|
273 |
+
pN = Point('N*')
|
274 |
+
pN.set_vel(N, 0)
|
275 |
+
# A.x is along the pendulum
|
276 |
+
theta1 = atan(q2/q1)
|
277 |
+
A = N.orientnew('A', 'axis', [theta1, N.z])
|
278 |
+
# Create point P, the pendulum mass
|
279 |
+
P = pN.locatenew('P1', q1*N.x + q2*N.y)
|
280 |
+
P.set_vel(N, P.pos_from(pN).dt(N))
|
281 |
+
pP = Particle('pP', P, m)
|
282 |
+
# Constraint Equations
|
283 |
+
f_c = Matrix([q1**2 + q2**2 - L**2])
|
284 |
+
# Calculate the lagrangian, and form the equations of motion
|
285 |
+
Lag = Lagrangian(N, pP)
|
286 |
+
LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c, forcelist=[(P, m*g*N.x)], frame=N)
|
287 |
+
LM.form_lagranges_equations()
|
288 |
+
# Compose operating point
|
289 |
+
op_point = {q1: L, q2: 0, q1d: 0, q2d: 0, q1d.diff(t): 0, q2d.diff(t): 0}
|
290 |
+
# Solve for multiplier operating point
|
291 |
+
lam_op = LM.solve_multipliers(op_point=op_point)
|
292 |
+
op_point.update(lam_op)
|
293 |
+
# Perform the Linearization
|
294 |
+
A, B, inp_vec = LM.linearize([q2], [q2d], [q1], [q1d],
|
295 |
+
op_point=op_point, A_and_B=True)
|
296 |
+
assert _simplify_matrix(A) == Matrix([[0, 1], [-9.8/L, 0]])
|
297 |
+
assert B == Matrix([])
|
298 |
+
|
299 |
+
def test_linearize_rolling_disc_lagrange():
|
300 |
+
q1, q2, q3 = q = dynamicsymbols('q1 q2 q3')
|
301 |
+
q1d, q2d, q3d = qd = dynamicsymbols('q1 q2 q3', 1)
|
302 |
+
r, m, g = symbols('r m g')
|
303 |
+
|
304 |
+
N = ReferenceFrame('N')
|
305 |
+
Y = N.orientnew('Y', 'Axis', [q1, N.z])
|
306 |
+
L = Y.orientnew('L', 'Axis', [q2, Y.x])
|
307 |
+
R = L.orientnew('R', 'Axis', [q3, L.y])
|
308 |
+
|
309 |
+
C = Point('C')
|
310 |
+
C.set_vel(N, 0)
|
311 |
+
Dmc = C.locatenew('Dmc', r * L.z)
|
312 |
+
Dmc.v2pt_theory(C, N, R)
|
313 |
+
|
314 |
+
I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
|
315 |
+
BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
|
316 |
+
BodyD.potential_energy = - m * g * r * cos(q2)
|
317 |
+
|
318 |
+
Lag = Lagrangian(N, BodyD)
|
319 |
+
l = LagrangesMethod(Lag, q)
|
320 |
+
l.form_lagranges_equations()
|
321 |
+
|
322 |
+
# Linearize about steady-state upright rolling
|
323 |
+
op_point = {q1: 0, q2: 0, q3: 0,
|
324 |
+
q1d: 0, q2d: 0,
|
325 |
+
q1d.diff(): 0, q2d.diff(): 0, q3d.diff(): 0}
|
326 |
+
A = l.linearize(q_ind=q, qd_ind=qd, op_point=op_point, A_and_B=True)[0]
|
327 |
+
sol = Matrix([[0, 0, 0, 1, 0, 0],
|
328 |
+
[0, 0, 0, 0, 1, 0],
|
329 |
+
[0, 0, 0, 0, 0, 1],
|
330 |
+
[0, 0, 0, 0, -6*q3d, 0],
|
331 |
+
[0, -4*g/(5*r), 0, 6*q3d/5, 0, 0],
|
332 |
+
[0, 0, 0, 0, 0, 0]])
|
333 |
+
|
334 |
+
assert A == sol
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_particle.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import symbols
|
2 |
+
from sympy.physics.mechanics import Point, Particle, ReferenceFrame, inertia
|
3 |
+
|
4 |
+
from sympy.testing.pytest import raises, warns_deprecated_sympy
|
5 |
+
|
6 |
+
|
7 |
+
def test_particle():
|
8 |
+
m, m2, v1, v2, v3, r, g, h = symbols('m m2 v1 v2 v3 r g h')
|
9 |
+
P = Point('P')
|
10 |
+
P2 = Point('P2')
|
11 |
+
p = Particle('pa', P, m)
|
12 |
+
assert p.__str__() == 'pa'
|
13 |
+
assert p.mass == m
|
14 |
+
assert p.point == P
|
15 |
+
# Test the mass setter
|
16 |
+
p.mass = m2
|
17 |
+
assert p.mass == m2
|
18 |
+
# Test the point setter
|
19 |
+
p.point = P2
|
20 |
+
assert p.point == P2
|
21 |
+
# Test the linear momentum function
|
22 |
+
N = ReferenceFrame('N')
|
23 |
+
O = Point('O')
|
24 |
+
P2.set_pos(O, r * N.y)
|
25 |
+
P2.set_vel(N, v1 * N.x)
|
26 |
+
raises(TypeError, lambda: Particle(P, P, m))
|
27 |
+
raises(TypeError, lambda: Particle('pa', m, m))
|
28 |
+
assert p.linear_momentum(N) == m2 * v1 * N.x
|
29 |
+
assert p.angular_momentum(O, N) == -m2 * r *v1 * N.z
|
30 |
+
P2.set_vel(N, v2 * N.y)
|
31 |
+
assert p.linear_momentum(N) == m2 * v2 * N.y
|
32 |
+
assert p.angular_momentum(O, N) == 0
|
33 |
+
P2.set_vel(N, v3 * N.z)
|
34 |
+
assert p.linear_momentum(N) == m2 * v3 * N.z
|
35 |
+
assert p.angular_momentum(O, N) == m2 * r * v3 * N.x
|
36 |
+
P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
|
37 |
+
assert p.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
|
38 |
+
assert p.angular_momentum(O, N) == m2 * r * (v3 * N.x - v1 * N.z)
|
39 |
+
p.potential_energy = m * g * h
|
40 |
+
assert p.potential_energy == m * g * h
|
41 |
+
# TODO make the result not be system-dependent
|
42 |
+
assert p.kinetic_energy(
|
43 |
+
N) in [m2*(v1**2 + v2**2 + v3**2)/2,
|
44 |
+
m2 * v1**2 / 2 + m2 * v2**2 / 2 + m2 * v3**2 / 2]
|
45 |
+
|
46 |
+
|
47 |
+
def test_parallel_axis():
|
48 |
+
N = ReferenceFrame('N')
|
49 |
+
m, a, b = symbols('m, a, b')
|
50 |
+
o = Point('o')
|
51 |
+
p = o.locatenew('p', a * N.x + b * N.y)
|
52 |
+
P = Particle('P', o, m)
|
53 |
+
Ip = P.parallel_axis(p, N)
|
54 |
+
Ip_expected = inertia(N, m * b**2, m * a**2, m * (a**2 + b**2),
|
55 |
+
ixy=-m * a * b)
|
56 |
+
assert Ip == Ip_expected
|
57 |
+
|
58 |
+
def test_deprecated_set_potential_energy():
|
59 |
+
m, g, h = symbols('m g h')
|
60 |
+
P = Point('P')
|
61 |
+
p = Particle('pa', P, m)
|
62 |
+
with warns_deprecated_sympy():
|
63 |
+
p.set_potential_energy(m*g*h)
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_rigidbody.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import symbols
|
2 |
+
from sympy.physics.mechanics import Point, ReferenceFrame, Dyadic, RigidBody
|
3 |
+
from sympy.physics.mechanics import dynamicsymbols, outer, inertia
|
4 |
+
from sympy.physics.mechanics import inertia_of_point_mass
|
5 |
+
from sympy.core.backend import expand, zeros, _simplify_matrix
|
6 |
+
|
7 |
+
from sympy.testing.pytest import raises, warns_deprecated_sympy
|
8 |
+
|
9 |
+
|
10 |
+
def test_rigidbody():
|
11 |
+
m, m2, v1, v2, v3, omega = symbols('m m2 v1 v2 v3 omega')
|
12 |
+
A = ReferenceFrame('A')
|
13 |
+
A2 = ReferenceFrame('A2')
|
14 |
+
P = Point('P')
|
15 |
+
P2 = Point('P2')
|
16 |
+
I = Dyadic(0)
|
17 |
+
I2 = Dyadic(0)
|
18 |
+
B = RigidBody('B', P, A, m, (I, P))
|
19 |
+
assert B.mass == m
|
20 |
+
assert B.frame == A
|
21 |
+
assert B.masscenter == P
|
22 |
+
assert B.inertia == (I, B.masscenter)
|
23 |
+
|
24 |
+
B.mass = m2
|
25 |
+
B.frame = A2
|
26 |
+
B.masscenter = P2
|
27 |
+
B.inertia = (I2, B.masscenter)
|
28 |
+
raises(TypeError, lambda: RigidBody(P, P, A, m, (I, P)))
|
29 |
+
raises(TypeError, lambda: RigidBody('B', P, P, m, (I, P)))
|
30 |
+
raises(TypeError, lambda: RigidBody('B', P, A, m, (P, P)))
|
31 |
+
raises(TypeError, lambda: RigidBody('B', P, A, m, (I, I)))
|
32 |
+
assert B.__str__() == 'B'
|
33 |
+
assert B.mass == m2
|
34 |
+
assert B.frame == A2
|
35 |
+
assert B.masscenter == P2
|
36 |
+
assert B.inertia == (I2, B.masscenter)
|
37 |
+
assert B.masscenter == P2
|
38 |
+
assert B.inertia == (I2, B.masscenter)
|
39 |
+
|
40 |
+
# Testing linear momentum function assuming A2 is the inertial frame
|
41 |
+
N = ReferenceFrame('N')
|
42 |
+
P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
|
43 |
+
assert B.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
|
44 |
+
|
45 |
+
|
46 |
+
def test_rigidbody2():
|
47 |
+
M, v, r, omega, g, h = dynamicsymbols('M v r omega g h')
|
48 |
+
N = ReferenceFrame('N')
|
49 |
+
b = ReferenceFrame('b')
|
50 |
+
b.set_ang_vel(N, omega * b.x)
|
51 |
+
P = Point('P')
|
52 |
+
I = outer(b.x, b.x)
|
53 |
+
Inertia_tuple = (I, P)
|
54 |
+
B = RigidBody('B', P, b, M, Inertia_tuple)
|
55 |
+
P.set_vel(N, v * b.x)
|
56 |
+
assert B.angular_momentum(P, N) == omega * b.x
|
57 |
+
O = Point('O')
|
58 |
+
O.set_vel(N, v * b.x)
|
59 |
+
P.set_pos(O, r * b.y)
|
60 |
+
assert B.angular_momentum(O, N) == omega * b.x - M*v*r*b.z
|
61 |
+
B.potential_energy = M * g * h
|
62 |
+
assert B.potential_energy == M * g * h
|
63 |
+
assert expand(2 * B.kinetic_energy(N)) == omega**2 + M * v**2
|
64 |
+
|
65 |
+
def test_rigidbody3():
|
66 |
+
q1, q2, q3, q4 = dynamicsymbols('q1:5')
|
67 |
+
p1, p2, p3 = symbols('p1:4')
|
68 |
+
m = symbols('m')
|
69 |
+
|
70 |
+
A = ReferenceFrame('A')
|
71 |
+
B = A.orientnew('B', 'axis', [q1, A.x])
|
72 |
+
O = Point('O')
|
73 |
+
O.set_vel(A, q2*A.x + q3*A.y + q4*A.z)
|
74 |
+
P = O.locatenew('P', p1*B.x + p2*B.y + p3*B.z)
|
75 |
+
P.v2pt_theory(O, A, B)
|
76 |
+
I = outer(B.x, B.x)
|
77 |
+
|
78 |
+
rb1 = RigidBody('rb1', P, B, m, (I, P))
|
79 |
+
# I_S/O = I_S/S* + I_S*/O
|
80 |
+
rb2 = RigidBody('rb2', P, B, m,
|
81 |
+
(I + inertia_of_point_mass(m, P.pos_from(O), B), O))
|
82 |
+
|
83 |
+
assert rb1.central_inertia == rb2.central_inertia
|
84 |
+
assert rb1.angular_momentum(O, A) == rb2.angular_momentum(O, A)
|
85 |
+
|
86 |
+
|
87 |
+
def test_pendulum_angular_momentum():
|
88 |
+
"""Consider a pendulum of length OA = 2a, of mass m as a rigid body of
|
89 |
+
center of mass G (OG = a) which turn around (O,z). The angle between the
|
90 |
+
reference frame R and the rod is q. The inertia of the body is I =
|
91 |
+
(G,0,ma^2/3,ma^2/3). """
|
92 |
+
|
93 |
+
m, a = symbols('m, a')
|
94 |
+
q = dynamicsymbols('q')
|
95 |
+
|
96 |
+
R = ReferenceFrame('R')
|
97 |
+
R1 = R.orientnew('R1', 'Axis', [q, R.z])
|
98 |
+
R1.set_ang_vel(R, q.diff() * R.z)
|
99 |
+
|
100 |
+
I = inertia(R1, 0, m * a**2 / 3, m * a**2 / 3)
|
101 |
+
|
102 |
+
O = Point('O')
|
103 |
+
|
104 |
+
A = O.locatenew('A', 2*a * R1.x)
|
105 |
+
G = O.locatenew('G', a * R1.x)
|
106 |
+
|
107 |
+
S = RigidBody('S', G, R1, m, (I, G))
|
108 |
+
|
109 |
+
O.set_vel(R, 0)
|
110 |
+
A.v2pt_theory(O, R, R1)
|
111 |
+
G.v2pt_theory(O, R, R1)
|
112 |
+
|
113 |
+
assert (4 * m * a**2 / 3 * q.diff() * R.z -
|
114 |
+
S.angular_momentum(O, R).express(R)) == 0
|
115 |
+
|
116 |
+
|
117 |
+
def test_rigidbody_inertia():
|
118 |
+
N = ReferenceFrame('N')
|
119 |
+
m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
|
120 |
+
Io = inertia(N, Ix, Iy, Iz)
|
121 |
+
o = Point('o')
|
122 |
+
p = o.locatenew('p', a * N.x + b * N.y)
|
123 |
+
R = RigidBody('R', o, N, m, (Io, p))
|
124 |
+
I_check = inertia(N, Ix - b ** 2 * m, Iy - a ** 2 * m,
|
125 |
+
Iz - m * (a ** 2 + b ** 2), m * a * b)
|
126 |
+
assert R.inertia == (Io, p)
|
127 |
+
assert R.central_inertia == I_check
|
128 |
+
R.central_inertia = Io
|
129 |
+
assert R.inertia == (Io, o)
|
130 |
+
assert R.central_inertia == Io
|
131 |
+
R.inertia = (Io, p)
|
132 |
+
assert R.inertia == (Io, p)
|
133 |
+
assert R.central_inertia == I_check
|
134 |
+
|
135 |
+
|
136 |
+
def test_parallel_axis():
|
137 |
+
N = ReferenceFrame('N')
|
138 |
+
m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
|
139 |
+
Io = inertia(N, Ix, Iy, Iz)
|
140 |
+
o = Point('o')
|
141 |
+
p = o.locatenew('p', a * N.x + b * N.y)
|
142 |
+
R = RigidBody('R', o, N, m, (Io, o))
|
143 |
+
Ip = R.parallel_axis(p)
|
144 |
+
Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2,
|
145 |
+
Iz + m * (a**2 + b**2), ixy=-m * a * b)
|
146 |
+
assert Ip == Ip_expected
|
147 |
+
# Reference frame from which the parallel axis is viewed should not matter
|
148 |
+
A = ReferenceFrame('A')
|
149 |
+
A.orient_axis(N, N.z, 1)
|
150 |
+
assert _simplify_matrix(
|
151 |
+
(R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3)
|
152 |
+
|
153 |
+
|
154 |
+
def test_deprecated_set_potential_energy():
|
155 |
+
m, g, h = symbols('m g h')
|
156 |
+
A = ReferenceFrame('A')
|
157 |
+
P = Point('P')
|
158 |
+
I = Dyadic(0)
|
159 |
+
B = RigidBody('B', P, A, m, (I, P))
|
160 |
+
with warns_deprecated_sympy():
|
161 |
+
B.set_potential_energy(m*g*h)
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/boson.py
ADDED
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Bosonic quantum operators."""
|
2 |
+
|
3 |
+
from sympy.core.mul import Mul
|
4 |
+
from sympy.core.numbers import Integer
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.functions.elementary.complexes import conjugate
|
7 |
+
from sympy.functions.elementary.exponential import exp
|
8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
9 |
+
from sympy.physics.quantum import Operator
|
10 |
+
from sympy.physics.quantum import HilbertSpace, FockSpace, Ket, Bra, IdentityOperator
|
11 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
12 |
+
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
'BosonOp',
|
16 |
+
'BosonFockKet',
|
17 |
+
'BosonFockBra',
|
18 |
+
'BosonCoherentKet',
|
19 |
+
'BosonCoherentBra'
|
20 |
+
]
|
21 |
+
|
22 |
+
|
23 |
+
class BosonOp(Operator):
|
24 |
+
"""A bosonic operator that satisfies [a, Dagger(a)] == 1.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
==========
|
28 |
+
|
29 |
+
name : str
|
30 |
+
A string that labels the bosonic mode.
|
31 |
+
|
32 |
+
annihilation : bool
|
33 |
+
A bool that indicates if the bosonic operator is an annihilation (True,
|
34 |
+
default value) or creation operator (False)
|
35 |
+
|
36 |
+
Examples
|
37 |
+
========
|
38 |
+
|
39 |
+
>>> from sympy.physics.quantum import Dagger, Commutator
|
40 |
+
>>> from sympy.physics.quantum.boson import BosonOp
|
41 |
+
>>> a = BosonOp("a")
|
42 |
+
>>> Commutator(a, Dagger(a)).doit()
|
43 |
+
1
|
44 |
+
"""
|
45 |
+
|
46 |
+
@property
|
47 |
+
def name(self):
|
48 |
+
return self.args[0]
|
49 |
+
|
50 |
+
@property
|
51 |
+
def is_annihilation(self):
|
52 |
+
return bool(self.args[1])
|
53 |
+
|
54 |
+
@classmethod
|
55 |
+
def default_args(self):
|
56 |
+
return ("a", True)
|
57 |
+
|
58 |
+
def __new__(cls, *args, **hints):
|
59 |
+
if not len(args) in [1, 2]:
|
60 |
+
raise ValueError('1 or 2 parameters expected, got %s' % args)
|
61 |
+
|
62 |
+
if len(args) == 1:
|
63 |
+
args = (args[0], S.One)
|
64 |
+
|
65 |
+
if len(args) == 2:
|
66 |
+
args = (args[0], Integer(args[1]))
|
67 |
+
|
68 |
+
return Operator.__new__(cls, *args)
|
69 |
+
|
70 |
+
def _eval_commutator_BosonOp(self, other, **hints):
|
71 |
+
if self.name == other.name:
|
72 |
+
# [a^\dagger, a] = -1
|
73 |
+
if not self.is_annihilation and other.is_annihilation:
|
74 |
+
return S.NegativeOne
|
75 |
+
|
76 |
+
elif 'independent' in hints and hints['independent']:
|
77 |
+
# [a, b] = 0
|
78 |
+
return S.Zero
|
79 |
+
|
80 |
+
return None
|
81 |
+
|
82 |
+
def _eval_commutator_FermionOp(self, other, **hints):
|
83 |
+
return S.Zero
|
84 |
+
|
85 |
+
def _eval_anticommutator_BosonOp(self, other, **hints):
|
86 |
+
if 'independent' in hints and hints['independent']:
|
87 |
+
# {a, b} = 2 * a * b, because [a, b] = 0
|
88 |
+
return 2 * self * other
|
89 |
+
|
90 |
+
return None
|
91 |
+
|
92 |
+
def _eval_adjoint(self):
|
93 |
+
return BosonOp(str(self.name), not self.is_annihilation)
|
94 |
+
|
95 |
+
def __mul__(self, other):
|
96 |
+
|
97 |
+
if other == IdentityOperator(2):
|
98 |
+
return self
|
99 |
+
|
100 |
+
if isinstance(other, Mul):
|
101 |
+
args1 = tuple(arg for arg in other.args if arg.is_commutative)
|
102 |
+
args2 = tuple(arg for arg in other.args if not arg.is_commutative)
|
103 |
+
x = self
|
104 |
+
for y in args2:
|
105 |
+
x = x * y
|
106 |
+
return Mul(*args1) * x
|
107 |
+
|
108 |
+
return Mul(self, other)
|
109 |
+
|
110 |
+
def _print_contents_latex(self, printer, *args):
|
111 |
+
if self.is_annihilation:
|
112 |
+
return r'{%s}' % str(self.name)
|
113 |
+
else:
|
114 |
+
return r'{{%s}^\dagger}' % str(self.name)
|
115 |
+
|
116 |
+
def _print_contents(self, printer, *args):
|
117 |
+
if self.is_annihilation:
|
118 |
+
return r'%s' % str(self.name)
|
119 |
+
else:
|
120 |
+
return r'Dagger(%s)' % str(self.name)
|
121 |
+
|
122 |
+
def _print_contents_pretty(self, printer, *args):
|
123 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
124 |
+
pform = printer._print(self.args[0], *args)
|
125 |
+
if self.is_annihilation:
|
126 |
+
return pform
|
127 |
+
else:
|
128 |
+
return pform**prettyForm('\N{DAGGER}')
|
129 |
+
|
130 |
+
|
131 |
+
class BosonFockKet(Ket):
|
132 |
+
"""Fock state ket for a bosonic mode.
|
133 |
+
|
134 |
+
Parameters
|
135 |
+
==========
|
136 |
+
|
137 |
+
n : Number
|
138 |
+
The Fock state number.
|
139 |
+
|
140 |
+
"""
|
141 |
+
|
142 |
+
def __new__(cls, n):
|
143 |
+
return Ket.__new__(cls, n)
|
144 |
+
|
145 |
+
@property
|
146 |
+
def n(self):
|
147 |
+
return self.label[0]
|
148 |
+
|
149 |
+
@classmethod
|
150 |
+
def dual_class(self):
|
151 |
+
return BosonFockBra
|
152 |
+
|
153 |
+
@classmethod
|
154 |
+
def _eval_hilbert_space(cls, label):
|
155 |
+
return FockSpace()
|
156 |
+
|
157 |
+
def _eval_innerproduct_BosonFockBra(self, bra, **hints):
|
158 |
+
return KroneckerDelta(self.n, bra.n)
|
159 |
+
|
160 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
161 |
+
if op.is_annihilation:
|
162 |
+
return sqrt(self.n) * BosonFockKet(self.n - 1)
|
163 |
+
else:
|
164 |
+
return sqrt(self.n + 1) * BosonFockKet(self.n + 1)
|
165 |
+
|
166 |
+
|
167 |
+
class BosonFockBra(Bra):
|
168 |
+
"""Fock state bra for a bosonic mode.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
==========
|
172 |
+
|
173 |
+
n : Number
|
174 |
+
The Fock state number.
|
175 |
+
|
176 |
+
"""
|
177 |
+
|
178 |
+
def __new__(cls, n):
|
179 |
+
return Bra.__new__(cls, n)
|
180 |
+
|
181 |
+
@property
|
182 |
+
def n(self):
|
183 |
+
return self.label[0]
|
184 |
+
|
185 |
+
@classmethod
|
186 |
+
def dual_class(self):
|
187 |
+
return BosonFockKet
|
188 |
+
|
189 |
+
@classmethod
|
190 |
+
def _eval_hilbert_space(cls, label):
|
191 |
+
return FockSpace()
|
192 |
+
|
193 |
+
|
194 |
+
class BosonCoherentKet(Ket):
|
195 |
+
"""Coherent state ket for a bosonic mode.
|
196 |
+
|
197 |
+
Parameters
|
198 |
+
==========
|
199 |
+
|
200 |
+
alpha : Number, Symbol
|
201 |
+
The complex amplitude of the coherent state.
|
202 |
+
|
203 |
+
"""
|
204 |
+
|
205 |
+
def __new__(cls, alpha):
|
206 |
+
return Ket.__new__(cls, alpha)
|
207 |
+
|
208 |
+
@property
|
209 |
+
def alpha(self):
|
210 |
+
return self.label[0]
|
211 |
+
|
212 |
+
@classmethod
|
213 |
+
def dual_class(self):
|
214 |
+
return BosonCoherentBra
|
215 |
+
|
216 |
+
@classmethod
|
217 |
+
def _eval_hilbert_space(cls, label):
|
218 |
+
return HilbertSpace()
|
219 |
+
|
220 |
+
def _eval_innerproduct_BosonCoherentBra(self, bra, **hints):
|
221 |
+
if self.alpha == bra.alpha:
|
222 |
+
return S.One
|
223 |
+
else:
|
224 |
+
return exp(-(abs(self.alpha)**2 + abs(bra.alpha)**2 - 2 * conjugate(bra.alpha) * self.alpha)/2)
|
225 |
+
|
226 |
+
def _apply_from_right_to_BosonOp(self, op, **options):
|
227 |
+
if op.is_annihilation:
|
228 |
+
return self.alpha * self
|
229 |
+
else:
|
230 |
+
return None
|
231 |
+
|
232 |
+
|
233 |
+
class BosonCoherentBra(Bra):
|
234 |
+
"""Coherent state bra for a bosonic mode.
|
235 |
+
|
236 |
+
Parameters
|
237 |
+
==========
|
238 |
+
|
239 |
+
alpha : Number, Symbol
|
240 |
+
The complex amplitude of the coherent state.
|
241 |
+
|
242 |
+
"""
|
243 |
+
|
244 |
+
def __new__(cls, alpha):
|
245 |
+
return Bra.__new__(cls, alpha)
|
246 |
+
|
247 |
+
@property
|
248 |
+
def alpha(self):
|
249 |
+
return self.label[0]
|
250 |
+
|
251 |
+
@classmethod
|
252 |
+
def dual_class(self):
|
253 |
+
return BosonCoherentKet
|
254 |
+
|
255 |
+
def _apply_operator_BosonOp(self, op, **options):
|
256 |
+
if not op.is_annihilation:
|
257 |
+
return self.alpha * self
|
258 |
+
else:
|
259 |
+
return None
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/cartesian.py
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Operators and states for 1D cartesian position and momentum.
|
2 |
+
|
3 |
+
TODO:
|
4 |
+
|
5 |
+
* Add 3D classes to mappings in operatorset.py
|
6 |
+
|
7 |
+
"""
|
8 |
+
|
9 |
+
from sympy.core.numbers import (I, pi)
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.functions.elementary.exponential import exp
|
12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
13 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
14 |
+
from sympy.sets.sets import Interval
|
15 |
+
|
16 |
+
from sympy.physics.quantum.constants import hbar
|
17 |
+
from sympy.physics.quantum.hilbert import L2
|
18 |
+
from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator
|
19 |
+
from sympy.physics.quantum.state import Ket, Bra, State
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'XOp',
|
23 |
+
'YOp',
|
24 |
+
'ZOp',
|
25 |
+
'PxOp',
|
26 |
+
'X',
|
27 |
+
'Y',
|
28 |
+
'Z',
|
29 |
+
'Px',
|
30 |
+
'XKet',
|
31 |
+
'XBra',
|
32 |
+
'PxKet',
|
33 |
+
'PxBra',
|
34 |
+
'PositionState3D',
|
35 |
+
'PositionKet3D',
|
36 |
+
'PositionBra3D'
|
37 |
+
]
|
38 |
+
|
39 |
+
#-------------------------------------------------------------------------
|
40 |
+
# Position operators
|
41 |
+
#-------------------------------------------------------------------------
|
42 |
+
|
43 |
+
|
44 |
+
class XOp(HermitianOperator):
|
45 |
+
"""1D cartesian position operator."""
|
46 |
+
|
47 |
+
@classmethod
|
48 |
+
def default_args(self):
|
49 |
+
return ("X",)
|
50 |
+
|
51 |
+
@classmethod
|
52 |
+
def _eval_hilbert_space(self, args):
|
53 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
54 |
+
|
55 |
+
def _eval_commutator_PxOp(self, other):
|
56 |
+
return I*hbar
|
57 |
+
|
58 |
+
def _apply_operator_XKet(self, ket, **options):
|
59 |
+
return ket.position*ket
|
60 |
+
|
61 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
62 |
+
return ket.position_x*ket
|
63 |
+
|
64 |
+
def _represent_PxKet(self, basis, *, index=1, **options):
|
65 |
+
states = basis._enumerate_state(2, start_index=index)
|
66 |
+
coord1 = states[0].momentum
|
67 |
+
coord2 = states[1].momentum
|
68 |
+
d = DifferentialOperator(coord1)
|
69 |
+
delta = DiracDelta(coord1 - coord2)
|
70 |
+
|
71 |
+
return I*hbar*(d*delta)
|
72 |
+
|
73 |
+
|
74 |
+
class YOp(HermitianOperator):
|
75 |
+
""" Y cartesian coordinate operator (for 2D or 3D systems) """
|
76 |
+
|
77 |
+
@classmethod
|
78 |
+
def default_args(self):
|
79 |
+
return ("Y",)
|
80 |
+
|
81 |
+
@classmethod
|
82 |
+
def _eval_hilbert_space(self, args):
|
83 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
84 |
+
|
85 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
86 |
+
return ket.position_y*ket
|
87 |
+
|
88 |
+
|
89 |
+
class ZOp(HermitianOperator):
|
90 |
+
""" Z cartesian coordinate operator (for 3D systems) """
|
91 |
+
|
92 |
+
@classmethod
|
93 |
+
def default_args(self):
|
94 |
+
return ("Z",)
|
95 |
+
|
96 |
+
@classmethod
|
97 |
+
def _eval_hilbert_space(self, args):
|
98 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
99 |
+
|
100 |
+
def _apply_operator_PositionKet3D(self, ket, **options):
|
101 |
+
return ket.position_z*ket
|
102 |
+
|
103 |
+
#-------------------------------------------------------------------------
|
104 |
+
# Momentum operators
|
105 |
+
#-------------------------------------------------------------------------
|
106 |
+
|
107 |
+
|
108 |
+
class PxOp(HermitianOperator):
|
109 |
+
"""1D cartesian momentum operator."""
|
110 |
+
|
111 |
+
@classmethod
|
112 |
+
def default_args(self):
|
113 |
+
return ("Px",)
|
114 |
+
|
115 |
+
@classmethod
|
116 |
+
def _eval_hilbert_space(self, args):
|
117 |
+
return L2(Interval(S.NegativeInfinity, S.Infinity))
|
118 |
+
|
119 |
+
def _apply_operator_PxKet(self, ket, **options):
|
120 |
+
return ket.momentum*ket
|
121 |
+
|
122 |
+
def _represent_XKet(self, basis, *, index=1, **options):
|
123 |
+
states = basis._enumerate_state(2, start_index=index)
|
124 |
+
coord1 = states[0].position
|
125 |
+
coord2 = states[1].position
|
126 |
+
d = DifferentialOperator(coord1)
|
127 |
+
delta = DiracDelta(coord1 - coord2)
|
128 |
+
|
129 |
+
return -I*hbar*(d*delta)
|
130 |
+
|
131 |
+
X = XOp('X')
|
132 |
+
Y = YOp('Y')
|
133 |
+
Z = ZOp('Z')
|
134 |
+
Px = PxOp('Px')
|
135 |
+
|
136 |
+
#-------------------------------------------------------------------------
|
137 |
+
# Position eigenstates
|
138 |
+
#-------------------------------------------------------------------------
|
139 |
+
|
140 |
+
|
141 |
+
class XKet(Ket):
|
142 |
+
"""1D cartesian position eigenket."""
|
143 |
+
|
144 |
+
@classmethod
|
145 |
+
def _operators_to_state(self, op, **options):
|
146 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
147 |
+
|
148 |
+
def _state_to_operators(self, op_class, **options):
|
149 |
+
return op_class.__new__(op_class,
|
150 |
+
*_uppercase_labels(self), **options)
|
151 |
+
|
152 |
+
@classmethod
|
153 |
+
def default_args(self):
|
154 |
+
return ("x",)
|
155 |
+
|
156 |
+
@classmethod
|
157 |
+
def dual_class(self):
|
158 |
+
return XBra
|
159 |
+
|
160 |
+
@property
|
161 |
+
def position(self):
|
162 |
+
"""The position of the state."""
|
163 |
+
return self.label[0]
|
164 |
+
|
165 |
+
def _enumerate_state(self, num_states, **options):
|
166 |
+
return _enumerate_continuous_1D(self, num_states, **options)
|
167 |
+
|
168 |
+
def _eval_innerproduct_XBra(self, bra, **hints):
|
169 |
+
return DiracDelta(self.position - bra.position)
|
170 |
+
|
171 |
+
def _eval_innerproduct_PxBra(self, bra, **hints):
|
172 |
+
return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar)
|
173 |
+
|
174 |
+
|
175 |
+
class XBra(Bra):
|
176 |
+
"""1D cartesian position eigenbra."""
|
177 |
+
|
178 |
+
@classmethod
|
179 |
+
def default_args(self):
|
180 |
+
return ("x",)
|
181 |
+
|
182 |
+
@classmethod
|
183 |
+
def dual_class(self):
|
184 |
+
return XKet
|
185 |
+
|
186 |
+
@property
|
187 |
+
def position(self):
|
188 |
+
"""The position of the state."""
|
189 |
+
return self.label[0]
|
190 |
+
|
191 |
+
|
192 |
+
class PositionState3D(State):
|
193 |
+
""" Base class for 3D cartesian position eigenstates """
|
194 |
+
|
195 |
+
@classmethod
|
196 |
+
def _operators_to_state(self, op, **options):
|
197 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
198 |
+
|
199 |
+
def _state_to_operators(self, op_class, **options):
|
200 |
+
return op_class.__new__(op_class,
|
201 |
+
*_uppercase_labels(self), **options)
|
202 |
+
|
203 |
+
@classmethod
|
204 |
+
def default_args(self):
|
205 |
+
return ("x", "y", "z")
|
206 |
+
|
207 |
+
@property
|
208 |
+
def position_x(self):
|
209 |
+
""" The x coordinate of the state """
|
210 |
+
return self.label[0]
|
211 |
+
|
212 |
+
@property
|
213 |
+
def position_y(self):
|
214 |
+
""" The y coordinate of the state """
|
215 |
+
return self.label[1]
|
216 |
+
|
217 |
+
@property
|
218 |
+
def position_z(self):
|
219 |
+
""" The z coordinate of the state """
|
220 |
+
return self.label[2]
|
221 |
+
|
222 |
+
|
223 |
+
class PositionKet3D(Ket, PositionState3D):
|
224 |
+
""" 3D cartesian position eigenket """
|
225 |
+
|
226 |
+
def _eval_innerproduct_PositionBra3D(self, bra, **options):
|
227 |
+
x_diff = self.position_x - bra.position_x
|
228 |
+
y_diff = self.position_y - bra.position_y
|
229 |
+
z_diff = self.position_z - bra.position_z
|
230 |
+
|
231 |
+
return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff)
|
232 |
+
|
233 |
+
@classmethod
|
234 |
+
def dual_class(self):
|
235 |
+
return PositionBra3D
|
236 |
+
|
237 |
+
|
238 |
+
# XXX: The type:ignore here is because mypy gives Definition of
|
239 |
+
# "_state_to_operators" in base class "PositionState3D" is incompatible with
|
240 |
+
# definition in base class "BraBase"
|
241 |
+
class PositionBra3D(Bra, PositionState3D): # type: ignore
|
242 |
+
""" 3D cartesian position eigenbra """
|
243 |
+
|
244 |
+
@classmethod
|
245 |
+
def dual_class(self):
|
246 |
+
return PositionKet3D
|
247 |
+
|
248 |
+
#-------------------------------------------------------------------------
|
249 |
+
# Momentum eigenstates
|
250 |
+
#-------------------------------------------------------------------------
|
251 |
+
|
252 |
+
|
253 |
+
class PxKet(Ket):
|
254 |
+
"""1D cartesian momentum eigenket."""
|
255 |
+
|
256 |
+
@classmethod
|
257 |
+
def _operators_to_state(self, op, **options):
|
258 |
+
return self.__new__(self, *_lowercase_labels(op), **options)
|
259 |
+
|
260 |
+
def _state_to_operators(self, op_class, **options):
|
261 |
+
return op_class.__new__(op_class,
|
262 |
+
*_uppercase_labels(self), **options)
|
263 |
+
|
264 |
+
@classmethod
|
265 |
+
def default_args(self):
|
266 |
+
return ("px",)
|
267 |
+
|
268 |
+
@classmethod
|
269 |
+
def dual_class(self):
|
270 |
+
return PxBra
|
271 |
+
|
272 |
+
@property
|
273 |
+
def momentum(self):
|
274 |
+
"""The momentum of the state."""
|
275 |
+
return self.label[0]
|
276 |
+
|
277 |
+
def _enumerate_state(self, *args, **options):
|
278 |
+
return _enumerate_continuous_1D(self, *args, **options)
|
279 |
+
|
280 |
+
def _eval_innerproduct_XBra(self, bra, **hints):
|
281 |
+
return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar)
|
282 |
+
|
283 |
+
def _eval_innerproduct_PxBra(self, bra, **hints):
|
284 |
+
return DiracDelta(self.momentum - bra.momentum)
|
285 |
+
|
286 |
+
|
287 |
+
class PxBra(Bra):
|
288 |
+
"""1D cartesian momentum eigenbra."""
|
289 |
+
|
290 |
+
@classmethod
|
291 |
+
def default_args(self):
|
292 |
+
return ("px",)
|
293 |
+
|
294 |
+
@classmethod
|
295 |
+
def dual_class(self):
|
296 |
+
return PxKet
|
297 |
+
|
298 |
+
@property
|
299 |
+
def momentum(self):
|
300 |
+
"""The momentum of the state."""
|
301 |
+
return self.label[0]
|
302 |
+
|
303 |
+
#-------------------------------------------------------------------------
|
304 |
+
# Global helper functions
|
305 |
+
#-------------------------------------------------------------------------
|
306 |
+
|
307 |
+
|
308 |
+
def _enumerate_continuous_1D(*args, **options):
|
309 |
+
state = args[0]
|
310 |
+
num_states = args[1]
|
311 |
+
state_class = state.__class__
|
312 |
+
index_list = options.pop('index_list', [])
|
313 |
+
|
314 |
+
if len(index_list) == 0:
|
315 |
+
start_index = options.pop('start_index', 1)
|
316 |
+
index_list = list(range(start_index, start_index + num_states))
|
317 |
+
|
318 |
+
enum_states = [0 for i in range(len(index_list))]
|
319 |
+
|
320 |
+
for i, ind in enumerate(index_list):
|
321 |
+
label = state.args[0]
|
322 |
+
enum_states[i] = state_class(str(label) + "_" + str(ind), **options)
|
323 |
+
|
324 |
+
return enum_states
|
325 |
+
|
326 |
+
|
327 |
+
def _lowercase_labels(ops):
|
328 |
+
if not isinstance(ops, set):
|
329 |
+
ops = [ops]
|
330 |
+
|
331 |
+
return [str(arg.label[0]).lower() for arg in ops]
|
332 |
+
|
333 |
+
|
334 |
+
def _uppercase_labels(ops):
|
335 |
+
if not isinstance(ops, set):
|
336 |
+
ops = [ops]
|
337 |
+
|
338 |
+
new_args = [str(arg.label[0])[0].upper() +
|
339 |
+
str(arg.label[0])[1:] for arg in ops]
|
340 |
+
|
341 |
+
return new_args
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/cg.py
ADDED
@@ -0,0 +1,754 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#TODO:
|
2 |
+
# -Implement Clebsch-Gordan symmetries
|
3 |
+
# -Improve simplification method
|
4 |
+
# -Implement new simplifications
|
5 |
+
"""Clebsch-Gordon Coefficients."""
|
6 |
+
|
7 |
+
from sympy.concrete.summations import Sum
|
8 |
+
from sympy.core.add import Add
|
9 |
+
from sympy.core.expr import Expr
|
10 |
+
from sympy.core.function import expand
|
11 |
+
from sympy.core.mul import Mul
|
12 |
+
from sympy.core.power import Pow
|
13 |
+
from sympy.core.relational import Eq
|
14 |
+
from sympy.core.singleton import S
|
15 |
+
from sympy.core.symbol import (Wild, symbols)
|
16 |
+
from sympy.core.sympify import sympify
|
17 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
18 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
19 |
+
from sympy.printing.pretty.stringpict import prettyForm, stringPict
|
20 |
+
|
21 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
22 |
+
from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
|
23 |
+
from sympy.printing.precedence import PRECEDENCE
|
24 |
+
|
25 |
+
__all__ = [
|
26 |
+
'CG',
|
27 |
+
'Wigner3j',
|
28 |
+
'Wigner6j',
|
29 |
+
'Wigner9j',
|
30 |
+
'cg_simp'
|
31 |
+
]
|
32 |
+
|
33 |
+
#-----------------------------------------------------------------------------
|
34 |
+
# CG Coefficients
|
35 |
+
#-----------------------------------------------------------------------------
|
36 |
+
|
37 |
+
|
38 |
+
class Wigner3j(Expr):
|
39 |
+
"""Class for the Wigner-3j symbols.
|
40 |
+
|
41 |
+
Explanation
|
42 |
+
===========
|
43 |
+
|
44 |
+
Wigner 3j-symbols are coefficients determined by the coupling of
|
45 |
+
two angular momenta. When created, they are expressed as symbolic
|
46 |
+
quantities that, for numerical parameters, can be evaluated using the
|
47 |
+
``.doit()`` method [1]_.
|
48 |
+
|
49 |
+
Parameters
|
50 |
+
==========
|
51 |
+
|
52 |
+
j1, m1, j2, m2, j3, m3 : Number, Symbol
|
53 |
+
Terms determining the angular momentum of coupled angular momentum
|
54 |
+
systems.
|
55 |
+
|
56 |
+
Examples
|
57 |
+
========
|
58 |
+
|
59 |
+
Declare a Wigner-3j coefficient and calculate its value
|
60 |
+
|
61 |
+
>>> from sympy.physics.quantum.cg import Wigner3j
|
62 |
+
>>> w3j = Wigner3j(6,0,4,0,2,0)
|
63 |
+
>>> w3j
|
64 |
+
Wigner3j(6, 0, 4, 0, 2, 0)
|
65 |
+
>>> w3j.doit()
|
66 |
+
sqrt(715)/143
|
67 |
+
|
68 |
+
See Also
|
69 |
+
========
|
70 |
+
|
71 |
+
CG: Clebsch-Gordan coefficients
|
72 |
+
|
73 |
+
References
|
74 |
+
==========
|
75 |
+
|
76 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
77 |
+
"""
|
78 |
+
|
79 |
+
is_commutative = True
|
80 |
+
|
81 |
+
def __new__(cls, j1, m1, j2, m2, j3, m3):
|
82 |
+
args = map(sympify, (j1, m1, j2, m2, j3, m3))
|
83 |
+
return Expr.__new__(cls, *args)
|
84 |
+
|
85 |
+
@property
|
86 |
+
def j1(self):
|
87 |
+
return self.args[0]
|
88 |
+
|
89 |
+
@property
|
90 |
+
def m1(self):
|
91 |
+
return self.args[1]
|
92 |
+
|
93 |
+
@property
|
94 |
+
def j2(self):
|
95 |
+
return self.args[2]
|
96 |
+
|
97 |
+
@property
|
98 |
+
def m2(self):
|
99 |
+
return self.args[3]
|
100 |
+
|
101 |
+
@property
|
102 |
+
def j3(self):
|
103 |
+
return self.args[4]
|
104 |
+
|
105 |
+
@property
|
106 |
+
def m3(self):
|
107 |
+
return self.args[5]
|
108 |
+
|
109 |
+
@property
|
110 |
+
def is_symbolic(self):
|
111 |
+
return not all(arg.is_number for arg in self.args)
|
112 |
+
|
113 |
+
# This is modified from the _print_Matrix method
|
114 |
+
def _pretty(self, printer, *args):
|
115 |
+
m = ((printer._print(self.j1), printer._print(self.m1)),
|
116 |
+
(printer._print(self.j2), printer._print(self.m2)),
|
117 |
+
(printer._print(self.j3), printer._print(self.m3)))
|
118 |
+
hsep = 2
|
119 |
+
vsep = 1
|
120 |
+
maxw = [-1]*3
|
121 |
+
for j in range(3):
|
122 |
+
maxw[j] = max([ m[j][i].width() for i in range(2) ])
|
123 |
+
D = None
|
124 |
+
for i in range(2):
|
125 |
+
D_row = None
|
126 |
+
for j in range(3):
|
127 |
+
s = m[j][i]
|
128 |
+
wdelta = maxw[j] - s.width()
|
129 |
+
wleft = wdelta //2
|
130 |
+
wright = wdelta - wleft
|
131 |
+
|
132 |
+
s = prettyForm(*s.right(' '*wright))
|
133 |
+
s = prettyForm(*s.left(' '*wleft))
|
134 |
+
|
135 |
+
if D_row is None:
|
136 |
+
D_row = s
|
137 |
+
continue
|
138 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
139 |
+
D_row = prettyForm(*D_row.right(s))
|
140 |
+
if D is None:
|
141 |
+
D = D_row
|
142 |
+
continue
|
143 |
+
for _ in range(vsep):
|
144 |
+
D = prettyForm(*D.below(' '))
|
145 |
+
D = prettyForm(*D.below(D_row))
|
146 |
+
D = prettyForm(*D.parens())
|
147 |
+
return D
|
148 |
+
|
149 |
+
def _latex(self, printer, *args):
|
150 |
+
label = map(printer._print, (self.j1, self.j2, self.j3,
|
151 |
+
self.m1, self.m2, self.m3))
|
152 |
+
return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
|
153 |
+
tuple(label)
|
154 |
+
|
155 |
+
def doit(self, **hints):
|
156 |
+
if self.is_symbolic:
|
157 |
+
raise ValueError("Coefficients must be numerical")
|
158 |
+
return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
|
159 |
+
|
160 |
+
|
161 |
+
class CG(Wigner3j):
|
162 |
+
r"""Class for Clebsch-Gordan coefficient.
|
163 |
+
|
164 |
+
Explanation
|
165 |
+
===========
|
166 |
+
|
167 |
+
Clebsch-Gordan coefficients describe the angular momentum coupling between
|
168 |
+
two systems. The coefficients give the expansion of a coupled total angular
|
169 |
+
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
|
170 |
+
coefficients are defined as [1]_:
|
171 |
+
|
172 |
+
.. math ::
|
173 |
+
C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
|
174 |
+
|
175 |
+
Parameters
|
176 |
+
==========
|
177 |
+
|
178 |
+
j1, m1, j2, m2 : Number, Symbol
|
179 |
+
Angular momenta of states 1 and 2.
|
180 |
+
|
181 |
+
j3, m3: Number, Symbol
|
182 |
+
Total angular momentum of the coupled system.
|
183 |
+
|
184 |
+
Examples
|
185 |
+
========
|
186 |
+
|
187 |
+
Define a Clebsch-Gordan coefficient and evaluate its value
|
188 |
+
|
189 |
+
>>> from sympy.physics.quantum.cg import CG
|
190 |
+
>>> from sympy import S
|
191 |
+
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
|
192 |
+
>>> cg
|
193 |
+
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
|
194 |
+
>>> cg.doit()
|
195 |
+
sqrt(3)/2
|
196 |
+
>>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
|
197 |
+
sqrt(2)/2
|
198 |
+
|
199 |
+
|
200 |
+
Compare [2]_.
|
201 |
+
|
202 |
+
See Also
|
203 |
+
========
|
204 |
+
|
205 |
+
Wigner3j: Wigner-3j symbols
|
206 |
+
|
207 |
+
References
|
208 |
+
==========
|
209 |
+
|
210 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
211 |
+
.. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
|
212 |
+
<https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
|
213 |
+
in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
|
214 |
+
2020, 083C01 (2020).
|
215 |
+
"""
|
216 |
+
precedence = PRECEDENCE["Pow"] - 1
|
217 |
+
|
218 |
+
def doit(self, **hints):
|
219 |
+
if self.is_symbolic:
|
220 |
+
raise ValueError("Coefficients must be numerical")
|
221 |
+
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
|
222 |
+
|
223 |
+
def _pretty(self, printer, *args):
|
224 |
+
bot = printer._print_seq(
|
225 |
+
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
|
226 |
+
top = printer._print_seq((self.j3, self.m3), delimiter=',')
|
227 |
+
|
228 |
+
pad = max(top.width(), bot.width())
|
229 |
+
bot = prettyForm(*bot.left(' '))
|
230 |
+
top = prettyForm(*top.left(' '))
|
231 |
+
|
232 |
+
if not pad == bot.width():
|
233 |
+
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
|
234 |
+
if not pad == top.width():
|
235 |
+
top = prettyForm(*top.right(' '*(pad - top.width())))
|
236 |
+
s = stringPict('C' + ' '*pad)
|
237 |
+
s = prettyForm(*s.below(bot))
|
238 |
+
s = prettyForm(*s.above(top))
|
239 |
+
return s
|
240 |
+
|
241 |
+
def _latex(self, printer, *args):
|
242 |
+
label = map(printer._print, (self.j3, self.m3, self.j1,
|
243 |
+
self.m1, self.j2, self.m2))
|
244 |
+
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
|
245 |
+
|
246 |
+
|
247 |
+
class Wigner6j(Expr):
|
248 |
+
"""Class for the Wigner-6j symbols
|
249 |
+
|
250 |
+
See Also
|
251 |
+
========
|
252 |
+
|
253 |
+
Wigner3j: Wigner-3j symbols
|
254 |
+
|
255 |
+
"""
|
256 |
+
def __new__(cls, j1, j2, j12, j3, j, j23):
|
257 |
+
args = map(sympify, (j1, j2, j12, j3, j, j23))
|
258 |
+
return Expr.__new__(cls, *args)
|
259 |
+
|
260 |
+
@property
|
261 |
+
def j1(self):
|
262 |
+
return self.args[0]
|
263 |
+
|
264 |
+
@property
|
265 |
+
def j2(self):
|
266 |
+
return self.args[1]
|
267 |
+
|
268 |
+
@property
|
269 |
+
def j12(self):
|
270 |
+
return self.args[2]
|
271 |
+
|
272 |
+
@property
|
273 |
+
def j3(self):
|
274 |
+
return self.args[3]
|
275 |
+
|
276 |
+
@property
|
277 |
+
def j(self):
|
278 |
+
return self.args[4]
|
279 |
+
|
280 |
+
@property
|
281 |
+
def j23(self):
|
282 |
+
return self.args[5]
|
283 |
+
|
284 |
+
@property
|
285 |
+
def is_symbolic(self):
|
286 |
+
return not all(arg.is_number for arg in self.args)
|
287 |
+
|
288 |
+
# This is modified from the _print_Matrix method
|
289 |
+
def _pretty(self, printer, *args):
|
290 |
+
m = ((printer._print(self.j1), printer._print(self.j3)),
|
291 |
+
(printer._print(self.j2), printer._print(self.j)),
|
292 |
+
(printer._print(self.j12), printer._print(self.j23)))
|
293 |
+
hsep = 2
|
294 |
+
vsep = 1
|
295 |
+
maxw = [-1]*3
|
296 |
+
for j in range(3):
|
297 |
+
maxw[j] = max([ m[j][i].width() for i in range(2) ])
|
298 |
+
D = None
|
299 |
+
for i in range(2):
|
300 |
+
D_row = None
|
301 |
+
for j in range(3):
|
302 |
+
s = m[j][i]
|
303 |
+
wdelta = maxw[j] - s.width()
|
304 |
+
wleft = wdelta //2
|
305 |
+
wright = wdelta - wleft
|
306 |
+
|
307 |
+
s = prettyForm(*s.right(' '*wright))
|
308 |
+
s = prettyForm(*s.left(' '*wleft))
|
309 |
+
|
310 |
+
if D_row is None:
|
311 |
+
D_row = s
|
312 |
+
continue
|
313 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
314 |
+
D_row = prettyForm(*D_row.right(s))
|
315 |
+
if D is None:
|
316 |
+
D = D_row
|
317 |
+
continue
|
318 |
+
for _ in range(vsep):
|
319 |
+
D = prettyForm(*D.below(' '))
|
320 |
+
D = prettyForm(*D.below(D_row))
|
321 |
+
D = prettyForm(*D.parens(left='{', right='}'))
|
322 |
+
return D
|
323 |
+
|
324 |
+
def _latex(self, printer, *args):
|
325 |
+
label = map(printer._print, (self.j1, self.j2, self.j12,
|
326 |
+
self.j3, self.j, self.j23))
|
327 |
+
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
|
328 |
+
tuple(label)
|
329 |
+
|
330 |
+
def doit(self, **hints):
|
331 |
+
if self.is_symbolic:
|
332 |
+
raise ValueError("Coefficients must be numerical")
|
333 |
+
return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
|
334 |
+
|
335 |
+
|
336 |
+
class Wigner9j(Expr):
|
337 |
+
"""Class for the Wigner-9j symbols
|
338 |
+
|
339 |
+
See Also
|
340 |
+
========
|
341 |
+
|
342 |
+
Wigner3j: Wigner-3j symbols
|
343 |
+
|
344 |
+
"""
|
345 |
+
def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
|
346 |
+
args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
|
347 |
+
return Expr.__new__(cls, *args)
|
348 |
+
|
349 |
+
@property
|
350 |
+
def j1(self):
|
351 |
+
return self.args[0]
|
352 |
+
|
353 |
+
@property
|
354 |
+
def j2(self):
|
355 |
+
return self.args[1]
|
356 |
+
|
357 |
+
@property
|
358 |
+
def j12(self):
|
359 |
+
return self.args[2]
|
360 |
+
|
361 |
+
@property
|
362 |
+
def j3(self):
|
363 |
+
return self.args[3]
|
364 |
+
|
365 |
+
@property
|
366 |
+
def j4(self):
|
367 |
+
return self.args[4]
|
368 |
+
|
369 |
+
@property
|
370 |
+
def j34(self):
|
371 |
+
return self.args[5]
|
372 |
+
|
373 |
+
@property
|
374 |
+
def j13(self):
|
375 |
+
return self.args[6]
|
376 |
+
|
377 |
+
@property
|
378 |
+
def j24(self):
|
379 |
+
return self.args[7]
|
380 |
+
|
381 |
+
@property
|
382 |
+
def j(self):
|
383 |
+
return self.args[8]
|
384 |
+
|
385 |
+
@property
|
386 |
+
def is_symbolic(self):
|
387 |
+
return not all(arg.is_number for arg in self.args)
|
388 |
+
|
389 |
+
# This is modified from the _print_Matrix method
|
390 |
+
def _pretty(self, printer, *args):
|
391 |
+
m = (
|
392 |
+
(printer._print(
|
393 |
+
self.j1), printer._print(self.j3), printer._print(self.j13)),
|
394 |
+
(printer._print(
|
395 |
+
self.j2), printer._print(self.j4), printer._print(self.j24)),
|
396 |
+
(printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
|
397 |
+
hsep = 2
|
398 |
+
vsep = 1
|
399 |
+
maxw = [-1]*3
|
400 |
+
for j in range(3):
|
401 |
+
maxw[j] = max([ m[j][i].width() for i in range(3) ])
|
402 |
+
D = None
|
403 |
+
for i in range(3):
|
404 |
+
D_row = None
|
405 |
+
for j in range(3):
|
406 |
+
s = m[j][i]
|
407 |
+
wdelta = maxw[j] - s.width()
|
408 |
+
wleft = wdelta //2
|
409 |
+
wright = wdelta - wleft
|
410 |
+
|
411 |
+
s = prettyForm(*s.right(' '*wright))
|
412 |
+
s = prettyForm(*s.left(' '*wleft))
|
413 |
+
|
414 |
+
if D_row is None:
|
415 |
+
D_row = s
|
416 |
+
continue
|
417 |
+
D_row = prettyForm(*D_row.right(' '*hsep))
|
418 |
+
D_row = prettyForm(*D_row.right(s))
|
419 |
+
if D is None:
|
420 |
+
D = D_row
|
421 |
+
continue
|
422 |
+
for _ in range(vsep):
|
423 |
+
D = prettyForm(*D.below(' '))
|
424 |
+
D = prettyForm(*D.below(D_row))
|
425 |
+
D = prettyForm(*D.parens(left='{', right='}'))
|
426 |
+
return D
|
427 |
+
|
428 |
+
def _latex(self, printer, *args):
|
429 |
+
label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
|
430 |
+
self.j4, self.j34, self.j13, self.j24, self.j))
|
431 |
+
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
|
432 |
+
tuple(label)
|
433 |
+
|
434 |
+
def doit(self, **hints):
|
435 |
+
if self.is_symbolic:
|
436 |
+
raise ValueError("Coefficients must be numerical")
|
437 |
+
return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
|
438 |
+
|
439 |
+
|
440 |
+
def cg_simp(e):
|
441 |
+
"""Simplify and combine CG coefficients.
|
442 |
+
|
443 |
+
Explanation
|
444 |
+
===========
|
445 |
+
|
446 |
+
This function uses various symmetry and properties of sums and
|
447 |
+
products of Clebsch-Gordan coefficients to simplify statements
|
448 |
+
involving these terms [1]_.
|
449 |
+
|
450 |
+
Examples
|
451 |
+
========
|
452 |
+
|
453 |
+
Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
|
454 |
+
2*a+1
|
455 |
+
|
456 |
+
>>> from sympy.physics.quantum.cg import CG, cg_simp
|
457 |
+
>>> a = CG(1,1,0,0,1,1)
|
458 |
+
>>> b = CG(1,0,0,0,1,0)
|
459 |
+
>>> c = CG(1,-1,0,0,1,-1)
|
460 |
+
>>> cg_simp(a+b+c)
|
461 |
+
3
|
462 |
+
|
463 |
+
See Also
|
464 |
+
========
|
465 |
+
|
466 |
+
CG: Clebsh-Gordan coefficients
|
467 |
+
|
468 |
+
References
|
469 |
+
==========
|
470 |
+
|
471 |
+
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
|
472 |
+
"""
|
473 |
+
if isinstance(e, Add):
|
474 |
+
return _cg_simp_add(e)
|
475 |
+
elif isinstance(e, Sum):
|
476 |
+
return _cg_simp_sum(e)
|
477 |
+
elif isinstance(e, Mul):
|
478 |
+
return Mul(*[cg_simp(arg) for arg in e.args])
|
479 |
+
elif isinstance(e, Pow):
|
480 |
+
return Pow(cg_simp(e.base), e.exp)
|
481 |
+
else:
|
482 |
+
return e
|
483 |
+
|
484 |
+
|
485 |
+
def _cg_simp_add(e):
|
486 |
+
#TODO: Improve simplification method
|
487 |
+
"""Takes a sum of terms involving Clebsch-Gordan coefficients and
|
488 |
+
simplifies the terms.
|
489 |
+
|
490 |
+
Explanation
|
491 |
+
===========
|
492 |
+
|
493 |
+
First, we create two lists, cg_part, which is all the terms involving CG
|
494 |
+
coefficients, and other_part, which is all other terms. The cg_part list
|
495 |
+
is then passed to the simplification methods, which return the new cg_part
|
496 |
+
and any additional terms that are added to other_part
|
497 |
+
"""
|
498 |
+
cg_part = []
|
499 |
+
other_part = []
|
500 |
+
|
501 |
+
e = expand(e)
|
502 |
+
for arg in e.args:
|
503 |
+
if arg.has(CG):
|
504 |
+
if isinstance(arg, Sum):
|
505 |
+
other_part.append(_cg_simp_sum(arg))
|
506 |
+
elif isinstance(arg, Mul):
|
507 |
+
terms = 1
|
508 |
+
for term in arg.args:
|
509 |
+
if isinstance(term, Sum):
|
510 |
+
terms *= _cg_simp_sum(term)
|
511 |
+
else:
|
512 |
+
terms *= term
|
513 |
+
if terms.has(CG):
|
514 |
+
cg_part.append(terms)
|
515 |
+
else:
|
516 |
+
other_part.append(terms)
|
517 |
+
else:
|
518 |
+
cg_part.append(arg)
|
519 |
+
else:
|
520 |
+
other_part.append(arg)
|
521 |
+
|
522 |
+
cg_part, other = _check_varsh_871_1(cg_part)
|
523 |
+
other_part.append(other)
|
524 |
+
cg_part, other = _check_varsh_871_2(cg_part)
|
525 |
+
other_part.append(other)
|
526 |
+
cg_part, other = _check_varsh_872_9(cg_part)
|
527 |
+
other_part.append(other)
|
528 |
+
return Add(*cg_part) + Add(*other_part)
|
529 |
+
|
530 |
+
|
531 |
+
def _check_varsh_871_1(term_list):
|
532 |
+
# Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
|
533 |
+
a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
|
534 |
+
expr = lt*CG(a, alpha, b, 0, a, alpha)
|
535 |
+
simp = (2*a + 1)*KroneckerDelta(b, 0)
|
536 |
+
sign = lt/abs(lt)
|
537 |
+
build_expr = 2*a + 1
|
538 |
+
index_expr = a + alpha
|
539 |
+
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
|
540 |
+
|
541 |
+
|
542 |
+
def _check_varsh_871_2(term_list):
|
543 |
+
# Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
|
544 |
+
a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
|
545 |
+
expr = lt*CG(a, alpha, a, -alpha, c, 0)
|
546 |
+
simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
|
547 |
+
sign = (-1)**(a - alpha)*lt/abs(lt)
|
548 |
+
build_expr = 2*a + 1
|
549 |
+
index_expr = a + alpha
|
550 |
+
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
|
551 |
+
|
552 |
+
|
553 |
+
def _check_varsh_872_9(term_list):
|
554 |
+
# Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
|
555 |
+
a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
|
556 |
+
'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
|
557 |
+
# Case alpha==alphap, beta==betap
|
558 |
+
|
559 |
+
# For numerical alpha,beta
|
560 |
+
expr = lt*CG(a, alpha, b, beta, c, gamma)**2
|
561 |
+
simp = S.One
|
562 |
+
sign = lt/abs(lt)
|
563 |
+
x = abs(a - b)
|
564 |
+
y = abs(alpha + beta)
|
565 |
+
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
|
566 |
+
index_expr = a + b - c
|
567 |
+
term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
|
568 |
+
|
569 |
+
# For symbolic alpha,beta
|
570 |
+
x = abs(a - b)
|
571 |
+
y = a + b
|
572 |
+
build_expr = (y + 1 - x)*(x + y + 1)
|
573 |
+
index_expr = (c - x)*(x + c) + c + gamma
|
574 |
+
term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
|
575 |
+
|
576 |
+
# Case alpha!=alphap or beta!=betap
|
577 |
+
# Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
|
578 |
+
# For numerical alpha,alphap,beta,betap
|
579 |
+
expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
|
580 |
+
simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
|
581 |
+
sign = S.One
|
582 |
+
x = abs(a - b)
|
583 |
+
y = abs(alpha + beta)
|
584 |
+
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
|
585 |
+
index_expr = a + b - c
|
586 |
+
term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
|
587 |
+
|
588 |
+
# For symbolic alpha,alphap,beta,betap
|
589 |
+
x = abs(a - b)
|
590 |
+
y = a + b
|
591 |
+
build_expr = (y + 1 - x)*(x + y + 1)
|
592 |
+
index_expr = (c - x)*(x + c) + c + gamma
|
593 |
+
term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
|
594 |
+
|
595 |
+
return term_list, other1 + other2 + other4
|
596 |
+
|
597 |
+
|
598 |
+
def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
|
599 |
+
""" Checks for simplifications that can be made, returning a tuple of the
|
600 |
+
simplified list of terms and any terms generated by simplification.
|
601 |
+
|
602 |
+
Parameters
|
603 |
+
==========
|
604 |
+
|
605 |
+
expr: expression
|
606 |
+
The expression with Wild terms that will be matched to the terms in
|
607 |
+
the sum
|
608 |
+
|
609 |
+
simp: expression
|
610 |
+
The expression with Wild terms that is substituted in place of the CG
|
611 |
+
terms in the case of simplification
|
612 |
+
|
613 |
+
sign: expression
|
614 |
+
The expression with Wild terms denoting the sign that is on expr that
|
615 |
+
must match
|
616 |
+
|
617 |
+
lt: expression
|
618 |
+
The expression with Wild terms that gives the leading term of the
|
619 |
+
matched expr
|
620 |
+
|
621 |
+
term_list: list
|
622 |
+
A list of all of the terms is the sum to be simplified
|
623 |
+
|
624 |
+
variables: list
|
625 |
+
A list of all the variables that appears in expr
|
626 |
+
|
627 |
+
dep_variables: list
|
628 |
+
A list of the variables that must match for all the terms in the sum,
|
629 |
+
i.e. the dependent variables
|
630 |
+
|
631 |
+
build_index_expr: expression
|
632 |
+
Expression with Wild terms giving the number of elements in cg_index
|
633 |
+
|
634 |
+
index_expr: expression
|
635 |
+
Expression with Wild terms giving the index terms have when storing
|
636 |
+
them to cg_index
|
637 |
+
|
638 |
+
"""
|
639 |
+
other_part = 0
|
640 |
+
i = 0
|
641 |
+
while i < len(term_list):
|
642 |
+
sub_1 = _check_cg(term_list[i], expr, len(variables))
|
643 |
+
if sub_1 is None:
|
644 |
+
i += 1
|
645 |
+
continue
|
646 |
+
if not build_index_expr.subs(sub_1).is_number:
|
647 |
+
i += 1
|
648 |
+
continue
|
649 |
+
sub_dep = [(x, sub_1[x]) for x in dep_variables]
|
650 |
+
cg_index = [None]*build_index_expr.subs(sub_1)
|
651 |
+
for j in range(i, len(term_list)):
|
652 |
+
sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
|
653 |
+
if sub_2 is None:
|
654 |
+
continue
|
655 |
+
if not index_expr.subs(sub_dep).subs(sub_2).is_number:
|
656 |
+
continue
|
657 |
+
cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
|
658 |
+
if not any(i is None for i in cg_index):
|
659 |
+
min_lt = min(*[ abs(term[2]) for term in cg_index ])
|
660 |
+
indices = [ term[0] for term in cg_index]
|
661 |
+
indices.sort()
|
662 |
+
indices.reverse()
|
663 |
+
[ term_list.pop(j) for j in indices ]
|
664 |
+
for term in cg_index:
|
665 |
+
if abs(term[2]) > min_lt:
|
666 |
+
term_list.append( (term[2] - min_lt*term[3])*term[1] )
|
667 |
+
other_part += min_lt*(sign*simp).subs(sub_1)
|
668 |
+
else:
|
669 |
+
i += 1
|
670 |
+
return term_list, other_part
|
671 |
+
|
672 |
+
|
673 |
+
def _check_cg(cg_term, expr, length, sign=None):
|
674 |
+
"""Checks whether a term matches the given expression"""
|
675 |
+
# TODO: Check for symmetries
|
676 |
+
matches = cg_term.match(expr)
|
677 |
+
if matches is None:
|
678 |
+
return
|
679 |
+
if sign is not None:
|
680 |
+
if not isinstance(sign, tuple):
|
681 |
+
raise TypeError('sign must be a tuple')
|
682 |
+
if not sign[0] == (sign[1]).subs(matches):
|
683 |
+
return
|
684 |
+
if len(matches) == length:
|
685 |
+
return matches
|
686 |
+
|
687 |
+
|
688 |
+
def _cg_simp_sum(e):
|
689 |
+
e = _check_varsh_sum_871_1(e)
|
690 |
+
e = _check_varsh_sum_871_2(e)
|
691 |
+
e = _check_varsh_sum_872_4(e)
|
692 |
+
return e
|
693 |
+
|
694 |
+
|
695 |
+
def _check_varsh_sum_871_1(e):
|
696 |
+
a = Wild('a')
|
697 |
+
alpha = symbols('alpha')
|
698 |
+
b = Wild('b')
|
699 |
+
match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
|
700 |
+
if match is not None and len(match) == 2:
|
701 |
+
return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
|
702 |
+
return e
|
703 |
+
|
704 |
+
|
705 |
+
def _check_varsh_sum_871_2(e):
|
706 |
+
a = Wild('a')
|
707 |
+
alpha = symbols('alpha')
|
708 |
+
c = Wild('c')
|
709 |
+
match = e.match(
|
710 |
+
Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
|
711 |
+
if match is not None and len(match) == 2:
|
712 |
+
return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
|
713 |
+
return e
|
714 |
+
|
715 |
+
|
716 |
+
def _check_varsh_sum_872_4(e):
|
717 |
+
alpha = symbols('alpha')
|
718 |
+
beta = symbols('beta')
|
719 |
+
a = Wild('a')
|
720 |
+
b = Wild('b')
|
721 |
+
c = Wild('c')
|
722 |
+
cp = Wild('cp')
|
723 |
+
gamma = Wild('gamma')
|
724 |
+
gammap = Wild('gammap')
|
725 |
+
cg1 = CG(a, alpha, b, beta, c, gamma)
|
726 |
+
cg2 = CG(a, alpha, b, beta, cp, gammap)
|
727 |
+
match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
|
728 |
+
if match1 is not None and len(match1) == 6:
|
729 |
+
return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
|
730 |
+
match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
|
731 |
+
if match2 is not None and len(match2) == 4:
|
732 |
+
return S.One
|
733 |
+
return e
|
734 |
+
|
735 |
+
|
736 |
+
def _cg_list(term):
|
737 |
+
if isinstance(term, CG):
|
738 |
+
return (term,), 1, 1
|
739 |
+
cg = []
|
740 |
+
coeff = 1
|
741 |
+
if not isinstance(term, (Mul, Pow)):
|
742 |
+
raise NotImplementedError('term must be CG, Add, Mul or Pow')
|
743 |
+
if isinstance(term, Pow) and term.exp.is_number:
|
744 |
+
if term.exp.is_number:
|
745 |
+
[ cg.append(term.base) for _ in range(term.exp) ]
|
746 |
+
else:
|
747 |
+
return (term,), 1, 1
|
748 |
+
if isinstance(term, Mul):
|
749 |
+
for arg in term.args:
|
750 |
+
if isinstance(arg, CG):
|
751 |
+
cg.append(arg)
|
752 |
+
else:
|
753 |
+
coeff *= arg
|
754 |
+
return cg, coeff, coeff/abs(coeff)
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/circuitutils.py
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Primitive circuit operations on quantum circuits."""
|
2 |
+
|
3 |
+
from functools import reduce
|
4 |
+
|
5 |
+
from sympy.core.sorting import default_sort_key
|
6 |
+
from sympy.core.containers import Tuple
|
7 |
+
from sympy.core.mul import Mul
|
8 |
+
from sympy.core.symbol import Symbol
|
9 |
+
from sympy.core.sympify import sympify
|
10 |
+
from sympy.utilities import numbered_symbols
|
11 |
+
from sympy.physics.quantum.gate import Gate
|
12 |
+
|
13 |
+
__all__ = [
|
14 |
+
'kmp_table',
|
15 |
+
'find_subcircuit',
|
16 |
+
'replace_subcircuit',
|
17 |
+
'convert_to_symbolic_indices',
|
18 |
+
'convert_to_real_indices',
|
19 |
+
'random_reduce',
|
20 |
+
'random_insert'
|
21 |
+
]
|
22 |
+
|
23 |
+
|
24 |
+
def kmp_table(word):
|
25 |
+
"""Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
|
26 |
+
|
27 |
+
Note: This is applicable to strings or
|
28 |
+
quantum circuits represented as tuples.
|
29 |
+
"""
|
30 |
+
|
31 |
+
# Current position in subcircuit
|
32 |
+
pos = 2
|
33 |
+
# Beginning position of candidate substring that
|
34 |
+
# may reappear later in word
|
35 |
+
cnd = 0
|
36 |
+
# The 'partial match' table that helps one determine
|
37 |
+
# the next location to start substring search
|
38 |
+
table = []
|
39 |
+
table.append(-1)
|
40 |
+
table.append(0)
|
41 |
+
|
42 |
+
while pos < len(word):
|
43 |
+
if word[pos - 1] == word[cnd]:
|
44 |
+
cnd = cnd + 1
|
45 |
+
table.append(cnd)
|
46 |
+
pos = pos + 1
|
47 |
+
elif cnd > 0:
|
48 |
+
cnd = table[cnd]
|
49 |
+
else:
|
50 |
+
table.append(0)
|
51 |
+
pos = pos + 1
|
52 |
+
|
53 |
+
return table
|
54 |
+
|
55 |
+
|
56 |
+
def find_subcircuit(circuit, subcircuit, start=0, end=0):
|
57 |
+
"""Finds the subcircuit in circuit, if it exists.
|
58 |
+
|
59 |
+
Explanation
|
60 |
+
===========
|
61 |
+
|
62 |
+
If the subcircuit exists, the index of the start of
|
63 |
+
the subcircuit in circuit is returned; otherwise,
|
64 |
+
-1 is returned. The algorithm that is implemented
|
65 |
+
is the Knuth-Morris-Pratt algorithm.
|
66 |
+
|
67 |
+
Parameters
|
68 |
+
==========
|
69 |
+
|
70 |
+
circuit : tuple, Gate or Mul
|
71 |
+
A tuple of Gates or Mul representing a quantum circuit
|
72 |
+
subcircuit : tuple, Gate or Mul
|
73 |
+
A tuple of Gates or Mul to find in circuit
|
74 |
+
start : int
|
75 |
+
The location to start looking for subcircuit.
|
76 |
+
If start is the same or past end, -1 is returned.
|
77 |
+
end : int
|
78 |
+
The last place to look for a subcircuit. If end
|
79 |
+
is less than 1 (one), then the length of circuit
|
80 |
+
is taken to be end.
|
81 |
+
|
82 |
+
Examples
|
83 |
+
========
|
84 |
+
|
85 |
+
Find the first instance of a subcircuit:
|
86 |
+
|
87 |
+
>>> from sympy.physics.quantum.circuitutils import find_subcircuit
|
88 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z, H
|
89 |
+
>>> circuit = X(0)*Z(0)*Y(0)*H(0)
|
90 |
+
>>> subcircuit = Z(0)*Y(0)
|
91 |
+
>>> find_subcircuit(circuit, subcircuit)
|
92 |
+
1
|
93 |
+
|
94 |
+
Find the first instance starting at a specific position:
|
95 |
+
|
96 |
+
>>> find_subcircuit(circuit, subcircuit, start=1)
|
97 |
+
1
|
98 |
+
|
99 |
+
>>> find_subcircuit(circuit, subcircuit, start=2)
|
100 |
+
-1
|
101 |
+
|
102 |
+
>>> circuit = circuit*subcircuit
|
103 |
+
>>> find_subcircuit(circuit, subcircuit, start=2)
|
104 |
+
4
|
105 |
+
|
106 |
+
Find the subcircuit within some interval:
|
107 |
+
|
108 |
+
>>> find_subcircuit(circuit, subcircuit, start=2, end=2)
|
109 |
+
-1
|
110 |
+
"""
|
111 |
+
|
112 |
+
if isinstance(circuit, Mul):
|
113 |
+
circuit = circuit.args
|
114 |
+
|
115 |
+
if isinstance(subcircuit, Mul):
|
116 |
+
subcircuit = subcircuit.args
|
117 |
+
|
118 |
+
if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
|
119 |
+
return -1
|
120 |
+
|
121 |
+
if end < 1:
|
122 |
+
end = len(circuit)
|
123 |
+
|
124 |
+
# Location in circuit
|
125 |
+
pos = start
|
126 |
+
# Location in the subcircuit
|
127 |
+
index = 0
|
128 |
+
# 'Partial match' table
|
129 |
+
table = kmp_table(subcircuit)
|
130 |
+
|
131 |
+
while (pos + index) < end:
|
132 |
+
if subcircuit[index] == circuit[pos + index]:
|
133 |
+
index = index + 1
|
134 |
+
else:
|
135 |
+
pos = pos + index - table[index]
|
136 |
+
index = table[index] if table[index] > -1 else 0
|
137 |
+
|
138 |
+
if index == len(subcircuit):
|
139 |
+
return pos
|
140 |
+
|
141 |
+
return -1
|
142 |
+
|
143 |
+
|
144 |
+
def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
|
145 |
+
"""Replaces a subcircuit with another subcircuit in circuit,
|
146 |
+
if it exists.
|
147 |
+
|
148 |
+
Explanation
|
149 |
+
===========
|
150 |
+
|
151 |
+
If multiple instances of subcircuit exists, the first instance is
|
152 |
+
replaced. The position to being searching from (if different from
|
153 |
+
0) may be optionally given. If subcircuit cannot be found, circuit
|
154 |
+
is returned.
|
155 |
+
|
156 |
+
Parameters
|
157 |
+
==========
|
158 |
+
|
159 |
+
circuit : tuple, Gate or Mul
|
160 |
+
A quantum circuit.
|
161 |
+
subcircuit : tuple, Gate or Mul
|
162 |
+
The circuit to be replaced.
|
163 |
+
replace : tuple, Gate or Mul
|
164 |
+
The replacement circuit.
|
165 |
+
pos : int
|
166 |
+
The location to start search and replace
|
167 |
+
subcircuit, if it exists. This may be used
|
168 |
+
if it is known beforehand that multiple
|
169 |
+
instances exist, and it is desirable to
|
170 |
+
replace a specific instance. If a negative number
|
171 |
+
is given, pos will be defaulted to 0.
|
172 |
+
|
173 |
+
Examples
|
174 |
+
========
|
175 |
+
|
176 |
+
Find and remove the subcircuit:
|
177 |
+
|
178 |
+
>>> from sympy.physics.quantum.circuitutils import replace_subcircuit
|
179 |
+
>>> from sympy.physics.quantum.gate import X, Y, Z, H
|
180 |
+
>>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
|
181 |
+
>>> subcircuit = Z(0)*Y(0)
|
182 |
+
>>> replace_subcircuit(circuit, subcircuit)
|
183 |
+
(X(0), H(0), X(0), H(0), Y(0))
|
184 |
+
|
185 |
+
Remove the subcircuit given a starting search point:
|
186 |
+
|
187 |
+
>>> replace_subcircuit(circuit, subcircuit, pos=1)
|
188 |
+
(X(0), H(0), X(0), H(0), Y(0))
|
189 |
+
|
190 |
+
>>> replace_subcircuit(circuit, subcircuit, pos=2)
|
191 |
+
(X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
|
192 |
+
|
193 |
+
Replace the subcircuit:
|
194 |
+
|
195 |
+
>>> replacement = H(0)*Z(0)
|
196 |
+
>>> replace_subcircuit(circuit, subcircuit, replace=replacement)
|
197 |
+
(X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
|
198 |
+
"""
|
199 |
+
|
200 |
+
if pos < 0:
|
201 |
+
pos = 0
|
202 |
+
|
203 |
+
if isinstance(circuit, Mul):
|
204 |
+
circuit = circuit.args
|
205 |
+
|
206 |
+
if isinstance(subcircuit, Mul):
|
207 |
+
subcircuit = subcircuit.args
|
208 |
+
|
209 |
+
if isinstance(replace, Mul):
|
210 |
+
replace = replace.args
|
211 |
+
elif replace is None:
|
212 |
+
replace = ()
|
213 |
+
|
214 |
+
# Look for the subcircuit starting at pos
|
215 |
+
loc = find_subcircuit(circuit, subcircuit, start=pos)
|
216 |
+
|
217 |
+
# If subcircuit was found
|
218 |
+
if loc > -1:
|
219 |
+
# Get the gates to the left of subcircuit
|
220 |
+
left = circuit[0:loc]
|
221 |
+
# Get the gates to the right of subcircuit
|
222 |
+
right = circuit[loc + len(subcircuit):len(circuit)]
|
223 |
+
# Recombine the left and right side gates into a circuit
|
224 |
+
circuit = left + replace + right
|
225 |
+
|
226 |
+
return circuit
|
227 |
+
|
228 |
+
|
229 |
+
def _sympify_qubit_map(mapping):
|
230 |
+
new_map = {}
|
231 |
+
for key in mapping:
|
232 |
+
new_map[key] = sympify(mapping[key])
|
233 |
+
return new_map
|
234 |
+
|
235 |
+
|
236 |
+
def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
|
237 |
+
"""Returns the circuit with symbolic indices and the
|
238 |
+
dictionary mapping symbolic indices to real indices.
|
239 |
+
|
240 |
+
The mapping is 1 to 1 and onto (bijective).
|
241 |
+
|
242 |
+
Parameters
|
243 |
+
==========
|
244 |
+
|
245 |
+
seq : tuple, Gate/Integer/tuple or Mul
|
246 |
+
A tuple of Gate, Integer, or tuple objects, or a Mul
|
247 |
+
start : Symbol
|
248 |
+
An optional starting symbolic index
|
249 |
+
gen : object
|
250 |
+
An optional numbered symbol generator
|
251 |
+
qubit_map : dict
|
252 |
+
An existing mapping of symbolic indices to real indices
|
253 |
+
|
254 |
+
All symbolic indices have the format 'i#', where # is
|
255 |
+
some number >= 0.
|
256 |
+
"""
|
257 |
+
|
258 |
+
if isinstance(seq, Mul):
|
259 |
+
seq = seq.args
|
260 |
+
|
261 |
+
# A numbered symbol generator
|
262 |
+
index_gen = numbered_symbols(prefix='i', start=-1)
|
263 |
+
cur_ndx = next(index_gen)
|
264 |
+
|
265 |
+
# keys are symbolic indices; values are real indices
|
266 |
+
ndx_map = {}
|
267 |
+
|
268 |
+
def create_inverse_map(symb_to_real_map):
|
269 |
+
rev_items = lambda item: (item[1], item[0])
|
270 |
+
return dict(map(rev_items, symb_to_real_map.items()))
|
271 |
+
|
272 |
+
if start is not None:
|
273 |
+
if not isinstance(start, Symbol):
|
274 |
+
msg = 'Expected Symbol for starting index, got %r.' % start
|
275 |
+
raise TypeError(msg)
|
276 |
+
cur_ndx = start
|
277 |
+
|
278 |
+
if gen is not None:
|
279 |
+
if not isinstance(gen, numbered_symbols().__class__):
|
280 |
+
msg = 'Expected a generator, got %r.' % gen
|
281 |
+
raise TypeError(msg)
|
282 |
+
index_gen = gen
|
283 |
+
|
284 |
+
if qubit_map is not None:
|
285 |
+
if not isinstance(qubit_map, dict):
|
286 |
+
msg = ('Expected dict for existing map, got ' +
|
287 |
+
'%r.' % qubit_map)
|
288 |
+
raise TypeError(msg)
|
289 |
+
ndx_map = qubit_map
|
290 |
+
|
291 |
+
ndx_map = _sympify_qubit_map(ndx_map)
|
292 |
+
# keys are real indices; keys are symbolic indices
|
293 |
+
inv_map = create_inverse_map(ndx_map)
|
294 |
+
|
295 |
+
sym_seq = ()
|
296 |
+
for item in seq:
|
297 |
+
# Nested items, so recurse
|
298 |
+
if isinstance(item, Gate):
|
299 |
+
result = convert_to_symbolic_indices(item.args,
|
300 |
+
qubit_map=ndx_map,
|
301 |
+
start=cur_ndx,
|
302 |
+
gen=index_gen)
|
303 |
+
sym_item, new_map, cur_ndx, index_gen = result
|
304 |
+
ndx_map.update(new_map)
|
305 |
+
inv_map = create_inverse_map(ndx_map)
|
306 |
+
|
307 |
+
elif isinstance(item, (tuple, Tuple)):
|
308 |
+
result = convert_to_symbolic_indices(item,
|
309 |
+
qubit_map=ndx_map,
|
310 |
+
start=cur_ndx,
|
311 |
+
gen=index_gen)
|
312 |
+
sym_item, new_map, cur_ndx, index_gen = result
|
313 |
+
ndx_map.update(new_map)
|
314 |
+
inv_map = create_inverse_map(ndx_map)
|
315 |
+
|
316 |
+
elif item in inv_map:
|
317 |
+
sym_item = inv_map[item]
|
318 |
+
|
319 |
+
else:
|
320 |
+
cur_ndx = next(gen)
|
321 |
+
ndx_map[cur_ndx] = item
|
322 |
+
inv_map[item] = cur_ndx
|
323 |
+
sym_item = cur_ndx
|
324 |
+
|
325 |
+
if isinstance(item, Gate):
|
326 |
+
sym_item = item.__class__(*sym_item)
|
327 |
+
|
328 |
+
sym_seq = sym_seq + (sym_item,)
|
329 |
+
|
330 |
+
return sym_seq, ndx_map, cur_ndx, index_gen
|
331 |
+
|
332 |
+
|
333 |
+
def convert_to_real_indices(seq, qubit_map):
|
334 |
+
"""Returns the circuit with real indices.
|
335 |
+
|
336 |
+
Parameters
|
337 |
+
==========
|
338 |
+
|
339 |
+
seq : tuple, Gate/Integer/tuple or Mul
|
340 |
+
A tuple of Gate, Integer, or tuple objects or a Mul
|
341 |
+
qubit_map : dict
|
342 |
+
A dictionary mapping symbolic indices to real indices.
|
343 |
+
|
344 |
+
Examples
|
345 |
+
========
|
346 |
+
|
347 |
+
Change the symbolic indices to real integers:
|
348 |
+
|
349 |
+
>>> from sympy import symbols
|
350 |
+
>>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
|
351 |
+
>>> from sympy.physics.quantum.gate import X, Y, H
|
352 |
+
>>> i0, i1 = symbols('i:2')
|
353 |
+
>>> index_map = {i0 : 0, i1 : 1}
|
354 |
+
>>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
|
355 |
+
(X(0), Y(1), H(0), X(1))
|
356 |
+
"""
|
357 |
+
|
358 |
+
if isinstance(seq, Mul):
|
359 |
+
seq = seq.args
|
360 |
+
|
361 |
+
if not isinstance(qubit_map, dict):
|
362 |
+
msg = 'Expected dict for qubit_map, got %r.' % qubit_map
|
363 |
+
raise TypeError(msg)
|
364 |
+
|
365 |
+
qubit_map = _sympify_qubit_map(qubit_map)
|
366 |
+
real_seq = ()
|
367 |
+
for item in seq:
|
368 |
+
# Nested items, so recurse
|
369 |
+
if isinstance(item, Gate):
|
370 |
+
real_item = convert_to_real_indices(item.args, qubit_map)
|
371 |
+
|
372 |
+
elif isinstance(item, (tuple, Tuple)):
|
373 |
+
real_item = convert_to_real_indices(item, qubit_map)
|
374 |
+
|
375 |
+
else:
|
376 |
+
real_item = qubit_map[item]
|
377 |
+
|
378 |
+
if isinstance(item, Gate):
|
379 |
+
real_item = item.__class__(*real_item)
|
380 |
+
|
381 |
+
real_seq = real_seq + (real_item,)
|
382 |
+
|
383 |
+
return real_seq
|
384 |
+
|
385 |
+
|
386 |
+
def random_reduce(circuit, gate_ids, seed=None):
|
387 |
+
"""Shorten the length of a quantum circuit.
|
388 |
+
|
389 |
+
Explanation
|
390 |
+
===========
|
391 |
+
|
392 |
+
random_reduce looks for circuit identities in circuit, randomly chooses
|
393 |
+
one to remove, and returns a shorter yet equivalent circuit. If no
|
394 |
+
identities are found, the same circuit is returned.
|
395 |
+
|
396 |
+
Parameters
|
397 |
+
==========
|
398 |
+
|
399 |
+
circuit : Gate tuple of Mul
|
400 |
+
A tuple of Gates representing a quantum circuit
|
401 |
+
gate_ids : list, GateIdentity
|
402 |
+
List of gate identities to find in circuit
|
403 |
+
seed : int or list
|
404 |
+
seed used for _randrange; to override the random selection, provide a
|
405 |
+
list of integers: the elements of gate_ids will be tested in the order
|
406 |
+
given by the list
|
407 |
+
|
408 |
+
"""
|
409 |
+
from sympy.core.random import _randrange
|
410 |
+
|
411 |
+
if not gate_ids:
|
412 |
+
return circuit
|
413 |
+
|
414 |
+
if isinstance(circuit, Mul):
|
415 |
+
circuit = circuit.args
|
416 |
+
|
417 |
+
ids = flatten_ids(gate_ids)
|
418 |
+
|
419 |
+
# Create the random integer generator with the seed
|
420 |
+
randrange = _randrange(seed)
|
421 |
+
|
422 |
+
# Look for an identity in the circuit
|
423 |
+
while ids:
|
424 |
+
i = randrange(len(ids))
|
425 |
+
id = ids.pop(i)
|
426 |
+
if find_subcircuit(circuit, id) != -1:
|
427 |
+
break
|
428 |
+
else:
|
429 |
+
# no identity was found
|
430 |
+
return circuit
|
431 |
+
|
432 |
+
# return circuit with the identity removed
|
433 |
+
return replace_subcircuit(circuit, id)
|
434 |
+
|
435 |
+
|
436 |
+
def random_insert(circuit, choices, seed=None):
|
437 |
+
"""Insert a circuit into another quantum circuit.
|
438 |
+
|
439 |
+
Explanation
|
440 |
+
===========
|
441 |
+
|
442 |
+
random_insert randomly chooses a location in the circuit to insert
|
443 |
+
a randomly selected circuit from amongst the given choices.
|
444 |
+
|
445 |
+
Parameters
|
446 |
+
==========
|
447 |
+
|
448 |
+
circuit : Gate tuple or Mul
|
449 |
+
A tuple or Mul of Gates representing a quantum circuit
|
450 |
+
choices : list
|
451 |
+
Set of circuit choices
|
452 |
+
seed : int or list
|
453 |
+
seed used for _randrange; to override the random selections, give
|
454 |
+
a list two integers, [i, j] where i is the circuit location where
|
455 |
+
choice[j] will be inserted.
|
456 |
+
|
457 |
+
Notes
|
458 |
+
=====
|
459 |
+
|
460 |
+
Indices for insertion should be [0, n] if n is the length of the
|
461 |
+
circuit.
|
462 |
+
"""
|
463 |
+
from sympy.core.random import _randrange
|
464 |
+
|
465 |
+
if not choices:
|
466 |
+
return circuit
|
467 |
+
|
468 |
+
if isinstance(circuit, Mul):
|
469 |
+
circuit = circuit.args
|
470 |
+
|
471 |
+
# get the location in the circuit and the element to insert from choices
|
472 |
+
randrange = _randrange(seed)
|
473 |
+
loc = randrange(len(circuit) + 1)
|
474 |
+
choice = choices[randrange(len(choices))]
|
475 |
+
|
476 |
+
circuit = list(circuit)
|
477 |
+
circuit[loc: loc] = choice
|
478 |
+
return tuple(circuit)
|
479 |
+
|
480 |
+
# Flatten the GateIdentity objects (with gate rules) into one single list
|
481 |
+
|
482 |
+
|
483 |
+
def flatten_ids(ids):
|
484 |
+
collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
|
485 |
+
key=default_sort_key)
|
486 |
+
ids = reduce(collapse, ids, [])
|
487 |
+
ids.sort(key=default_sort_key)
|
488 |
+
return ids
|
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/commutator.py
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""The commutator: [A,B] = A*B - B*A."""
|
2 |
+
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.expr import Expr
|
5 |
+
from sympy.core.mul import Mul
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
9 |
+
|
10 |
+
from sympy.physics.quantum.dagger import Dagger
|
11 |
+
from sympy.physics.quantum.operator import Operator
|
12 |
+
|
13 |
+
|
14 |
+
__all__ = [
|
15 |
+
'Commutator'
|
16 |
+
]
|
17 |
+
|
18 |
+
#-----------------------------------------------------------------------------
|
19 |
+
# Commutator
|
20 |
+
#-----------------------------------------------------------------------------
|
21 |
+
|
22 |
+
|
23 |
+
class Commutator(Expr):
|
24 |
+
"""The standard commutator, in an unevaluated state.
|
25 |
+
|
26 |
+
Explanation
|
27 |
+
===========
|
28 |
+
|
29 |
+
Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This
|
30 |
+
class returns the commutator in an unevaluated form. To evaluate the
|
31 |
+
commutator, use the ``.doit()`` method.
|
32 |
+
|
33 |
+
Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The
|
34 |
+
arguments of the commutator are put into canonical order using ``__cmp__``.
|
35 |
+
If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``.
|
36 |
+
|
37 |
+
Parameters
|
38 |
+
==========
|
39 |
+
|
40 |
+
A : Expr
|
41 |
+
The first argument of the commutator [A,B].
|
42 |
+
B : Expr
|
43 |
+
The second argument of the commutator [A,B].
|
44 |
+
|
45 |
+
Examples
|
46 |
+
========
|
47 |
+
|
48 |
+
>>> from sympy.physics.quantum import Commutator, Dagger, Operator
|
49 |
+
>>> from sympy.abc import x, y
|
50 |
+
>>> A = Operator('A')
|
51 |
+
>>> B = Operator('B')
|
52 |
+
>>> C = Operator('C')
|
53 |
+
|
54 |
+
Create a commutator and use ``.doit()`` to evaluate it:
|
55 |
+
|
56 |
+
>>> comm = Commutator(A, B)
|
57 |
+
>>> comm
|
58 |
+
[A,B]
|
59 |
+
>>> comm.doit()
|
60 |
+
A*B - B*A
|
61 |
+
|
62 |
+
The commutator orders it arguments in canonical order:
|
63 |
+
|
64 |
+
>>> comm = Commutator(B, A); comm
|
65 |
+
-[A,B]
|
66 |
+
|
67 |
+
Commutative constants are factored out:
|
68 |
+
|
69 |
+
>>> Commutator(3*x*A, x*y*B)
|
70 |
+
3*x**2*y*[A,B]
|
71 |
+
|
72 |
+
Using ``.expand(commutator=True)``, the standard commutator expansion rules
|
73 |
+
can be applied:
|
74 |
+
|
75 |
+
>>> Commutator(A+B, C).expand(commutator=True)
|
76 |
+
[A,C] + [B,C]
|
77 |
+
>>> Commutator(A, B+C).expand(commutator=True)
|
78 |
+
[A,B] + [A,C]
|
79 |
+
>>> Commutator(A*B, C).expand(commutator=True)
|
80 |
+
[A,C]*B + A*[B,C]
|
81 |
+
>>> Commutator(A, B*C).expand(commutator=True)
|
82 |
+
[A,B]*C + B*[A,C]
|
83 |
+
|
84 |
+
Adjoint operations applied to the commutator are properly applied to the
|
85 |
+
arguments:
|
86 |
+
|
87 |
+
>>> Dagger(Commutator(A, B))
|
88 |
+
-[Dagger(A),Dagger(B)]
|
89 |
+
|
90 |
+
References
|
91 |
+
==========
|
92 |
+
|
93 |
+
.. [1] https://en.wikipedia.org/wiki/Commutator
|
94 |
+
"""
|
95 |
+
is_commutative = False
|
96 |
+
|
97 |
+
def __new__(cls, A, B):
|
98 |
+
r = cls.eval(A, B)
|
99 |
+
if r is not None:
|
100 |
+
return r
|
101 |
+
obj = Expr.__new__(cls, A, B)
|
102 |
+
return obj
|
103 |
+
|
104 |
+
@classmethod
|
105 |
+
def eval(cls, a, b):
|
106 |
+
if not (a and b):
|
107 |
+
return S.Zero
|
108 |
+
if a == b:
|
109 |
+
return S.Zero
|
110 |
+
if a.is_commutative or b.is_commutative:
|
111 |
+
return S.Zero
|
112 |
+
|
113 |
+
# [xA,yB] -> xy*[A,B]
|
114 |
+
ca, nca = a.args_cnc()
|
115 |
+
cb, ncb = b.args_cnc()
|
116 |
+
c_part = ca + cb
|
117 |
+
if c_part:
|
118 |
+
return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb)))
|
119 |
+
|
120 |
+
# Canonical ordering of arguments
|
121 |
+
# The Commutator [A, B] is in canonical form if A < B.
|
122 |
+
if a.compare(b) == 1:
|
123 |
+
return S.NegativeOne*cls(b, a)
|
124 |
+
|
125 |
+
def _expand_pow(self, A, B, sign):
|
126 |
+
exp = A.exp
|
127 |
+
if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1:
|
128 |
+
# nothing to do
|
129 |
+
return self
|
130 |
+
base = A.base
|
131 |
+
if exp.is_negative:
|
132 |
+
base = A.base**-1
|
133 |
+
exp = -exp
|
134 |
+
comm = Commutator(base, B).expand(commutator=True)
|
135 |
+
|
136 |
+
result = base**(exp - 1) * comm
|
137 |
+
for i in range(1, exp):
|
138 |
+
result += base**(exp - 1 - i) * comm * base**i
|
139 |
+
return sign*result.expand()
|
140 |
+
|
141 |
+
def _eval_expand_commutator(self, **hints):
|
142 |
+
A = self.args[0]
|
143 |
+
B = self.args[1]
|
144 |
+
|
145 |
+
if isinstance(A, Add):
|
146 |
+
# [A + B, C] -> [A, C] + [B, C]
|
147 |
+
sargs = []
|
148 |
+
for term in A.args:
|
149 |
+
comm = Commutator(term, B)
|
150 |
+
if isinstance(comm, Commutator):
|
151 |
+
comm = comm._eval_expand_commutator()
|
152 |
+
sargs.append(comm)
|
153 |
+
return Add(*sargs)
|
154 |
+
elif isinstance(B, Add):
|
155 |
+
# [A, B + C] -> [A, B] + [A, C]
|
156 |
+
sargs = []
|
157 |
+
for term in B.args:
|
158 |
+
comm = Commutator(A, term)
|
159 |
+
if isinstance(comm, Commutator):
|
160 |
+
comm = comm._eval_expand_commutator()
|
161 |
+
sargs.append(comm)
|
162 |
+
return Add(*sargs)
|
163 |
+
elif isinstance(A, Mul):
|
164 |
+
# [A*B, C] -> A*[B, C] + [A, C]*B
|
165 |
+
a = A.args[0]
|
166 |
+
b = Mul(*A.args[1:])
|
167 |
+
c = B
|
168 |
+
comm1 = Commutator(b, c)
|
169 |
+
comm2 = Commutator(a, c)
|
170 |
+
if isinstance(comm1, Commutator):
|
171 |
+
comm1 = comm1._eval_expand_commutator()
|
172 |
+
if isinstance(comm2, Commutator):
|
173 |
+
comm2 = comm2._eval_expand_commutator()
|
174 |
+
first = Mul(a, comm1)
|
175 |
+
second = Mul(comm2, b)
|
176 |
+
return Add(first, second)
|
177 |
+
elif isinstance(B, Mul):
|
178 |
+
# [A, B*C] -> [A, B]*C + B*[A, C]
|
179 |
+
a = A
|
180 |
+
b = B.args[0]
|
181 |
+
c = Mul(*B.args[1:])
|
182 |
+
comm1 = Commutator(a, b)
|
183 |
+
comm2 = Commutator(a, c)
|
184 |
+
if isinstance(comm1, Commutator):
|
185 |
+
comm1 = comm1._eval_expand_commutator()
|
186 |
+
if isinstance(comm2, Commutator):
|
187 |
+
comm2 = comm2._eval_expand_commutator()
|
188 |
+
first = Mul(comm1, c)
|
189 |
+
second = Mul(b, comm2)
|
190 |
+
return Add(first, second)
|
191 |
+
elif isinstance(A, Pow):
|
192 |
+
# [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1)
|
193 |
+
return self._expand_pow(A, B, 1)
|
194 |
+
elif isinstance(B, Pow):
|
195 |
+
# [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1)
|
196 |
+
return self._expand_pow(B, A, -1)
|
197 |
+
|
198 |
+
# No changes, so return self
|
199 |
+
return self
|
200 |
+
|
201 |
+
def doit(self, **hints):
|
202 |
+
""" Evaluate commutator """
|
203 |
+
A = self.args[0]
|
204 |
+
B = self.args[1]
|
205 |
+
if isinstance(A, Operator) and isinstance(B, Operator):
|
206 |
+
try:
|
207 |
+
comm = A._eval_commutator(B, **hints)
|
208 |
+
except NotImplementedError:
|
209 |
+
try:
|
210 |
+
comm = -1*B._eval_commutator(A, **hints)
|
211 |
+
except NotImplementedError:
|
212 |
+
comm = None
|
213 |
+
if comm is not None:
|
214 |
+
return comm.doit(**hints)
|
215 |
+
return (A*B - B*A).doit(**hints)
|
216 |
+
|
217 |
+
def _eval_adjoint(self):
|
218 |
+
return Commutator(Dagger(self.args[1]), Dagger(self.args[0]))
|
219 |
+
|
220 |
+
def _sympyrepr(self, printer, *args):
|
221 |
+
return "%s(%s,%s)" % (
|
222 |
+
self.__class__.__name__, printer._print(
|
223 |
+
self.args[0]), printer._print(self.args[1])
|
224 |
+
)
|
225 |
+
|
226 |
+
def _sympystr(self, printer, *args):
|
227 |
+
return "[%s,%s]" % (
|
228 |
+
printer._print(self.args[0]), printer._print(self.args[1]))
|
229 |
+
|
230 |
+
def _pretty(self, printer, *args):
|
231 |
+
pform = printer._print(self.args[0], *args)
|
232 |
+
pform = prettyForm(*pform.right(prettyForm(',')))
|
233 |
+
pform = prettyForm(*pform.right(printer._print(self.args[1], *args)))
|
234 |
+
pform = prettyForm(*pform.parens(left='[', right=']'))
|
235 |
+
return pform
|
236 |
+
|
237 |
+
def _latex(self, printer, *args):
|
238 |
+
return "\\left[%s,%s\\right]" % tuple([
|
239 |
+
printer._print(arg, *args) for arg in self.args])
|