jasonfan commited on
Commit
5c43c6c
·
verified ·
1 Parent(s): 61f7854

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_mathematica.py +280 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_maxima.py +50 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_sym_expr.py +209 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_sympy_parser.py +371 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/__init__.py +12 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/__init__.py +53 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/_mixin.py +53 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/activation.py +869 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py +1763 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/musculotendon.py +1424 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py +0 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_activation.py +348 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_curve.py +1695 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_mixin.py +48 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_musculotendon.py +837 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py +10 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/arch.py +1025 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py +0 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/cable.py +815 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py +0 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_arch.py +61 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py +1118 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_cable.py +83 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py +100 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py +1108 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/__init__.py +17 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/control_plots.py +1135 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/lti.py +0 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py +0 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py +332 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py +0 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/__init__.py +0 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py +716 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py +0 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py +427 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hydrogen.py +265 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/matrices.py +176 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py +90 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/actuator.py +1147 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/body.py +710 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/body_base.py +94 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py +735 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/inertia.py +199 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py +2188 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py +318 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py +859 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py +512 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py +474 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/loads.py +177 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/method.py +39 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_mathematica.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import sin, Function, symbols, Dummy, Lambda, cos
2
+ from sympy.parsing.mathematica import parse_mathematica, MathematicaParser
3
+ from sympy.core.sympify import sympify
4
+ from sympy.abc import n, w, x, y, z
5
+ from sympy.testing.pytest import raises
6
+
7
+
8
+ def test_mathematica():
9
+ d = {
10
+ '- 6x': '-6*x',
11
+ 'Sin[x]^2': 'sin(x)**2',
12
+ '2(x-1)': '2*(x-1)',
13
+ '3y+8': '3*y+8',
14
+ 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
15
+ 'x+y': 'x+y',
16
+ '355/113': '355/113',
17
+ '2.718281828': '2.718281828',
18
+ 'Cos(1/2 * π)': 'Cos(π/2)',
19
+ 'Sin[12]': 'sin(12)',
20
+ 'Exp[Log[4]]': 'exp(log(4))',
21
+ '(x+1)(x+3)': '(x+1)*(x+3)',
22
+ 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))',
23
+ 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))',
24
+ '2*Sin[x+y]': '2*sin(x+y)',
25
+ 'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
26
+ 'Sin[Cos[x]]': 'sin(cos(x))',
27
+ '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259
28
+ '+Sqrt[2]': 'sqrt(2)',
29
+ '-Sqrt[2]': '-sqrt(2)',
30
+ '-1/Sqrt[2]': '-1/sqrt(2)',
31
+ '-(1/Sqrt[3])': '-(1/sqrt(3))',
32
+ '1/(2*Sqrt[5])': '1/(2*sqrt(5))',
33
+ 'Mod[5,3]': 'Mod(5,3)',
34
+ '-Mod[5,3]': '-Mod(5,3)',
35
+ '(x+1)y': '(x+1)*y',
36
+ 'x(y+1)': 'x*(y+1)',
37
+ 'Sin[x]Cos[y]': 'sin(x)*cos(y)',
38
+ 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2',
39
+ 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)',
40
+ 'x y': 'x*y',
41
+ 'x y': 'x*y',
42
+ '2 x': '2*x',
43
+ 'x 8': 'x*8',
44
+ '2 8': '2*8',
45
+ '4.x': '4.*x',
46
+ '4. 3': '4.*3',
47
+ '4. 3.': '4.*3.',
48
+ '1 2 3': '1*2*3',
49
+ ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))',
50
+ 'Log[2,4]': 'log(4,2)',
51
+ 'Log[Log[2,4],4]': 'log(4,log(4,2))',
52
+ 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))',
53
+ 'ArcSin[Cos[0]]': 'asin(cos(0))',
54
+ 'Log2[16]': 'log(16,2)',
55
+ 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)',
56
+ 'Min[1,-2,3]': 'Min(1,-2,3)',
57
+ 'Exp[I Pi/2]': 'exp(I*pi/2)',
58
+ 'ArcTan[x,y]': 'atan2(y,x)',
59
+ 'Pochhammer[x,y]': 'rf(x,y)',
60
+ 'ExpIntegralEi[x]': 'Ei(x)',
61
+ 'SinIntegral[x]': 'Si(x)',
62
+ 'CosIntegral[x]': 'Ci(x)',
63
+ 'AiryAi[x]': 'airyai(x)',
64
+ 'AiryAiPrime[5]': 'airyaiprime(5)',
65
+ 'AiryBi[x]': 'airybi(x)',
66
+ 'AiryBiPrime[7]': 'airybiprime(7)',
67
+ 'LogIntegral[4]': ' li(4)',
68
+ 'PrimePi[7]': 'primepi(7)',
69
+ 'Prime[5]': 'prime(5)',
70
+ 'PrimeQ[5]': 'isprime(5)',
71
+ 'Rational[2,19]': 'Rational(2,19)', # test case for issue 25716
72
+ }
73
+
74
+ for e in d:
75
+ assert parse_mathematica(e) == sympify(d[e])
76
+
77
+ # The parsed form of this expression should not evaluate the Lambda object:
78
+ assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2
79
+
80
+ d1, d2, d3 = symbols("d1:4", cls=Dummy)
81
+ assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3)))
82
+ assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2)))
83
+ assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3)
84
+ assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2)
85
+
86
+
87
+ def test_parser_mathematica_tokenizer():
88
+ parser = MathematicaParser()
89
+
90
+ chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr))
91
+
92
+ # Basic patterns
93
+ assert chain("x") == "x"
94
+ assert chain("42") == "42"
95
+ assert chain(".2") == ".2"
96
+ assert chain("+x") == "x"
97
+ assert chain("-1") == "-1"
98
+ assert chain("- 3") == "-3"
99
+ assert chain("α") == "α"
100
+ assert chain("+Sin[x]") == ["Sin", "x"]
101
+ assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]]
102
+ assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]]
103
+ assert chain("(x)") == "x"
104
+ assert chain("(+x)") == "x"
105
+ assert chain("-a") == ["Times", "-1", "a"]
106
+ assert chain("(-x)") == ["Times", "-1", "x"]
107
+ assert chain("(x + y)") == ["Plus", "x", "y"]
108
+ assert chain("3 + 4") == ["Plus", "3", "4"]
109
+ assert chain("a - 3") == ["Plus", "a", "-3"]
110
+ assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]]
111
+ assert chain("7 * 8") == ["Times", "7", "8"]
112
+ assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]]
113
+ assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]]
114
+ assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]]
115
+
116
+ # Missing asterisk (*) patterns:
117
+ assert chain("x y") == ["Times", "x", "y"]
118
+ assert chain("3 4") == ["Times", "3", "4"]
119
+ assert chain("a[b] c") == ["Times", ["a", "b"], "c"]
120
+ assert chain("(x) (y)") == ["Times", "x", "y"]
121
+ assert chain("3 (a)") == ["Times", "3", "a"]
122
+ assert chain("(a) b") == ["Times", "a", "b"]
123
+ assert chain("4.2") == "4.2"
124
+ assert chain("4 2") == ["Times", "4", "2"]
125
+ assert chain("4 2") == ["Times", "4", "2"]
126
+ assert chain("3 . 4") == ["Dot", "3", "4"]
127
+ assert chain("4. 2") == ["Times", "4.", "2"]
128
+ assert chain("x.y") == ["Dot", "x", "y"]
129
+ assert chain("4.y") == ["Times", "4.", "y"]
130
+ assert chain("4 .y") == ["Dot", "4", "y"]
131
+ assert chain("x.4") == ["Times", "x", ".4"]
132
+ assert chain("x0.3") == ["Times", "x0", ".3"]
133
+ assert chain("x. 4") == ["Dot", "x", "4"]
134
+
135
+ # Comments
136
+ assert chain("a (* +b *) + c") == ["Plus", "a", "c"]
137
+ assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"]
138
+ assert chain("""a + (*
139
+ + b
140
+ *) c + (* d
141
+ *) e
142
+ """) == ["Plus", "a", "c", "e"]
143
+
144
+ # Operators couples + and -, * and / are mutually associative:
145
+ # (i.e. expression gets flattened when mixing these operators)
146
+ assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]]
147
+ assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"]
148
+ assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]]
149
+ assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"]
150
+ assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]]
151
+ assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"]
152
+ assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]]
153
+ assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]]
154
+ assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]]
155
+ assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]]
156
+ assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"]
157
+
158
+ # Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { }
159
+ assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"]
160
+ assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"]
161
+ assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]]
162
+ assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]]
163
+ assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"]
164
+ assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]]
165
+ assert chain("{{a}}") == ["List", ["List", "a"]]
166
+ assert chain("a[b, c]") == ["a", "b", "c"]
167
+ assert chain("a[[b, c]]") == ["Part", "a", "b", "c"]
168
+ assert chain("a[b[c]]") == ["a", ["b", "c"]]
169
+ assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]]
170
+ assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]]
171
+ assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]]
172
+ assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]]
173
+ assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]]
174
+ assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]]
175
+ assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
176
+ assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
177
+ assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]]
178
+
179
+ # Flat operator:
180
+ assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"]
181
+ assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"]
182
+
183
+ # Right priority operator:
184
+ assert chain("a^b") == ["Power", "a", "b"]
185
+ assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]]
186
+ assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]]
187
+
188
+ # Left priority operator:
189
+ assert chain("a/.b") == ["ReplaceAll", "a", "b"]
190
+ assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"]
191
+
192
+ assert chain("a//b") == ["a", "b"]
193
+ assert chain("a//b//c") == [["a", "b"], "c"]
194
+ assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"]
195
+
196
+ # Compound expressions
197
+ assert chain("a;b") == ["CompoundExpression", "a", "b"]
198
+ assert chain("a;") == ["CompoundExpression", "a", "Null"]
199
+ assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"]
200
+ assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]]
201
+ assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"]
202
+ assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"]
203
+
204
+ # New lines
205
+ assert chain("a\nb\n") == ["CompoundExpression", "a", "b"]
206
+ assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]]
207
+ assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"]
208
+ assert chain("a + \nb\n") == ["Plus", "a", "b"]
209
+ assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]]
210
+ assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]]
211
+
212
+ # Patterns
213
+ assert chain("y_") == ["Pattern", "y", ["Blank"]]
214
+ assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]]
215
+ assert chain("y__") == ["Pattern", "y", ["BlankSequence"]]
216
+ assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]]
217
+ assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]]
218
+ assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"]
219
+
220
+ # Slots for lambda functions
221
+ assert chain("#") == ["Slot", "1"]
222
+ assert chain("#3") == ["Slot", "3"]
223
+ assert chain("#n") == ["Slot", "n"]
224
+ assert chain("##") == ["SlotSequence", "1"]
225
+ assert chain("##a") == ["SlotSequence", "a"]
226
+
227
+ # Lambda functions
228
+ assert chain("x&") == ["Function", "x"]
229
+ assert chain("#&") == ["Function", ["Slot", "1"]]
230
+ assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]]
231
+ assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]]
232
+ assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]]
233
+ assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"]
234
+ assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"]
235
+ assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]]
236
+
237
+ # Strings inside Mathematica expressions:
238
+ assert chain('"abc"') == ["_Str", "abc"]
239
+ assert chain('"a\\"b"') == ["_Str", 'a"b']
240
+ # This expression does not make sense mathematically, it's just testing the parser:
241
+ assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]]
242
+ assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"]
243
+ assert chain('"a" (* b *) ') == ["_Str", "a"]
244
+ assert chain('"a [ b] "') == ["_Str", "a [ b] "]
245
+ raises(SyntaxError, lambda: chain('"'))
246
+ raises(SyntaxError, lambda: chain('"\\"'))
247
+ raises(SyntaxError, lambda: chain('"abc'))
248
+ raises(SyntaxError, lambda: chain('"abc\\"def'))
249
+
250
+ # Invalid expressions:
251
+ raises(SyntaxError, lambda: chain("(,"))
252
+ raises(SyntaxError, lambda: chain("()"))
253
+ raises(SyntaxError, lambda: chain("a (* b"))
254
+
255
+
256
+ def test_parser_mathematica_exp_alt():
257
+ parser = MathematicaParser()
258
+
259
+ convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr))
260
+ convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr))
261
+
262
+ Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function)
263
+
264
+ full_form1 = "Sin[Times[x, y]]"
265
+ full_form2 = "Plus[Times[x, y], z]"
266
+ full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]"
267
+ full_form4 = "Rational[Rational[x, y], z]"
268
+
269
+ assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]]
270
+ assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"]
271
+ assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]]
272
+ assert parser._from_fullform_to_fullformlist(full_form4) == ["Rational", ["Rational", "x", "y"], "z"]
273
+
274
+ assert convert_chain2(full_form1) == Sin(Times(x, y))
275
+ assert convert_chain2(full_form2) == Plus(Times(x, y), z)
276
+ assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n)))
277
+
278
+ assert convert_chain3(full_form1) == sin(x*y)
279
+ assert convert_chain3(full_form2) == x*y + z
280
+ assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_maxima.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.parsing.maxima import parse_maxima
2
+ from sympy.core.numbers import (E, Rational, oo)
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions.combinatorial.factorials import factorial
5
+ from sympy.functions.elementary.complexes import Abs
6
+ from sympy.functions.elementary.exponential import log
7
+ from sympy.functions.elementary.trigonometric import (cos, sin)
8
+ from sympy.abc import x
9
+
10
+ n = Symbol('n', integer=True)
11
+
12
+
13
+ def test_parser():
14
+ assert Abs(parse_maxima('float(1/3)') - 0.333333333) < 10**(-5)
15
+ assert parse_maxima('13^26') == 91733330193268616658399616009
16
+ assert parse_maxima('sin(%pi/2) + cos(%pi/3)') == Rational(3, 2)
17
+ assert parse_maxima('log(%e)') == 1
18
+
19
+
20
+ def test_injection():
21
+ parse_maxima('c: x+1', globals=globals())
22
+ # c created by parse_maxima
23
+ assert c == x + 1 # noqa:F821
24
+
25
+ parse_maxima('g: sqrt(81)', globals=globals())
26
+ # g created by parse_maxima
27
+ assert g == 9 # noqa:F821
28
+
29
+
30
+ def test_maxima_functions():
31
+ assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1
32
+ assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2
33
+ assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2
34
+ assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \
35
+ -1 + 2*cos(x)**2 + 2*cos(x)*sin(x)
36
+ assert parse_maxima('solve(x^2-4,x)') == [-2, 2]
37
+ assert parse_maxima('limit((1+1/x)^x,x,inf)') == E
38
+ assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') is -oo
39
+ assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x))
40
+ assert parse_maxima('sum(k, k, 1, n)', name_dict={
41
+ "n": Symbol('n', integer=True),
42
+ "k": Symbol('k', integer=True)
43
+ }) == (n**2 + n)/2
44
+ assert parse_maxima('product(k, k, 1, n)', name_dict={
45
+ "n": Symbol('n', integer=True),
46
+ "k": Symbol('k', integer=True)
47
+ }) == factorial(n)
48
+ assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1
49
+ assert Abs( parse_maxima(
50
+ 'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_sym_expr.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.parsing.sym_expr import SymPyExpression
2
+ from sympy.testing.pytest import raises
3
+ from sympy.external import import_module
4
+
5
+ lfortran = import_module('lfortran')
6
+ cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']})
7
+
8
+ if lfortran and cin:
9
+ from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
10
+ Declaration, FloatType)
11
+ from sympy.core import Integer, Float
12
+ from sympy.core.symbol import Symbol
13
+
14
+ expr1 = SymPyExpression()
15
+ src = """\
16
+ integer :: a, b, c, d
17
+ real :: p, q, r, s
18
+ """
19
+
20
+ def test_c_parse():
21
+ src1 = """\
22
+ int a, b = 4;
23
+ float c, d = 2.4;
24
+ """
25
+ expr1.convert_to_expr(src1, 'c')
26
+ ls = expr1.return_expr()
27
+
28
+ assert ls[0] == Declaration(
29
+ Variable(
30
+ Symbol('a'),
31
+ type=IntBaseType(String('intc'))
32
+ )
33
+ )
34
+ assert ls[1] == Declaration(
35
+ Variable(
36
+ Symbol('b'),
37
+ type=IntBaseType(String('intc')),
38
+ value=Integer(4)
39
+ )
40
+ )
41
+ assert ls[2] == Declaration(
42
+ Variable(
43
+ Symbol('c'),
44
+ type=FloatType(
45
+ String('float32'),
46
+ nbits=Integer(32),
47
+ nmant=Integer(23),
48
+ nexp=Integer(8)
49
+ )
50
+ )
51
+ )
52
+ assert ls[3] == Declaration(
53
+ Variable(
54
+ Symbol('d'),
55
+ type=FloatType(
56
+ String('float32'),
57
+ nbits=Integer(32),
58
+ nmant=Integer(23),
59
+ nexp=Integer(8)
60
+ ),
61
+ value=Float('2.3999999999999999', precision=53)
62
+ )
63
+ )
64
+
65
+
66
+ def test_fortran_parse():
67
+ expr = SymPyExpression(src, 'f')
68
+ ls = expr.return_expr()
69
+
70
+ assert ls[0] == Declaration(
71
+ Variable(
72
+ Symbol('a'),
73
+ type=IntBaseType(String('integer')),
74
+ value=Integer(0)
75
+ )
76
+ )
77
+ assert ls[1] == Declaration(
78
+ Variable(
79
+ Symbol('b'),
80
+ type=IntBaseType(String('integer')),
81
+ value=Integer(0)
82
+ )
83
+ )
84
+ assert ls[2] == Declaration(
85
+ Variable(
86
+ Symbol('c'),
87
+ type=IntBaseType(String('integer')),
88
+ value=Integer(0)
89
+ )
90
+ )
91
+ assert ls[3] == Declaration(
92
+ Variable(
93
+ Symbol('d'),
94
+ type=IntBaseType(String('integer')),
95
+ value=Integer(0)
96
+ )
97
+ )
98
+ assert ls[4] == Declaration(
99
+ Variable(
100
+ Symbol('p'),
101
+ type=FloatBaseType(String('real')),
102
+ value=Float('0.0', precision=53)
103
+ )
104
+ )
105
+ assert ls[5] == Declaration(
106
+ Variable(
107
+ Symbol('q'),
108
+ type=FloatBaseType(String('real')),
109
+ value=Float('0.0', precision=53)
110
+ )
111
+ )
112
+ assert ls[6] == Declaration(
113
+ Variable(
114
+ Symbol('r'),
115
+ type=FloatBaseType(String('real')),
116
+ value=Float('0.0', precision=53)
117
+ )
118
+ )
119
+ assert ls[7] == Declaration(
120
+ Variable(
121
+ Symbol('s'),
122
+ type=FloatBaseType(String('real')),
123
+ value=Float('0.0', precision=53)
124
+ )
125
+ )
126
+
127
+
128
+ def test_convert_py():
129
+ src1 = (
130
+ src +
131
+ """\
132
+ a = b + c
133
+ s = p * q / r
134
+ """
135
+ )
136
+ expr1.convert_to_expr(src1, 'f')
137
+ exp_py = expr1.convert_to_python()
138
+ assert exp_py == [
139
+ 'a = 0',
140
+ 'b = 0',
141
+ 'c = 0',
142
+ 'd = 0',
143
+ 'p = 0.0',
144
+ 'q = 0.0',
145
+ 'r = 0.0',
146
+ 's = 0.0',
147
+ 'a = b + c',
148
+ 's = p*q/r'
149
+ ]
150
+
151
+
152
+ def test_convert_fort():
153
+ src1 = (
154
+ src +
155
+ """\
156
+ a = b + c
157
+ s = p * q / r
158
+ """
159
+ )
160
+ expr1.convert_to_expr(src1, 'f')
161
+ exp_fort = expr1.convert_to_fortran()
162
+ assert exp_fort == [
163
+ ' integer*4 a',
164
+ ' integer*4 b',
165
+ ' integer*4 c',
166
+ ' integer*4 d',
167
+ ' real*8 p',
168
+ ' real*8 q',
169
+ ' real*8 r',
170
+ ' real*8 s',
171
+ ' a = b + c',
172
+ ' s = p*q/r'
173
+ ]
174
+
175
+
176
+ def test_convert_c():
177
+ src1 = (
178
+ src +
179
+ """\
180
+ a = b + c
181
+ s = p * q / r
182
+ """
183
+ )
184
+ expr1.convert_to_expr(src1, 'f')
185
+ exp_c = expr1.convert_to_c()
186
+ assert exp_c == [
187
+ 'int a = 0',
188
+ 'int b = 0',
189
+ 'int c = 0',
190
+ 'int d = 0',
191
+ 'double p = 0.0',
192
+ 'double q = 0.0',
193
+ 'double r = 0.0',
194
+ 'double s = 0.0',
195
+ 'a = b + c;',
196
+ 's = p*q/r;'
197
+ ]
198
+
199
+
200
+ def test_exceptions():
201
+ src = 'int a;'
202
+ raises(ValueError, lambda: SymPyExpression(src))
203
+ raises(ValueError, lambda: SymPyExpression(mode = 'c'))
204
+ raises(NotImplementedError, lambda: SymPyExpression(src, mode = 'd'))
205
+
206
+ elif not lfortran and not cin:
207
+ def test_raise():
208
+ raises(ImportError, lambda: SymPyExpression('int a;', 'c'))
209
+ raises(ImportError, lambda: SymPyExpression('integer :: a', 'f'))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/parsing/tests/test_sympy_parser.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+
4
+ import builtins
5
+ import types
6
+
7
+ from sympy.assumptions import Q
8
+ from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq, Lt, Le, Gt, Ge, Ne
9
+ from sympy.functions import exp, factorial, factorial2, sin, Min, Max
10
+ from sympy.logic import And
11
+ from sympy.series import Limit
12
+ from sympy.testing.pytest import raises
13
+
14
+ from sympy.parsing.sympy_parser import (
15
+ parse_expr, standard_transformations, rationalize, TokenError,
16
+ split_symbols, implicit_multiplication, convert_equals_signs,
17
+ convert_xor, function_exponentiation, lambda_notation, auto_symbol,
18
+ repeated_decimals, implicit_multiplication_application,
19
+ auto_number, factorial_notation, implicit_application,
20
+ _transformation, T
21
+ )
22
+
23
+
24
+ def test_sympy_parser():
25
+ x = Symbol('x')
26
+ inputs = {
27
+ '2*x': 2 * x,
28
+ '3.00': Float(3),
29
+ '22/7': Rational(22, 7),
30
+ '2+3j': 2 + 3*I,
31
+ 'exp(x)': exp(x),
32
+ 'x!': factorial(x),
33
+ 'x!!': factorial2(x),
34
+ '(x + 1)! - 1': factorial(x + 1) - 1,
35
+ '3.[3]': Rational(10, 3),
36
+ '.0[3]': Rational(1, 30),
37
+ '3.2[3]': Rational(97, 30),
38
+ '1.3[12]': Rational(433, 330),
39
+ '1 + 3.[3]': Rational(13, 3),
40
+ '1 + .0[3]': Rational(31, 30),
41
+ '1 + 3.2[3]': Rational(127, 30),
42
+ '.[0011]': Rational(1, 909),
43
+ '0.1[00102] + 1': Rational(366697, 333330),
44
+ '1.[0191]': Rational(10190, 9999),
45
+ '10!': 3628800,
46
+ '-(2)': -Integer(2),
47
+ '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
48
+ 'Symbol("x").free_symbols': x.free_symbols,
49
+ "S('S(3).n(n=3)')": Float(3, 3),
50
+ 'factorint(12, visual=True)': Mul(
51
+ Pow(2, 2, evaluate=False),
52
+ Pow(3, 1, evaluate=False),
53
+ evaluate=False),
54
+ 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
55
+ 'Q.even(x)': Q.even(x),
56
+
57
+
58
+ }
59
+ for text, result in inputs.items():
60
+ assert parse_expr(text) == result
61
+
62
+ raises(TypeError, lambda:
63
+ parse_expr('x', standard_transformations))
64
+ raises(TypeError, lambda:
65
+ parse_expr('x', transformations=lambda x,y: 1))
66
+ raises(TypeError, lambda:
67
+ parse_expr('x', transformations=(lambda x,y: 1,)))
68
+ raises(TypeError, lambda: parse_expr('x', transformations=((),)))
69
+ raises(TypeError, lambda: parse_expr('x', {}, [], []))
70
+ raises(TypeError, lambda: parse_expr('x', [], [], {}))
71
+ raises(TypeError, lambda: parse_expr('x', [], [], {}))
72
+
73
+
74
+ def test_rationalize():
75
+ inputs = {
76
+ '0.123': Rational(123, 1000)
77
+ }
78
+ transformations = standard_transformations + (rationalize,)
79
+ for text, result in inputs.items():
80
+ assert parse_expr(text, transformations=transformations) == result
81
+
82
+
83
+ def test_factorial_fail():
84
+ inputs = ['x!!!', 'x!!!!', '(!)']
85
+
86
+
87
+ for text in inputs:
88
+ try:
89
+ parse_expr(text)
90
+ assert False
91
+ except TokenError:
92
+ assert True
93
+
94
+
95
+ def test_repeated_fail():
96
+ inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
97
+ '0.1[[1]]', '0x1.1[1]']
98
+
99
+
100
+ # All are valid Python, so only raise TypeError for invalid indexing
101
+ for text in inputs:
102
+ raises(TypeError, lambda: parse_expr(text))
103
+
104
+
105
+ inputs = ['0.1[', '0.1[1', '0.1[]']
106
+ for text in inputs:
107
+ raises((TokenError, SyntaxError), lambda: parse_expr(text))
108
+
109
+
110
+ def test_repeated_dot_only():
111
+ assert parse_expr('.[1]') == Rational(1, 9)
112
+ assert parse_expr('1 + .[1]') == Rational(10, 9)
113
+
114
+
115
+ def test_local_dict():
116
+ local_dict = {
117
+ 'my_function': lambda x: x + 2
118
+ }
119
+ inputs = {
120
+ 'my_function(2)': Integer(4)
121
+ }
122
+ for text, result in inputs.items():
123
+ assert parse_expr(text, local_dict=local_dict) == result
124
+
125
+
126
+ def test_local_dict_split_implmult():
127
+ t = standard_transformations + (split_symbols, implicit_multiplication,)
128
+ w = Symbol('w', real=True)
129
+ y = Symbol('y')
130
+ assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
131
+
132
+
133
+ def test_local_dict_symbol_to_fcn():
134
+ x = Symbol('x')
135
+ d = {'foo': Function('bar')}
136
+ assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
137
+ d = {'foo': Symbol('baz')}
138
+ raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
139
+
140
+
141
+ def test_global_dict():
142
+ global_dict = {
143
+ 'Symbol': Symbol
144
+ }
145
+ inputs = {
146
+ 'Q & S': And(Symbol('Q'), Symbol('S'))
147
+ }
148
+ for text, result in inputs.items():
149
+ assert parse_expr(text, global_dict=global_dict) == result
150
+
151
+
152
+ def test_no_globals():
153
+
154
+ # Replicate creating the default global_dict:
155
+ default_globals = {}
156
+ exec('from sympy import *', default_globals)
157
+ builtins_dict = vars(builtins)
158
+ for name, obj in builtins_dict.items():
159
+ if isinstance(obj, types.BuiltinFunctionType):
160
+ default_globals[name] = obj
161
+ default_globals['max'] = Max
162
+ default_globals['min'] = Min
163
+
164
+ # Need to include Symbol or parse_expr will not work:
165
+ default_globals.pop('Symbol')
166
+ global_dict = {'Symbol':Symbol}
167
+
168
+ for name in default_globals:
169
+ obj = parse_expr(name, global_dict=global_dict)
170
+ assert obj == Symbol(name)
171
+
172
+
173
+ def test_issue_2515():
174
+ raises(TokenError, lambda: parse_expr('(()'))
175
+ raises(TokenError, lambda: parse_expr('"""'))
176
+
177
+
178
+ def test_issue_7663():
179
+ x = Symbol('x')
180
+ e = '2*(x+1)'
181
+ assert parse_expr(e, evaluate=False) == parse_expr(e, evaluate=False)
182
+ assert parse_expr(e, evaluate=False).equals(2*(x+1))
183
+
184
+ def test_recursive_evaluate_false_10560():
185
+ inputs = {
186
+ '4*-3' : '4*-3',
187
+ '-4*3' : '(-4)*3',
188
+ "-2*x*y": '(-2)*x*y',
189
+ "x*-4*x": "x*(-4)*x"
190
+ }
191
+ for text, result in inputs.items():
192
+ assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
193
+
194
+
195
+ def test_function_evaluate_false():
196
+ inputs = [
197
+ 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
198
+ 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
199
+ 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
200
+ 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
201
+ 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
202
+ 'exp(0)', 'log(0)', 'sqrt(0)',
203
+ ]
204
+ for case in inputs:
205
+ expr = parse_expr(case, evaluate=False)
206
+ assert case == str(expr) != str(expr.doit())
207
+ assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
208
+ assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
209
+
210
+
211
+ def test_issue_10773():
212
+ inputs = {
213
+ '-10/5': '(-10)/5',
214
+ '-10/-5' : '(-10)/(-5)',
215
+ }
216
+ for text, result in inputs.items():
217
+ assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
218
+
219
+
220
+ def test_split_symbols():
221
+ transformations = standard_transformations + \
222
+ (split_symbols, implicit_multiplication,)
223
+ x = Symbol('x')
224
+ y = Symbol('y')
225
+ xy = Symbol('xy')
226
+
227
+
228
+ assert parse_expr("xy") == xy
229
+ assert parse_expr("xy", transformations=transformations) == x*y
230
+
231
+
232
+ def test_split_symbols_function():
233
+ transformations = standard_transformations + \
234
+ (split_symbols, implicit_multiplication,)
235
+ x = Symbol('x')
236
+ y = Symbol('y')
237
+ a = Symbol('a')
238
+ f = Function('f')
239
+
240
+
241
+ assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
242
+ assert parse_expr("af(x+1)", transformations=transformations,
243
+ local_dict={'f':f}) == a*f(x+1)
244
+
245
+
246
+ def test_functional_exponent():
247
+ t = standard_transformations + (convert_xor, function_exponentiation)
248
+ x = Symbol('x')
249
+ y = Symbol('y')
250
+ a = Symbol('a')
251
+ yfcn = Function('y')
252
+ assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
253
+ assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
254
+ assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
255
+ assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
256
+ assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
257
+
258
+
259
+ def test_match_parentheses_implicit_multiplication():
260
+ transformations = standard_transformations + \
261
+ (implicit_multiplication,)
262
+ raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
263
+
264
+
265
+ def test_convert_equals_signs():
266
+ transformations = standard_transformations + \
267
+ (convert_equals_signs, )
268
+ x = Symbol('x')
269
+ y = Symbol('y')
270
+ assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
271
+ assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
272
+ assert parse_expr("(2*y = x) = False",
273
+ transformations=transformations) == Eq(Eq(2*y, x), False)
274
+
275
+
276
+ def test_parse_function_issue_3539():
277
+ x = Symbol('x')
278
+ f = Function('f')
279
+ assert parse_expr('f(x)') == f(x)
280
+
281
+ def test_issue_24288():
282
+ assert parse_expr("1 < 2", evaluate=False) == Lt(1, 2, evaluate=False)
283
+ assert parse_expr("1 <= 2", evaluate=False) == Le(1, 2, evaluate=False)
284
+ assert parse_expr("1 > 2", evaluate=False) == Gt(1, 2, evaluate=False)
285
+ assert parse_expr("1 >= 2", evaluate=False) == Ge(1, 2, evaluate=False)
286
+ assert parse_expr("1 != 2", evaluate=False) == Ne(1, 2, evaluate=False)
287
+ assert parse_expr("1 == 2", evaluate=False) == Eq(1, 2, evaluate=False)
288
+ assert parse_expr("1 < 2 < 3", evaluate=False) == And(Lt(1, 2, evaluate=False), Lt(2, 3, evaluate=False), evaluate=False)
289
+ assert parse_expr("1 <= 2 <= 3", evaluate=False) == And(Le(1, 2, evaluate=False), Le(2, 3, evaluate=False), evaluate=False)
290
+ assert parse_expr("1 < 2 <= 3 < 4", evaluate=False) == \
291
+ And(Lt(1, 2, evaluate=False), Le(2, 3, evaluate=False), Lt(3, 4, evaluate=False), evaluate=False)
292
+ # Valid Python relational operators that SymPy does not decide how to handle them yet
293
+ raises(ValueError, lambda: parse_expr("1 in 2", evaluate=False))
294
+ raises(ValueError, lambda: parse_expr("1 is 2", evaluate=False))
295
+ raises(ValueError, lambda: parse_expr("1 not in 2", evaluate=False))
296
+ raises(ValueError, lambda: parse_expr("1 is not 2", evaluate=False))
297
+
298
+ def test_split_symbols_numeric():
299
+ transformations = (
300
+ standard_transformations +
301
+ (implicit_multiplication_application,))
302
+
303
+ n = Symbol('n')
304
+ expr1 = parse_expr('2**n * 3**n')
305
+ expr2 = parse_expr('2**n3**n', transformations=transformations)
306
+ assert expr1 == expr2 == 2**n*3**n
307
+
308
+ expr1 = parse_expr('n12n34', transformations=transformations)
309
+ assert expr1 == n*12*n*34
310
+
311
+
312
+ def test_unicode_names():
313
+ assert parse_expr('α') == Symbol('α')
314
+
315
+
316
+ def test_python3_features():
317
+ assert parse_expr("123_456") == 123456
318
+ assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
319
+ assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
320
+ assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
321
+ assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
322
+ assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
323
+
324
+
325
+ def test_issue_19501():
326
+ x = Symbol('x')
327
+ eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
328
+ standard_transformations +
329
+ (implicit_multiplication_application,)))
330
+ assert eq.free_symbols == {x}
331
+
332
+
333
+ def test_parsing_definitions():
334
+ from sympy.abc import x
335
+ assert len(_transformation) == 12 # if this changes, extend below
336
+ assert _transformation[0] == lambda_notation
337
+ assert _transformation[1] == auto_symbol
338
+ assert _transformation[2] == repeated_decimals
339
+ assert _transformation[3] == auto_number
340
+ assert _transformation[4] == factorial_notation
341
+ assert _transformation[5] == implicit_multiplication_application
342
+ assert _transformation[6] == convert_xor
343
+ assert _transformation[7] == implicit_application
344
+ assert _transformation[8] == implicit_multiplication
345
+ assert _transformation[9] == convert_equals_signs
346
+ assert _transformation[10] == function_exponentiation
347
+ assert _transformation[11] == rationalize
348
+ assert T[:5] == T[0,1,2,3,4] == standard_transformations
349
+ t = _transformation
350
+ assert T[-1, 0] == (t[len(t) - 1], t[0])
351
+ assert T[:5, 8] == standard_transformations + (t[8],)
352
+ assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
353
+ assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
354
+
355
+
356
+ def test_builtins():
357
+ cases = [
358
+ ('abs(x)', 'Abs(x)'),
359
+ ('max(x, y)', 'Max(x, y)'),
360
+ ('min(x, y)', 'Min(x, y)'),
361
+ ('pow(x, y)', 'Pow(x, y)'),
362
+ ]
363
+ for built_in_func_call, sympy_func_call in cases:
364
+ assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
365
+ assert str(parse_expr('pow(38, -1, 97)')) == '23'
366
+
367
+
368
+ def test_issue_22822():
369
+ raises(ValueError, lambda: parse_expr('x', {'': 1}))
370
+ data = {'some_parameter': None}
371
+ assert parse_expr('some_parameter is None', data) is True
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module that helps solving problems in physics.
3
+ """
4
+
5
+ from . import units
6
+ from .matrices import mgamma, msigma, minkowski_tensor, mdft
7
+
8
+ __all__ = [
9
+ 'units',
10
+
11
+ 'mgamma', 'msigma', 'minkowski_tensor', 'mdft',
12
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Biomechanics extension for SymPy.
2
+
3
+ Includes biomechanics-related constructs which allows users to extend multibody
4
+ models created using `sympy.physics.mechanics` into biomechanical or
5
+ musculoskeletal models involding musculotendons and activation dynamics.
6
+
7
+ """
8
+
9
+ from .activation import (
10
+ ActivationBase,
11
+ FirstOrderActivationDeGroote2016,
12
+ ZerothOrderActivation,
13
+ )
14
+ from .curve import (
15
+ CharacteristicCurveCollection,
16
+ CharacteristicCurveFunction,
17
+ FiberForceLengthActiveDeGroote2016,
18
+ FiberForceLengthPassiveDeGroote2016,
19
+ FiberForceLengthPassiveInverseDeGroote2016,
20
+ FiberForceVelocityDeGroote2016,
21
+ FiberForceVelocityInverseDeGroote2016,
22
+ TendonForceLengthDeGroote2016,
23
+ TendonForceLengthInverseDeGroote2016,
24
+ )
25
+ from .musculotendon import (
26
+ MusculotendonBase,
27
+ MusculotendonDeGroote2016,
28
+ MusculotendonFormulation,
29
+ )
30
+
31
+
32
+ __all__ = [
33
+ # Musculotendon characteristic curve functions
34
+ 'CharacteristicCurveCollection',
35
+ 'CharacteristicCurveFunction',
36
+ 'FiberForceLengthActiveDeGroote2016',
37
+ 'FiberForceLengthPassiveDeGroote2016',
38
+ 'FiberForceLengthPassiveInverseDeGroote2016',
39
+ 'FiberForceVelocityDeGroote2016',
40
+ 'FiberForceVelocityInverseDeGroote2016',
41
+ 'TendonForceLengthDeGroote2016',
42
+ 'TendonForceLengthInverseDeGroote2016',
43
+
44
+ # Activation dynamics classes
45
+ 'ActivationBase',
46
+ 'FirstOrderActivationDeGroote2016',
47
+ 'ZerothOrderActivation',
48
+
49
+ # Musculotendon classes
50
+ 'MusculotendonBase',
51
+ 'MusculotendonDeGroote2016',
52
+ 'MusculotendonFormulation',
53
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/_mixin.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mixin classes for sharing functionality between unrelated classes.
2
+
3
+ This module is named with a leading underscore to signify to users that it's
4
+ "private" and only intended for internal use by the biomechanics module.
5
+
6
+ """
7
+
8
+
9
+ __all__ = ['_NamedMixin']
10
+
11
+
12
+ class _NamedMixin:
13
+ """Mixin class for adding `name` properties.
14
+
15
+ Valid names, as will typically be used by subclasses as a suffix when
16
+ naming automatically-instantiated symbol attributes, must be nonzero length
17
+ strings.
18
+
19
+ Attributes
20
+ ==========
21
+
22
+ name : str
23
+ The name identifier associated with the instance. Must be a string of
24
+ length at least 1.
25
+
26
+ """
27
+
28
+ @property
29
+ def name(self) -> str:
30
+ """The name associated with the class instance."""
31
+ return self._name
32
+
33
+ @name.setter
34
+ def name(self, name: str) -> None:
35
+ if hasattr(self, '_name'):
36
+ msg = (
37
+ f'Can\'t set attribute `name` to {repr(name)} as it is '
38
+ f'immutable.'
39
+ )
40
+ raise AttributeError(msg)
41
+ if not isinstance(name, str):
42
+ msg = (
43
+ f'Name {repr(name)} passed to `name` was of type '
44
+ f'{type(name)}, must be {str}.'
45
+ )
46
+ raise TypeError(msg)
47
+ if name in {''}:
48
+ msg = (
49
+ f'Name {repr(name)} is invalid, must be a nonzero length '
50
+ f'{type(str)}.'
51
+ )
52
+ raise ValueError(msg)
53
+ self._name = name
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/activation.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Activation dynamics for musclotendon models.
2
+
3
+ Musculotendon models are able to produce active force when they are activated,
4
+ which is when a chemical process has taken place within the muscle fibers
5
+ causing them to voluntarily contract. Biologically this chemical process (the
6
+ diffusion of :math:`\textrm{Ca}^{2+}` ions) is not the input in the system,
7
+ electrical signals from the nervous system are. These are termed excitations.
8
+ Activation dynamics, which relates the normalized excitation level to the
9
+ normalized activation level, can be modeled by the models present in this
10
+ module.
11
+
12
+ """
13
+
14
+ from abc import ABC, abstractmethod
15
+ from functools import cached_property
16
+
17
+ from sympy.core.symbol import Symbol
18
+ from sympy.core.numbers import Float, Integer, Rational
19
+ from sympy.functions.elementary.hyperbolic import tanh
20
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, zeros
21
+ from sympy.physics.biomechanics._mixin import _NamedMixin
22
+ from sympy.physics.mechanics import dynamicsymbols
23
+
24
+
25
+ __all__ = [
26
+ 'ActivationBase',
27
+ 'FirstOrderActivationDeGroote2016',
28
+ 'ZerothOrderActivation',
29
+ ]
30
+
31
+
32
+ class ActivationBase(ABC, _NamedMixin):
33
+ """Abstract base class for all activation dynamics classes to inherit from.
34
+
35
+ Notes
36
+ =====
37
+
38
+ Instances of this class cannot be directly instantiated by users. However,
39
+ it can be used to created custom activation dynamics types through
40
+ subclassing.
41
+
42
+ """
43
+
44
+ def __init__(self, name):
45
+ """Initializer for ``ActivationBase``."""
46
+ self.name = str(name)
47
+
48
+ # Symbols
49
+ self._e = dynamicsymbols(f"e_{name}")
50
+ self._a = dynamicsymbols(f"a_{name}")
51
+
52
+ @classmethod
53
+ @abstractmethod
54
+ def with_defaults(cls, name):
55
+ """Alternate constructor that provides recommended defaults for
56
+ constants."""
57
+ pass
58
+
59
+ @property
60
+ def excitation(self):
61
+ """Dynamic symbol representing excitation.
62
+
63
+ Explanation
64
+ ===========
65
+
66
+ The alias ``e`` can also be used to access the same attribute.
67
+
68
+ """
69
+ return self._e
70
+
71
+ @property
72
+ def e(self):
73
+ """Dynamic symbol representing excitation.
74
+
75
+ Explanation
76
+ ===========
77
+
78
+ The alias ``excitation`` can also be used to access the same attribute.
79
+
80
+ """
81
+ return self._e
82
+
83
+ @property
84
+ def activation(self):
85
+ """Dynamic symbol representing activation.
86
+
87
+ Explanation
88
+ ===========
89
+
90
+ The alias ``a`` can also be used to access the same attribute.
91
+
92
+ """
93
+ return self._a
94
+
95
+ @property
96
+ def a(self):
97
+ """Dynamic symbol representing activation.
98
+
99
+ Explanation
100
+ ===========
101
+
102
+ The alias ``activation`` can also be used to access the same attribute.
103
+
104
+ """
105
+ return self._a
106
+
107
+ @property
108
+ @abstractmethod
109
+ def order(self):
110
+ """Order of the (differential) equation governing activation."""
111
+ pass
112
+
113
+ @property
114
+ @abstractmethod
115
+ def state_vars(self):
116
+ """Ordered column matrix of functions of time that represent the state
117
+ variables.
118
+
119
+ Explanation
120
+ ===========
121
+
122
+ The alias ``x`` can also be used to access the same attribute.
123
+
124
+ """
125
+ pass
126
+
127
+ @property
128
+ @abstractmethod
129
+ def x(self):
130
+ """Ordered column matrix of functions of time that represent the state
131
+ variables.
132
+
133
+ Explanation
134
+ ===========
135
+
136
+ The alias ``state_vars`` can also be used to access the same attribute.
137
+
138
+ """
139
+ pass
140
+
141
+ @property
142
+ @abstractmethod
143
+ def input_vars(self):
144
+ """Ordered column matrix of functions of time that represent the input
145
+ variables.
146
+
147
+ Explanation
148
+ ===========
149
+
150
+ The alias ``r`` can also be used to access the same attribute.
151
+
152
+ """
153
+ pass
154
+
155
+ @property
156
+ @abstractmethod
157
+ def r(self):
158
+ """Ordered column matrix of functions of time that represent the input
159
+ variables.
160
+
161
+ Explanation
162
+ ===========
163
+
164
+ The alias ``input_vars`` can also be used to access the same attribute.
165
+
166
+ """
167
+ pass
168
+
169
+ @property
170
+ @abstractmethod
171
+ def constants(self):
172
+ """Ordered column matrix of non-time varying symbols present in ``M``
173
+ and ``F``.
174
+
175
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
176
+ has been used instead of ``Symbol`` for a constant then that attribute
177
+ will not be included in the matrix returned by this property. This is
178
+ because the primary use of this property attribute is to provide an
179
+ ordered sequence of the still-free symbols that require numeric values
180
+ during code generation.
181
+
182
+ Explanation
183
+ ===========
184
+
185
+ The alias ``p`` can also be used to access the same attribute.
186
+
187
+ """
188
+ pass
189
+
190
+ @property
191
+ @abstractmethod
192
+ def p(self):
193
+ """Ordered column matrix of non-time varying symbols present in ``M``
194
+ and ``F``.
195
+
196
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
197
+ has been used instead of ``Symbol`` for a constant then that attribute
198
+ will not be included in the matrix returned by this property. This is
199
+ because the primary use of this property attribute is to provide an
200
+ ordered sequence of the still-free symbols that require numeric values
201
+ during code generation.
202
+
203
+ Explanation
204
+ ===========
205
+
206
+ The alias ``constants`` can also be used to access the same attribute.
207
+
208
+ """
209
+ pass
210
+
211
+ @property
212
+ @abstractmethod
213
+ def M(self):
214
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
215
+
216
+ Explanation
217
+ ===========
218
+
219
+ The square matrix that forms part of the LHS of the linear system of
220
+ ordinary differential equations governing the activation dynamics:
221
+
222
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
223
+
224
+ """
225
+ pass
226
+
227
+ @property
228
+ @abstractmethod
229
+ def F(self):
230
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
231
+
232
+ Explanation
233
+ ===========
234
+
235
+ The column matrix that forms the RHS of the linear system of ordinary
236
+ differential equations governing the activation dynamics:
237
+
238
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
239
+
240
+ """
241
+ pass
242
+
243
+ @abstractmethod
244
+ def rhs(self):
245
+ """
246
+
247
+ Explanation
248
+ ===========
249
+
250
+ The solution to the linear system of ordinary differential equations
251
+ governing the activation dynamics:
252
+
253
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
254
+
255
+ """
256
+ pass
257
+
258
+ def __eq__(self, other):
259
+ """Equality check for activation dynamics."""
260
+ if type(self) != type(other):
261
+ return False
262
+ if self.name != other.name:
263
+ return False
264
+ return True
265
+
266
+ def __repr__(self):
267
+ """Default representation of activation dynamics."""
268
+ return f'{self.__class__.__name__}({self.name!r})'
269
+
270
+
271
+ class ZerothOrderActivation(ActivationBase):
272
+ """Simple zeroth-order activation dynamics mapping excitation to
273
+ activation.
274
+
275
+ Explanation
276
+ ===========
277
+
278
+ Zeroth-order activation dynamics are useful in instances where you want to
279
+ reduce the complexity of your musculotendon dynamics as they simple map
280
+ exictation to activation. As a result, no additional state equations are
281
+ introduced to your system. They also remove a potential source of delay
282
+ between the input and dynamics of your system as no (ordinary) differential
283
+ equations are involved.
284
+
285
+ """
286
+
287
+ def __init__(self, name):
288
+ """Initializer for ``ZerothOrderActivation``.
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ name : str
294
+ The name identifier associated with the instance. Must be a string
295
+ of length at least 1.
296
+
297
+ """
298
+ super().__init__(name)
299
+
300
+ # Zeroth-order activation dynamics has activation equal excitation so
301
+ # overwrite the symbol for activation with the excitation symbol.
302
+ self._a = self._e
303
+
304
+ @classmethod
305
+ def with_defaults(cls, name):
306
+ """Alternate constructor that provides recommended defaults for
307
+ constants.
308
+
309
+ Explanation
310
+ ===========
311
+
312
+ As this concrete class doesn't implement any constants associated with
313
+ its dynamics, this ``classmethod`` simply creates a standard instance
314
+ of ``ZerothOrderActivation``. An implementation is provided to ensure
315
+ a consistent interface between all ``ActivationBase`` concrete classes.
316
+
317
+ """
318
+ return cls(name)
319
+
320
+ @property
321
+ def order(self):
322
+ """Order of the (differential) equation governing activation."""
323
+ return 0
324
+
325
+ @property
326
+ def state_vars(self):
327
+ """Ordered column matrix of functions of time that represent the state
328
+ variables.
329
+
330
+ Explanation
331
+ ===========
332
+
333
+ As zeroth-order activation dynamics simply maps excitation to
334
+ activation, this class has no associated state variables and so this
335
+ property return an empty column ``Matrix`` with shape (0, 1).
336
+
337
+ The alias ``x`` can also be used to access the same attribute.
338
+
339
+ """
340
+ return zeros(0, 1)
341
+
342
+ @property
343
+ def x(self):
344
+ """Ordered column matrix of functions of time that represent the state
345
+ variables.
346
+
347
+ Explanation
348
+ ===========
349
+
350
+ As zeroth-order activation dynamics simply maps excitation to
351
+ activation, this class has no associated state variables and so this
352
+ property return an empty column ``Matrix`` with shape (0, 1).
353
+
354
+ The alias ``state_vars`` can also be used to access the same attribute.
355
+
356
+ """
357
+ return zeros(0, 1)
358
+
359
+ @property
360
+ def input_vars(self):
361
+ """Ordered column matrix of functions of time that represent the input
362
+ variables.
363
+
364
+ Explanation
365
+ ===========
366
+
367
+ Excitation is the only input in zeroth-order activation dynamics and so
368
+ this property returns a column ``Matrix`` with one entry, ``e``, and
369
+ shape (1, 1).
370
+
371
+ The alias ``r`` can also be used to access the same attribute.
372
+
373
+ """
374
+ return Matrix([self._e])
375
+
376
+ @property
377
+ def r(self):
378
+ """Ordered column matrix of functions of time that represent the input
379
+ variables.
380
+
381
+ Explanation
382
+ ===========
383
+
384
+ Excitation is the only input in zeroth-order activation dynamics and so
385
+ this property returns a column ``Matrix`` with one entry, ``e``, and
386
+ shape (1, 1).
387
+
388
+ The alias ``input_vars`` can also be used to access the same attribute.
389
+
390
+ """
391
+ return Matrix([self._e])
392
+
393
+ @property
394
+ def constants(self):
395
+ """Ordered column matrix of non-time varying symbols present in ``M``
396
+ and ``F``.
397
+
398
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
399
+ has been used instead of ``Symbol`` for a constant then that attribute
400
+ will not be included in the matrix returned by this property. This is
401
+ because the primary use of this property attribute is to provide an
402
+ ordered sequence of the still-free symbols that require numeric values
403
+ during code generation.
404
+
405
+ Explanation
406
+ ===========
407
+
408
+ As zeroth-order activation dynamics simply maps excitation to
409
+ activation, this class has no associated constants and so this property
410
+ return an empty column ``Matrix`` with shape (0, 1).
411
+
412
+ The alias ``p`` can also be used to access the same attribute.
413
+
414
+ """
415
+ return zeros(0, 1)
416
+
417
+ @property
418
+ def p(self):
419
+ """Ordered column matrix of non-time varying symbols present in ``M``
420
+ and ``F``.
421
+
422
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
423
+ has been used instead of ``Symbol`` for a constant then that attribute
424
+ will not be included in the matrix returned by this property. This is
425
+ because the primary use of this property attribute is to provide an
426
+ ordered sequence of the still-free symbols that require numeric values
427
+ during code generation.
428
+
429
+ Explanation
430
+ ===========
431
+
432
+ As zeroth-order activation dynamics simply maps excitation to
433
+ activation, this class has no associated constants and so this property
434
+ return an empty column ``Matrix`` with shape (0, 1).
435
+
436
+ The alias ``constants`` can also be used to access the same attribute.
437
+
438
+ """
439
+ return zeros(0, 1)
440
+
441
+ @property
442
+ def M(self):
443
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
444
+
445
+ Explanation
446
+ ===========
447
+
448
+ The square matrix that forms part of the LHS of the linear system of
449
+ ordinary differential equations governing the activation dynamics:
450
+
451
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
452
+
453
+ As zeroth-order activation dynamics have no state variables, this
454
+ linear system has dimension 0 and therefore ``M`` is an empty square
455
+ ``Matrix`` with shape (0, 0).
456
+
457
+ """
458
+ return Matrix([])
459
+
460
+ @property
461
+ def F(self):
462
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
463
+
464
+ Explanation
465
+ ===========
466
+
467
+ The column matrix that forms the RHS of the linear system of ordinary
468
+ differential equations governing the activation dynamics:
469
+
470
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
471
+
472
+ As zeroth-order activation dynamics have no state variables, this
473
+ linear system has dimension 0 and therefore ``F`` is an empty column
474
+ ``Matrix`` with shape (0, 1).
475
+
476
+ """
477
+ return zeros(0, 1)
478
+
479
+ def rhs(self):
480
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
481
+
482
+ Explanation
483
+ ===========
484
+
485
+ The solution to the linear system of ordinary differential equations
486
+ governing the activation dynamics:
487
+
488
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
489
+
490
+ As zeroth-order activation dynamics have no state variables, this
491
+ linear has dimension 0 and therefore this method returns an empty
492
+ column ``Matrix`` with shape (0, 1).
493
+
494
+ """
495
+ return zeros(0, 1)
496
+
497
+
498
+ class FirstOrderActivationDeGroote2016(ActivationBase):
499
+ r"""First-order activation dynamics based on De Groote et al., 2016 [1]_.
500
+
501
+ Explanation
502
+ ===========
503
+
504
+ Gives the first-order activation dynamics equation for the rate of change
505
+ of activation with respect to time as a function of excitation and
506
+ activation.
507
+
508
+ The function is defined by the equation:
509
+
510
+ .. math::
511
+
512
+ \frac{da}{dt} = \left(\frac{\frac{1}{2} + a0}{\tau_a \left(\frac{1}{2}
513
+ + \frac{3a}{2}\right)} + \frac{\left(\frac{1}{2}
514
+ + \frac{3a}{2}\right) \left(\frac{1}{2} - a0\right)}{\tau_d}\right)
515
+ \left(e - a\right)
516
+
517
+ where
518
+
519
+ .. math::
520
+
521
+ a0 = \frac{\tanh{\left(b \left(e - a\right) \right)}}{2}
522
+
523
+ with constant values of :math:`tau_a = 0.015`, :math:`tau_d = 0.060`, and
524
+ :math:`b = 10`.
525
+
526
+ References
527
+ ==========
528
+
529
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
530
+ of direct collocation optimal control problem formulations for
531
+ solving the muscle redundancy problem, Annals of biomedical
532
+ engineering, 44(10), (2016) pp. 2922-2936
533
+
534
+ """
535
+
536
+ def __init__(self,
537
+ name,
538
+ activation_time_constant=None,
539
+ deactivation_time_constant=None,
540
+ smoothing_rate=None,
541
+ ):
542
+ """Initializer for ``FirstOrderActivationDeGroote2016``.
543
+
544
+ Parameters
545
+ ==========
546
+ activation time constant : Symbol | Number | None
547
+ The value of the activation time constant governing the delay
548
+ between excitation and activation when excitation exceeds
549
+ activation.
550
+ deactivation time constant : Symbol | Number | None
551
+ The value of the deactivation time constant governing the delay
552
+ between excitation and activation when activation exceeds
553
+ excitation.
554
+ smoothing_rate : Symbol | Number | None
555
+ The slope of the hyperbolic tangent function used to smooth between
556
+ the switching of the equations where excitation exceed activation
557
+ and where activation exceeds excitation. The recommended value to
558
+ use is ``10``, but values between ``0.1`` and ``100`` can be used.
559
+
560
+ """
561
+ super().__init__(name)
562
+
563
+ # Symbols
564
+ self.activation_time_constant = activation_time_constant
565
+ self.deactivation_time_constant = deactivation_time_constant
566
+ self.smoothing_rate = smoothing_rate
567
+
568
+ @classmethod
569
+ def with_defaults(cls, name):
570
+ r"""Alternate constructor that will use the published constants.
571
+
572
+ Explanation
573
+ ===========
574
+
575
+ Returns an instance of ``FirstOrderActivationDeGroote2016`` using the
576
+ three constant values specified in the original publication.
577
+
578
+ These have the values:
579
+
580
+ :math:`tau_a = 0.015`
581
+ :math:`tau_d = 0.060`
582
+ :math:`b = 10`
583
+
584
+ """
585
+ tau_a = Float('0.015')
586
+ tau_d = Float('0.060')
587
+ b = Float('10.0')
588
+ return cls(name, tau_a, tau_d, b)
589
+
590
+ @property
591
+ def activation_time_constant(self):
592
+ """Delay constant for activation.
593
+
594
+ Explanation
595
+ ===========
596
+
597
+ The alias ```tau_a`` can also be used to access the same attribute.
598
+
599
+ """
600
+ return self._tau_a
601
+
602
+ @activation_time_constant.setter
603
+ def activation_time_constant(self, tau_a):
604
+ if hasattr(self, '_tau_a'):
605
+ msg = (
606
+ f'Can\'t set attribute `activation_time_constant` to '
607
+ f'{repr(tau_a)} as it is immutable and already has value '
608
+ f'{self._tau_a}.'
609
+ )
610
+ raise AttributeError(msg)
611
+ self._tau_a = Symbol(f'tau_a_{self.name}') if tau_a is None else tau_a
612
+
613
+ @property
614
+ def tau_a(self):
615
+ """Delay constant for activation.
616
+
617
+ Explanation
618
+ ===========
619
+
620
+ The alias ``activation_time_constant`` can also be used to access the
621
+ same attribute.
622
+
623
+ """
624
+ return self._tau_a
625
+
626
+ @property
627
+ def deactivation_time_constant(self):
628
+ """Delay constant for deactivation.
629
+
630
+ Explanation
631
+ ===========
632
+
633
+ The alias ``tau_d`` can also be used to access the same attribute.
634
+
635
+ """
636
+ return self._tau_d
637
+
638
+ @deactivation_time_constant.setter
639
+ def deactivation_time_constant(self, tau_d):
640
+ if hasattr(self, '_tau_d'):
641
+ msg = (
642
+ f'Can\'t set attribute `deactivation_time_constant` to '
643
+ f'{repr(tau_d)} as it is immutable and already has value '
644
+ f'{self._tau_d}.'
645
+ )
646
+ raise AttributeError(msg)
647
+ self._tau_d = Symbol(f'tau_d_{self.name}') if tau_d is None else tau_d
648
+
649
+ @property
650
+ def tau_d(self):
651
+ """Delay constant for deactivation.
652
+
653
+ Explanation
654
+ ===========
655
+
656
+ The alias ``deactivation_time_constant`` can also be used to access the
657
+ same attribute.
658
+
659
+ """
660
+ return self._tau_d
661
+
662
+ @property
663
+ def smoothing_rate(self):
664
+ """Smoothing constant for the hyperbolic tangent term.
665
+
666
+ Explanation
667
+ ===========
668
+
669
+ The alias ``b`` can also be used to access the same attribute.
670
+
671
+ """
672
+ return self._b
673
+
674
+ @smoothing_rate.setter
675
+ def smoothing_rate(self, b):
676
+ if hasattr(self, '_b'):
677
+ msg = (
678
+ f'Can\'t set attribute `smoothing_rate` to {b!r} as it is '
679
+ f'immutable and already has value {self._b!r}.'
680
+ )
681
+ raise AttributeError(msg)
682
+ self._b = Symbol(f'b_{self.name}') if b is None else b
683
+
684
+ @property
685
+ def b(self):
686
+ """Smoothing constant for the hyperbolic tangent term.
687
+
688
+ Explanation
689
+ ===========
690
+
691
+ The alias ``smoothing_rate`` can also be used to access the same
692
+ attribute.
693
+
694
+ """
695
+ return self._b
696
+
697
+ @property
698
+ def order(self):
699
+ """Order of the (differential) equation governing activation."""
700
+ return 1
701
+
702
+ @property
703
+ def state_vars(self):
704
+ """Ordered column matrix of functions of time that represent the state
705
+ variables.
706
+
707
+ Explanation
708
+ ===========
709
+
710
+ The alias ``x`` can also be used to access the same attribute.
711
+
712
+ """
713
+ return Matrix([self._a])
714
+
715
+ @property
716
+ def x(self):
717
+ """Ordered column matrix of functions of time that represent the state
718
+ variables.
719
+
720
+ Explanation
721
+ ===========
722
+
723
+ The alias ``state_vars`` can also be used to access the same attribute.
724
+
725
+ """
726
+ return Matrix([self._a])
727
+
728
+ @property
729
+ def input_vars(self):
730
+ """Ordered column matrix of functions of time that represent the input
731
+ variables.
732
+
733
+ Explanation
734
+ ===========
735
+
736
+ The alias ``r`` can also be used to access the same attribute.
737
+
738
+ """
739
+ return Matrix([self._e])
740
+
741
+ @property
742
+ def r(self):
743
+ """Ordered column matrix of functions of time that represent the input
744
+ variables.
745
+
746
+ Explanation
747
+ ===========
748
+
749
+ The alias ``input_vars`` can also be used to access the same attribute.
750
+
751
+ """
752
+ return Matrix([self._e])
753
+
754
+ @property
755
+ def constants(self):
756
+ """Ordered column matrix of non-time varying symbols present in ``M``
757
+ and ``F``.
758
+
759
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
760
+ has been used instead of ``Symbol`` for a constant then that attribute
761
+ will not be included in the matrix returned by this property. This is
762
+ because the primary use of this property attribute is to provide an
763
+ ordered sequence of the still-free symbols that require numeric values
764
+ during code generation.
765
+
766
+ Explanation
767
+ ===========
768
+
769
+ The alias ``p`` can also be used to access the same attribute.
770
+
771
+ """
772
+ constants = [self._tau_a, self._tau_d, self._b]
773
+ symbolic_constants = [c for c in constants if not c.is_number]
774
+ return Matrix(symbolic_constants) if symbolic_constants else zeros(0, 1)
775
+
776
+ @property
777
+ def p(self):
778
+ """Ordered column matrix of non-time varying symbols present in ``M``
779
+ and ``F``.
780
+
781
+ Explanation
782
+ ===========
783
+
784
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
785
+ has been used instead of ``Symbol`` for a constant then that attribute
786
+ will not be included in the matrix returned by this property. This is
787
+ because the primary use of this property attribute is to provide an
788
+ ordered sequence of the still-free symbols that require numeric values
789
+ during code generation.
790
+
791
+ The alias ``constants`` can also be used to access the same attribute.
792
+
793
+ """
794
+ constants = [self._tau_a, self._tau_d, self._b]
795
+ symbolic_constants = [c for c in constants if not c.is_number]
796
+ return Matrix(symbolic_constants) if symbolic_constants else zeros(0, 1)
797
+
798
+ @property
799
+ def M(self):
800
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
801
+
802
+ Explanation
803
+ ===========
804
+
805
+ The square matrix that forms part of the LHS of the linear system of
806
+ ordinary differential equations governing the activation dynamics:
807
+
808
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
809
+
810
+ """
811
+ return Matrix([Integer(1)])
812
+
813
+ @property
814
+ def F(self):
815
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
816
+
817
+ Explanation
818
+ ===========
819
+
820
+ The column matrix that forms the RHS of the linear system of ordinary
821
+ differential equations governing the activation dynamics:
822
+
823
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
824
+
825
+ """
826
+ return Matrix([self._da_eqn])
827
+
828
+ def rhs(self):
829
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
830
+
831
+ Explanation
832
+ ===========
833
+
834
+ The solution to the linear system of ordinary differential equations
835
+ governing the activation dynamics:
836
+
837
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
838
+
839
+ """
840
+ return Matrix([self._da_eqn])
841
+
842
+ @cached_property
843
+ def _da_eqn(self):
844
+ HALF = Rational(1, 2)
845
+ a0 = HALF * tanh(self._b * (self._e - self._a))
846
+ a1 = (HALF + Rational(3, 2) * self._a)
847
+ a2 = (HALF + a0) / (self._tau_a * a1)
848
+ a3 = a1 * (HALF - a0) / self._tau_d
849
+ activation_dynamics_equation = (a2 + a3) * (self._e - self._a)
850
+ return activation_dynamics_equation
851
+
852
+ def __eq__(self, other):
853
+ """Equality check for ``FirstOrderActivationDeGroote2016``."""
854
+ if type(self) != type(other):
855
+ return False
856
+ self_attrs = (self.name, self.tau_a, self.tau_d, self.b)
857
+ other_attrs = (other.name, other.tau_a, other.tau_d, other.b)
858
+ if self_attrs == other_attrs:
859
+ return True
860
+ return False
861
+
862
+ def __repr__(self):
863
+ """Representation of ``FirstOrderActivationDeGroote2016``."""
864
+ return (
865
+ f'{self.__class__.__name__}({self.name!r}, '
866
+ f'activation_time_constant={self.tau_a!r}, '
867
+ f'deactivation_time_constant={self.tau_d!r}, '
868
+ f'smoothing_rate={self.b!r})'
869
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/curve.py ADDED
@@ -0,0 +1,1763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of characteristic curves for musculotendon models."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from sympy.core.expr import UnevaluatedExpr
6
+ from sympy.core.function import ArgumentIndexError, Function
7
+ from sympy.core.numbers import Float, Integer
8
+ from sympy.functions.elementary.exponential import exp, log
9
+ from sympy.functions.elementary.hyperbolic import cosh, sinh
10
+ from sympy.functions.elementary.miscellaneous import sqrt
11
+ from sympy.printing.precedence import PRECEDENCE
12
+
13
+
14
+ __all__ = [
15
+ 'CharacteristicCurveCollection',
16
+ 'CharacteristicCurveFunction',
17
+ 'FiberForceLengthActiveDeGroote2016',
18
+ 'FiberForceLengthPassiveDeGroote2016',
19
+ 'FiberForceLengthPassiveInverseDeGroote2016',
20
+ 'FiberForceVelocityDeGroote2016',
21
+ 'FiberForceVelocityInverseDeGroote2016',
22
+ 'TendonForceLengthDeGroote2016',
23
+ 'TendonForceLengthInverseDeGroote2016',
24
+ ]
25
+
26
+
27
+ class CharacteristicCurveFunction(Function):
28
+ """Base class for all musculotendon characteristic curve functions."""
29
+
30
+ @classmethod
31
+ def eval(cls):
32
+ msg = (
33
+ f'Cannot directly instantiate {cls.__name__!r}, instances of '
34
+ f'characteristic curves must be of a concrete subclass.'
35
+
36
+ )
37
+ raise TypeError(msg)
38
+
39
+ def _print_code(self, printer):
40
+ """Print code for the function defining the curve using a printer.
41
+
42
+ Explanation
43
+ ===========
44
+
45
+ The order of operations may need to be controlled as constant folding
46
+ the numeric terms within the equations of a musculotendon
47
+ characteristic curve can sometimes results in a numerically-unstable
48
+ expression.
49
+
50
+ Parameters
51
+ ==========
52
+
53
+ printer : Printer
54
+ The printer to be used to print a string representation of the
55
+ characteristic curve as valid code in the target language.
56
+
57
+ """
58
+ return printer._print(printer.parenthesize(
59
+ self.doit(deep=False, evaluate=False), PRECEDENCE['Atom'],
60
+ ))
61
+
62
+ _ccode = _print_code
63
+ _cupycode = _print_code
64
+ _cxxcode = _print_code
65
+ _fcode = _print_code
66
+ _jaxcode = _print_code
67
+ _lambdacode = _print_code
68
+ _mpmathcode = _print_code
69
+ _octave = _print_code
70
+ _pythoncode = _print_code
71
+ _numpycode = _print_code
72
+ _scipycode = _print_code
73
+
74
+
75
+ class TendonForceLengthDeGroote2016(CharacteristicCurveFunction):
76
+ r"""Tendon force-length curve based on De Groote et al., 2016 [1]_.
77
+
78
+ Explanation
79
+ ===========
80
+
81
+ Gives the normalized tendon force produced as a function of normalized
82
+ tendon length.
83
+
84
+ The function is defined by the equation:
85
+
86
+ $fl^T = c_0 \exp{c_3 \left( \tilde{l}^T - c_1 \right)} - c_2$
87
+
88
+ with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
89
+ $c_3 = 33.93669377311689$.
90
+
91
+ While it is possible to change the constant values, these were carefully
92
+ selected in the original publication to give the characteristic curve
93
+ specific and required properties. For example, the function produces no
94
+ force when the tendon is in an unstrained state. It also produces a force
95
+ of 1 normalized unit when the tendon is under a 5% strain.
96
+
97
+ Examples
98
+ ========
99
+
100
+ The preferred way to instantiate :class:`TendonForceLengthDeGroote2016` is using
101
+ the :meth:`~.with_defaults` constructor because this will automatically
102
+ populate the constants within the characteristic curve equation with the
103
+ floating point values from the original publication. This constructor takes
104
+ a single argument corresponding to normalized tendon length. We'll create a
105
+ :class:`~.Symbol` called ``l_T_tilde`` to represent this.
106
+
107
+ >>> from sympy import Symbol
108
+ >>> from sympy.physics.biomechanics import TendonForceLengthDeGroote2016
109
+ >>> l_T_tilde = Symbol('l_T_tilde')
110
+ >>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
111
+ >>> fl_T
112
+ TendonForceLengthDeGroote2016(l_T_tilde, 0.2, 0.995, 0.25,
113
+ 33.93669377311689)
114
+
115
+ It's also possible to populate the four constants with your own values too.
116
+
117
+ >>> from sympy import symbols
118
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
119
+ >>> fl_T = TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
120
+ >>> fl_T
121
+ TendonForceLengthDeGroote2016(l_T_tilde, c0, c1, c2, c3)
122
+
123
+ You don't just have to use symbols as the arguments, it's also possible to
124
+ use expressions. Let's create a new pair of symbols, ``l_T`` and
125
+ ``l_T_slack``, representing tendon length and tendon slack length
126
+ respectively. We can then represent ``l_T_tilde`` as an expression, the
127
+ ratio of these.
128
+
129
+ >>> l_T, l_T_slack = symbols('l_T l_T_slack')
130
+ >>> l_T_tilde = l_T/l_T_slack
131
+ >>> fl_T = TendonForceLengthDeGroote2016.with_defaults(l_T_tilde)
132
+ >>> fl_T
133
+ TendonForceLengthDeGroote2016(l_T/l_T_slack, 0.2, 0.995, 0.25,
134
+ 33.93669377311689)
135
+
136
+ To inspect the actual symbolic expression that this function represents,
137
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
138
+ argument ``evaluate=False`` as this will keep the expression in its
139
+ canonical form and won't simplify any constants.
140
+
141
+ >>> fl_T.doit(evaluate=False)
142
+ -0.25 + 0.2*exp(33.93669377311689*(l_T/l_T_slack - 0.995))
143
+
144
+ The function can also be differentiated. We'll differentiate with respect
145
+ to l_T using the ``diff`` method on an instance with the single positional
146
+ argument ``l_T``.
147
+
148
+ >>> fl_T.diff(l_T)
149
+ 6.787338754623378*exp(33.93669377311689*(l_T/l_T_slack - 0.995))/l_T_slack
150
+
151
+ References
152
+ ==========
153
+
154
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
155
+ of direct collocation optimal control problem formulations for
156
+ solving the muscle redundancy problem, Annals of biomedical
157
+ engineering, 44(10), (2016) pp. 2922-2936
158
+
159
+ """
160
+
161
+ @classmethod
162
+ def with_defaults(cls, l_T_tilde):
163
+ r"""Recommended constructor that will use the published constants.
164
+
165
+ Explanation
166
+ ===========
167
+
168
+ Returns a new instance of the tendon force-length function using the
169
+ four constant values specified in the original publication.
170
+
171
+ These have the values:
172
+
173
+ $c_0 = 0.2$
174
+ $c_1 = 0.995$
175
+ $c_2 = 0.25$
176
+ $c_3 = 33.93669377311689$
177
+
178
+ Parameters
179
+ ==========
180
+
181
+ l_T_tilde : Any (sympifiable)
182
+ Normalized tendon length.
183
+
184
+ """
185
+ c0 = Float('0.2')
186
+ c1 = Float('0.995')
187
+ c2 = Float('0.25')
188
+ c3 = Float('33.93669377311689')
189
+ return cls(l_T_tilde, c0, c1, c2, c3)
190
+
191
+ @classmethod
192
+ def eval(cls, l_T_tilde, c0, c1, c2, c3):
193
+ """Evaluation of basic inputs.
194
+
195
+ Parameters
196
+ ==========
197
+
198
+ l_T_tilde : Any (sympifiable)
199
+ Normalized tendon length.
200
+ c0 : Any (sympifiable)
201
+ The first constant in the characteristic equation. The published
202
+ value is ``0.2``.
203
+ c1 : Any (sympifiable)
204
+ The second constant in the characteristic equation. The published
205
+ value is ``0.995``.
206
+ c2 : Any (sympifiable)
207
+ The third constant in the characteristic equation. The published
208
+ value is ``0.25``.
209
+ c3 : Any (sympifiable)
210
+ The fourth constant in the characteristic equation. The published
211
+ value is ``33.93669377311689``.
212
+
213
+ """
214
+ pass
215
+
216
+ def _eval_evalf(self, prec):
217
+ """Evaluate the expression numerically using ``evalf``."""
218
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
219
+
220
+ def doit(self, deep=True, evaluate=True, **hints):
221
+ """Evaluate the expression defining the function.
222
+
223
+ Parameters
224
+ ==========
225
+
226
+ deep : bool
227
+ Whether ``doit`` should be recursively called. Default is ``True``.
228
+ evaluate : bool.
229
+ Whether the SymPy expression should be evaluated as it is
230
+ constructed. If ``False``, then no constant folding will be
231
+ conducted which will leave the expression in a more numerically-
232
+ stable for values of ``l_T_tilde`` that correspond to a sensible
233
+ operating range for a musculotendon. Default is ``True``.
234
+ **kwargs : dict[str, Any]
235
+ Additional keyword argument pairs to be recursively passed to
236
+ ``doit``.
237
+
238
+ """
239
+ l_T_tilde, *constants = self.args
240
+ if deep:
241
+ hints['evaluate'] = evaluate
242
+ l_T_tilde = l_T_tilde.doit(deep=deep, **hints)
243
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
244
+ else:
245
+ c0, c1, c2, c3 = constants
246
+
247
+ if evaluate:
248
+ return c0*exp(c3*(l_T_tilde - c1)) - c2
249
+
250
+ return c0*exp(c3*UnevaluatedExpr(l_T_tilde - c1)) - c2
251
+
252
+ def fdiff(self, argindex=1):
253
+ """Derivative of the function with respect to a single argument.
254
+
255
+ Parameters
256
+ ==========
257
+
258
+ argindex : int
259
+ The index of the function's arguments with respect to which the
260
+ derivative should be taken. Argument indexes start at ``1``.
261
+ Default is ``1``.
262
+
263
+ """
264
+ l_T_tilde, c0, c1, c2, c3 = self.args
265
+ if argindex == 1:
266
+ return c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
267
+ elif argindex == 2:
268
+ return exp(c3*UnevaluatedExpr(l_T_tilde - c1))
269
+ elif argindex == 3:
270
+ return -c0*c3*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
271
+ elif argindex == 4:
272
+ return Integer(-1)
273
+ elif argindex == 5:
274
+ return c0*(l_T_tilde - c1)*exp(c3*UnevaluatedExpr(l_T_tilde - c1))
275
+
276
+ raise ArgumentIndexError(self, argindex)
277
+
278
+ def inverse(self, argindex=1):
279
+ """Inverse function.
280
+
281
+ Parameters
282
+ ==========
283
+
284
+ argindex : int
285
+ Value to start indexing the arguments at. Default is ``1``.
286
+
287
+ """
288
+ return TendonForceLengthInverseDeGroote2016
289
+
290
+ def _latex(self, printer):
291
+ """Print a LaTeX representation of the function defining the curve.
292
+
293
+ Parameters
294
+ ==========
295
+
296
+ printer : Printer
297
+ The printer to be used to print the LaTeX string representation.
298
+
299
+ """
300
+ l_T_tilde = self.args[0]
301
+ _l_T_tilde = printer._print(l_T_tilde)
302
+ return r'\operatorname{fl}^T \left( %s \right)' % _l_T_tilde
303
+
304
+
305
+ class TendonForceLengthInverseDeGroote2016(CharacteristicCurveFunction):
306
+ r"""Inverse tendon force-length curve based on De Groote et al., 2016 [1]_.
307
+
308
+ Explanation
309
+ ===========
310
+
311
+ Gives the normalized tendon length that produces a specific normalized
312
+ tendon force.
313
+
314
+ The function is defined by the equation:
315
+
316
+ ${fl^T}^{-1} = frac{\log{\frac{fl^T + c_2}{c_0}}}{c_3} + c_1$
317
+
318
+ with constant values of $c_0 = 0.2$, $c_1 = 0.995$, $c_2 = 0.25$, and
319
+ $c_3 = 33.93669377311689$. This function is the exact analytical inverse
320
+ of the related tendon force-length curve ``TendonForceLengthDeGroote2016``.
321
+
322
+ While it is possible to change the constant values, these were carefully
323
+ selected in the original publication to give the characteristic curve
324
+ specific and required properties. For example, the function produces no
325
+ force when the tendon is in an unstrained state. It also produces a force
326
+ of 1 normalized unit when the tendon is under a 5% strain.
327
+
328
+ Examples
329
+ ========
330
+
331
+ The preferred way to instantiate :class:`TendonForceLengthInverseDeGroote2016` is
332
+ using the :meth:`~.with_defaults` constructor because this will automatically
333
+ populate the constants within the characteristic curve equation with the
334
+ floating point values from the original publication. This constructor takes
335
+ a single argument corresponding to normalized tendon force-length, which is
336
+ equal to the tendon force. We'll create a :class:`~.Symbol` called ``fl_T`` to
337
+ represent this.
338
+
339
+ >>> from sympy import Symbol
340
+ >>> from sympy.physics.biomechanics import TendonForceLengthInverseDeGroote2016
341
+ >>> fl_T = Symbol('fl_T')
342
+ >>> l_T_tilde = TendonForceLengthInverseDeGroote2016.with_defaults(fl_T)
343
+ >>> l_T_tilde
344
+ TendonForceLengthInverseDeGroote2016(fl_T, 0.2, 0.995, 0.25,
345
+ 33.93669377311689)
346
+
347
+ It's also possible to populate the four constants with your own values too.
348
+
349
+ >>> from sympy import symbols
350
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
351
+ >>> l_T_tilde = TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
352
+ >>> l_T_tilde
353
+ TendonForceLengthInverseDeGroote2016(fl_T, c0, c1, c2, c3)
354
+
355
+ To inspect the actual symbolic expression that this function represents,
356
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
357
+ argument ``evaluate=False`` as this will keep the expression in its
358
+ canonical form and won't simplify any constants.
359
+
360
+ >>> l_T_tilde.doit(evaluate=False)
361
+ c1 + log((c2 + fl_T)/c0)/c3
362
+
363
+ The function can also be differentiated. We'll differentiate with respect
364
+ to l_T using the ``diff`` method on an instance with the single positional
365
+ argument ``l_T``.
366
+
367
+ >>> l_T_tilde.diff(fl_T)
368
+ 1/(c3*(c2 + fl_T))
369
+
370
+ References
371
+ ==========
372
+
373
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
374
+ of direct collocation optimal control problem formulations for
375
+ solving the muscle redundancy problem, Annals of biomedical
376
+ engineering, 44(10), (2016) pp. 2922-2936
377
+
378
+ """
379
+
380
+ @classmethod
381
+ def with_defaults(cls, fl_T):
382
+ r"""Recommended constructor that will use the published constants.
383
+
384
+ Explanation
385
+ ===========
386
+
387
+ Returns a new instance of the inverse tendon force-length function
388
+ using the four constant values specified in the original publication.
389
+
390
+ These have the values:
391
+
392
+ $c_0 = 0.2$
393
+ $c_1 = 0.995$
394
+ $c_2 = 0.25$
395
+ $c_3 = 33.93669377311689$
396
+
397
+ Parameters
398
+ ==========
399
+
400
+ fl_T : Any (sympifiable)
401
+ Normalized tendon force as a function of tendon length.
402
+
403
+ """
404
+ c0 = Float('0.2')
405
+ c1 = Float('0.995')
406
+ c2 = Float('0.25')
407
+ c3 = Float('33.93669377311689')
408
+ return cls(fl_T, c0, c1, c2, c3)
409
+
410
+ @classmethod
411
+ def eval(cls, fl_T, c0, c1, c2, c3):
412
+ """Evaluation of basic inputs.
413
+
414
+ Parameters
415
+ ==========
416
+
417
+ fl_T : Any (sympifiable)
418
+ Normalized tendon force as a function of tendon length.
419
+ c0 : Any (sympifiable)
420
+ The first constant in the characteristic equation. The published
421
+ value is ``0.2``.
422
+ c1 : Any (sympifiable)
423
+ The second constant in the characteristic equation. The published
424
+ value is ``0.995``.
425
+ c2 : Any (sympifiable)
426
+ The third constant in the characteristic equation. The published
427
+ value is ``0.25``.
428
+ c3 : Any (sympifiable)
429
+ The fourth constant in the characteristic equation. The published
430
+ value is ``33.93669377311689``.
431
+
432
+ """
433
+ pass
434
+
435
+ def _eval_evalf(self, prec):
436
+ """Evaluate the expression numerically using ``evalf``."""
437
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
438
+
439
+ def doit(self, deep=True, evaluate=True, **hints):
440
+ """Evaluate the expression defining the function.
441
+
442
+ Parameters
443
+ ==========
444
+
445
+ deep : bool
446
+ Whether ``doit`` should be recursively called. Default is ``True``.
447
+ evaluate : bool.
448
+ Whether the SymPy expression should be evaluated as it is
449
+ constructed. If ``False``, then no constant folding will be
450
+ conducted which will leave the expression in a more numerically-
451
+ stable for values of ``l_T_tilde`` that correspond to a sensible
452
+ operating range for a musculotendon. Default is ``True``.
453
+ **kwargs : dict[str, Any]
454
+ Additional keyword argument pairs to be recursively passed to
455
+ ``doit``.
456
+
457
+ """
458
+ fl_T, *constants = self.args
459
+ if deep:
460
+ hints['evaluate'] = evaluate
461
+ fl_T = fl_T.doit(deep=deep, **hints)
462
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
463
+ else:
464
+ c0, c1, c2, c3 = constants
465
+
466
+ if evaluate:
467
+ return log((fl_T + c2)/c0)/c3 + c1
468
+
469
+ return log(UnevaluatedExpr((fl_T + c2)/c0))/c3 + c1
470
+
471
+ def fdiff(self, argindex=1):
472
+ """Derivative of the function with respect to a single argument.
473
+
474
+ Parameters
475
+ ==========
476
+
477
+ argindex : int
478
+ The index of the function's arguments with respect to which the
479
+ derivative should be taken. Argument indexes start at ``1``.
480
+ Default is ``1``.
481
+
482
+ """
483
+ fl_T, c0, c1, c2, c3 = self.args
484
+ if argindex == 1:
485
+ return 1/(c3*(fl_T + c2))
486
+ elif argindex == 2:
487
+ return -1/(c0*c3)
488
+ elif argindex == 3:
489
+ return Integer(1)
490
+ elif argindex == 4:
491
+ return 1/(c3*(fl_T + c2))
492
+ elif argindex == 5:
493
+ return -log(UnevaluatedExpr((fl_T + c2)/c0))/c3**2
494
+
495
+ raise ArgumentIndexError(self, argindex)
496
+
497
+ def inverse(self, argindex=1):
498
+ """Inverse function.
499
+
500
+ Parameters
501
+ ==========
502
+
503
+ argindex : int
504
+ Value to start indexing the arguments at. Default is ``1``.
505
+
506
+ """
507
+ return TendonForceLengthDeGroote2016
508
+
509
+ def _latex(self, printer):
510
+ """Print a LaTeX representation of the function defining the curve.
511
+
512
+ Parameters
513
+ ==========
514
+
515
+ printer : Printer
516
+ The printer to be used to print the LaTeX string representation.
517
+
518
+ """
519
+ fl_T = self.args[0]
520
+ _fl_T = printer._print(fl_T)
521
+ return r'\left( \operatorname{fl}^T \right)^{-1} \left( %s \right)' % _fl_T
522
+
523
+
524
+ class FiberForceLengthPassiveDeGroote2016(CharacteristicCurveFunction):
525
+ r"""Passive muscle fiber force-length curve based on De Groote et al., 2016
526
+ [1]_.
527
+
528
+ Explanation
529
+ ===========
530
+
531
+ The function is defined by the equation:
532
+
533
+ $fl^M_{pas} = \frac{\frac{\exp{c_1 \left(\tilde{l^M} - 1\right)}}{c_0} - 1}{\exp{c_1} - 1}$
534
+
535
+ with constant values of $c_0 = 0.6$ and $c_1 = 4.0$.
536
+
537
+ While it is possible to change the constant values, these were carefully
538
+ selected in the original publication to give the characteristic curve
539
+ specific and required properties. For example, the function produces a
540
+ passive fiber force very close to 0 for all normalized fiber lengths
541
+ between 0 and 1.
542
+
543
+ Examples
544
+ ========
545
+
546
+ The preferred way to instantiate :class:`FiberForceLengthPassiveDeGroote2016` is
547
+ using the :meth:`~.with_defaults` constructor because this will automatically
548
+ populate the constants within the characteristic curve equation with the
549
+ floating point values from the original publication. This constructor takes
550
+ a single argument corresponding to normalized muscle fiber length. We'll
551
+ create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
552
+
553
+ >>> from sympy import Symbol
554
+ >>> from sympy.physics.biomechanics import FiberForceLengthPassiveDeGroote2016
555
+ >>> l_M_tilde = Symbol('l_M_tilde')
556
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
557
+ >>> fl_M
558
+ FiberForceLengthPassiveDeGroote2016(l_M_tilde, 0.6, 4.0)
559
+
560
+ It's also possible to populate the two constants with your own values too.
561
+
562
+ >>> from sympy import symbols
563
+ >>> c0, c1 = symbols('c0 c1')
564
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
565
+ >>> fl_M
566
+ FiberForceLengthPassiveDeGroote2016(l_M_tilde, c0, c1)
567
+
568
+ You don't just have to use symbols as the arguments, it's also possible to
569
+ use expressions. Let's create a new pair of symbols, ``l_M`` and
570
+ ``l_M_opt``, representing muscle fiber length and optimal muscle fiber
571
+ length respectively. We can then represent ``l_M_tilde`` as an expression,
572
+ the ratio of these.
573
+
574
+ >>> l_M, l_M_opt = symbols('l_M l_M_opt')
575
+ >>> l_M_tilde = l_M/l_M_opt
576
+ >>> fl_M = FiberForceLengthPassiveDeGroote2016.with_defaults(l_M_tilde)
577
+ >>> fl_M
578
+ FiberForceLengthPassiveDeGroote2016(l_M/l_M_opt, 0.6, 4.0)
579
+
580
+ To inspect the actual symbolic expression that this function represents,
581
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
582
+ argument ``evaluate=False`` as this will keep the expression in its
583
+ canonical form and won't simplify any constants.
584
+
585
+ >>> fl_M.doit(evaluate=False)
586
+ 0.0186573603637741*(-1 + exp(6.66666666666667*(l_M/l_M_opt - 1)))
587
+
588
+ The function can also be differentiated. We'll differentiate with respect
589
+ to l_M using the ``diff`` method on an instance with the single positional
590
+ argument ``l_M``.
591
+
592
+ >>> fl_M.diff(l_M)
593
+ 0.12438240242516*exp(6.66666666666667*(l_M/l_M_opt - 1))/l_M_opt
594
+
595
+ References
596
+ ==========
597
+
598
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
599
+ of direct collocation optimal control problem formulations for
600
+ solving the muscle redundancy problem, Annals of biomedical
601
+ engineering, 44(10), (2016) pp. 2922-2936
602
+
603
+ """
604
+
605
+ @classmethod
606
+ def with_defaults(cls, l_M_tilde):
607
+ r"""Recommended constructor that will use the published constants.
608
+
609
+ Explanation
610
+ ===========
611
+
612
+ Returns a new instance of the muscle fiber passive force-length
613
+ function using the four constant values specified in the original
614
+ publication.
615
+
616
+ These have the values:
617
+
618
+ $c_0 = 0.6$
619
+ $c_1 = 4.0$
620
+
621
+ Parameters
622
+ ==========
623
+
624
+ l_M_tilde : Any (sympifiable)
625
+ Normalized muscle fiber length.
626
+
627
+ """
628
+ c0 = Float('0.6')
629
+ c1 = Float('4.0')
630
+ return cls(l_M_tilde, c0, c1)
631
+
632
+ @classmethod
633
+ def eval(cls, l_M_tilde, c0, c1):
634
+ """Evaluation of basic inputs.
635
+
636
+ Parameters
637
+ ==========
638
+
639
+ l_M_tilde : Any (sympifiable)
640
+ Normalized muscle fiber length.
641
+ c0 : Any (sympifiable)
642
+ The first constant in the characteristic equation. The published
643
+ value is ``0.6``.
644
+ c1 : Any (sympifiable)
645
+ The second constant in the characteristic equation. The published
646
+ value is ``4.0``.
647
+
648
+ """
649
+ pass
650
+
651
+ def _eval_evalf(self, prec):
652
+ """Evaluate the expression numerically using ``evalf``."""
653
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
654
+
655
+ def doit(self, deep=True, evaluate=True, **hints):
656
+ """Evaluate the expression defining the function.
657
+
658
+ Parameters
659
+ ==========
660
+
661
+ deep : bool
662
+ Whether ``doit`` should be recursively called. Default is ``True``.
663
+ evaluate : bool.
664
+ Whether the SymPy expression should be evaluated as it is
665
+ constructed. If ``False``, then no constant folding will be
666
+ conducted which will leave the expression in a more numerically-
667
+ stable for values of ``l_T_tilde`` that correspond to a sensible
668
+ operating range for a musculotendon. Default is ``True``.
669
+ **kwargs : dict[str, Any]
670
+ Additional keyword argument pairs to be recursively passed to
671
+ ``doit``.
672
+
673
+ """
674
+ l_M_tilde, *constants = self.args
675
+ if deep:
676
+ hints['evaluate'] = evaluate
677
+ l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
678
+ c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
679
+ else:
680
+ c0, c1 = constants
681
+
682
+ if evaluate:
683
+ return (exp((c1*(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
684
+
685
+ return (exp((c1*UnevaluatedExpr(l_M_tilde - 1))/c0) - 1)/(exp(c1) - 1)
686
+
687
+ def fdiff(self, argindex=1):
688
+ """Derivative of the function with respect to a single argument.
689
+
690
+ Parameters
691
+ ==========
692
+
693
+ argindex : int
694
+ The index of the function's arguments with respect to which the
695
+ derivative should be taken. Argument indexes start at ``1``.
696
+ Default is ``1``.
697
+
698
+ """
699
+ l_M_tilde, c0, c1 = self.args
700
+ if argindex == 1:
701
+ return c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)/(c0*(exp(c1) - 1))
702
+ elif argindex == 2:
703
+ return (
704
+ -c1*exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)
705
+ *UnevaluatedExpr(l_M_tilde - 1)/(c0**2*(exp(c1) - 1))
706
+ )
707
+ elif argindex == 3:
708
+ return (
709
+ -exp(c1)*(-1 + exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0))/(exp(c1) - 1)**2
710
+ + exp(c1*UnevaluatedExpr(l_M_tilde - 1)/c0)*(l_M_tilde - 1)/(c0*(exp(c1) - 1))
711
+ )
712
+
713
+ raise ArgumentIndexError(self, argindex)
714
+
715
+ def inverse(self, argindex=1):
716
+ """Inverse function.
717
+
718
+ Parameters
719
+ ==========
720
+
721
+ argindex : int
722
+ Value to start indexing the arguments at. Default is ``1``.
723
+
724
+ """
725
+ return FiberForceLengthPassiveInverseDeGroote2016
726
+
727
+ def _latex(self, printer):
728
+ """Print a LaTeX representation of the function defining the curve.
729
+
730
+ Parameters
731
+ ==========
732
+
733
+ printer : Printer
734
+ The printer to be used to print the LaTeX string representation.
735
+
736
+ """
737
+ l_M_tilde = self.args[0]
738
+ _l_M_tilde = printer._print(l_M_tilde)
739
+ return r'\operatorname{fl}^M_{pas} \left( %s \right)' % _l_M_tilde
740
+
741
+
742
+ class FiberForceLengthPassiveInverseDeGroote2016(CharacteristicCurveFunction):
743
+ r"""Inverse passive muscle fiber force-length curve based on De Groote et
744
+ al., 2016 [1]_.
745
+
746
+ Explanation
747
+ ===========
748
+
749
+ Gives the normalized muscle fiber length that produces a specific normalized
750
+ passive muscle fiber force.
751
+
752
+ The function is defined by the equation:
753
+
754
+ ${fl^M_{pas}}^{-1} = \frac{c_0 \log{\left(\exp{c_1} - 1\right)fl^M_pas + 1}}{c_1} + 1$
755
+
756
+ with constant values of $c_0 = 0.6$ and $c_1 = 4.0$. This function is the
757
+ exact analytical inverse of the related tendon force-length curve
758
+ ``FiberForceLengthPassiveDeGroote2016``.
759
+
760
+ While it is possible to change the constant values, these were carefully
761
+ selected in the original publication to give the characteristic curve
762
+ specific and required properties. For example, the function produces a
763
+ passive fiber force very close to 0 for all normalized fiber lengths
764
+ between 0 and 1.
765
+
766
+ Examples
767
+ ========
768
+
769
+ The preferred way to instantiate
770
+ :class:`FiberForceLengthPassiveInverseDeGroote2016` is using the
771
+ :meth:`~.with_defaults` constructor because this will automatically populate the
772
+ constants within the characteristic curve equation with the floating point
773
+ values from the original publication. This constructor takes a single
774
+ argument corresponding to the normalized passive muscle fiber length-force
775
+ component of the muscle fiber force. We'll create a :class:`~.Symbol` called
776
+ ``fl_M_pas`` to represent this.
777
+
778
+ >>> from sympy import Symbol
779
+ >>> from sympy.physics.biomechanics import FiberForceLengthPassiveInverseDeGroote2016
780
+ >>> fl_M_pas = Symbol('fl_M_pas')
781
+ >>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(fl_M_pas)
782
+ >>> l_M_tilde
783
+ FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, 0.6, 4.0)
784
+
785
+ It's also possible to populate the two constants with your own values too.
786
+
787
+ >>> from sympy import symbols
788
+ >>> c0, c1 = symbols('c0 c1')
789
+ >>> l_M_tilde = FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
790
+ >>> l_M_tilde
791
+ FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c0, c1)
792
+
793
+ To inspect the actual symbolic expression that this function represents,
794
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
795
+ argument ``evaluate=False`` as this will keep the expression in its
796
+ canonical form and won't simplify any constants.
797
+
798
+ >>> l_M_tilde.doit(evaluate=False)
799
+ c0*log(1 + fl_M_pas*(exp(c1) - 1))/c1 + 1
800
+
801
+ The function can also be differentiated. We'll differentiate with respect
802
+ to fl_M_pas using the ``diff`` method on an instance with the single positional
803
+ argument ``fl_M_pas``.
804
+
805
+ >>> l_M_tilde.diff(fl_M_pas)
806
+ c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
807
+
808
+ References
809
+ ==========
810
+
811
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
812
+ of direct collocation optimal control problem formulations for
813
+ solving the muscle redundancy problem, Annals of biomedical
814
+ engineering, 44(10), (2016) pp. 2922-2936
815
+
816
+ """
817
+
818
+ @classmethod
819
+ def with_defaults(cls, fl_M_pas):
820
+ r"""Recommended constructor that will use the published constants.
821
+
822
+ Explanation
823
+ ===========
824
+
825
+ Returns a new instance of the inverse muscle fiber passive force-length
826
+ function using the four constant values specified in the original
827
+ publication.
828
+
829
+ These have the values:
830
+
831
+ $c_0 = 0.6$
832
+ $c_1 = 4.0$
833
+
834
+ Parameters
835
+ ==========
836
+
837
+ fl_M_pas : Any (sympifiable)
838
+ Normalized passive muscle fiber force as a function of muscle fiber
839
+ length.
840
+
841
+ """
842
+ c0 = Float('0.6')
843
+ c1 = Float('4.0')
844
+ return cls(fl_M_pas, c0, c1)
845
+
846
+ @classmethod
847
+ def eval(cls, fl_M_pas, c0, c1):
848
+ """Evaluation of basic inputs.
849
+
850
+ Parameters
851
+ ==========
852
+
853
+ fl_M_pas : Any (sympifiable)
854
+ Normalized passive muscle fiber force.
855
+ c0 : Any (sympifiable)
856
+ The first constant in the characteristic equation. The published
857
+ value is ``0.6``.
858
+ c1 : Any (sympifiable)
859
+ The second constant in the characteristic equation. The published
860
+ value is ``4.0``.
861
+
862
+ """
863
+ pass
864
+
865
+ def _eval_evalf(self, prec):
866
+ """Evaluate the expression numerically using ``evalf``."""
867
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
868
+
869
+ def doit(self, deep=True, evaluate=True, **hints):
870
+ """Evaluate the expression defining the function.
871
+
872
+ Parameters
873
+ ==========
874
+
875
+ deep : bool
876
+ Whether ``doit`` should be recursively called. Default is ``True``.
877
+ evaluate : bool.
878
+ Whether the SymPy expression should be evaluated as it is
879
+ constructed. If ``False``, then no constant folding will be
880
+ conducted which will leave the expression in a more numerically-
881
+ stable for values of ``l_T_tilde`` that correspond to a sensible
882
+ operating range for a musculotendon. Default is ``True``.
883
+ **kwargs : dict[str, Any]
884
+ Additional keyword argument pairs to be recursively passed to
885
+ ``doit``.
886
+
887
+ """
888
+ fl_M_pas, *constants = self.args
889
+ if deep:
890
+ hints['evaluate'] = evaluate
891
+ fl_M_pas = fl_M_pas.doit(deep=deep, **hints)
892
+ c0, c1 = [c.doit(deep=deep, **hints) for c in constants]
893
+ else:
894
+ c0, c1 = constants
895
+
896
+ if evaluate:
897
+ return c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1 + 1
898
+
899
+ return c0*log(UnevaluatedExpr(fl_M_pas*(exp(c1) - 1)) + 1)/c1 + 1
900
+
901
+ def fdiff(self, argindex=1):
902
+ """Derivative of the function with respect to a single argument.
903
+
904
+ Parameters
905
+ ==========
906
+
907
+ argindex : int
908
+ The index of the function's arguments with respect to which the
909
+ derivative should be taken. Argument indexes start at ``1``.
910
+ Default is ``1``.
911
+
912
+ """
913
+ fl_M_pas, c0, c1 = self.args
914
+ if argindex == 1:
915
+ return c0*(exp(c1) - 1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
916
+ elif argindex == 2:
917
+ return log(fl_M_pas*(exp(c1) - 1) + 1)/c1
918
+ elif argindex == 3:
919
+ return (
920
+ c0*fl_M_pas*exp(c1)/(c1*(fl_M_pas*(exp(c1) - 1) + 1))
921
+ - c0*log(fl_M_pas*(exp(c1) - 1) + 1)/c1**2
922
+ )
923
+
924
+ raise ArgumentIndexError(self, argindex)
925
+
926
+ def inverse(self, argindex=1):
927
+ """Inverse function.
928
+
929
+ Parameters
930
+ ==========
931
+
932
+ argindex : int
933
+ Value to start indexing the arguments at. Default is ``1``.
934
+
935
+ """
936
+ return FiberForceLengthPassiveDeGroote2016
937
+
938
+ def _latex(self, printer):
939
+ """Print a LaTeX representation of the function defining the curve.
940
+
941
+ Parameters
942
+ ==========
943
+
944
+ printer : Printer
945
+ The printer to be used to print the LaTeX string representation.
946
+
947
+ """
948
+ fl_M_pas = self.args[0]
949
+ _fl_M_pas = printer._print(fl_M_pas)
950
+ return r'\left( \operatorname{fl}^M_{pas} \right)^{-1} \left( %s \right)' % _fl_M_pas
951
+
952
+
953
+ class FiberForceLengthActiveDeGroote2016(CharacteristicCurveFunction):
954
+ r"""Active muscle fiber force-length curve based on De Groote et al., 2016
955
+ [1]_.
956
+
957
+ Explanation
958
+ ===========
959
+
960
+ The function is defined by the equation:
961
+
962
+ $fl_{\text{act}}^M = c_0 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_1}{c_2 + c_3 \tilde{l}^M}\right)^2\right)
963
+ + c_4 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_5}{c_6 + c_7 \tilde{l}^M}\right)^2\right)
964
+ + c_8 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_9}{c_{10} + c_{11} \tilde{l}^M}\right)^2\right)$
965
+
966
+ with constant values of $c0 = 0.814$, $c1 = 1.06$, $c2 = 0.162$,
967
+ $c3 = 0.0633$, $c4 = 0.433$, $c5 = 0.717$, $c6 = -0.0299$, $c7 = 0.2$,
968
+ $c8 = 0.1$, $c9 = 1.0$, $c10 = 0.354$, and $c11 = 0.0$.
969
+
970
+ While it is possible to change the constant values, these were carefully
971
+ selected in the original publication to give the characteristic curve
972
+ specific and required properties. For example, the function produces a
973
+ active fiber force of 1 at a normalized fiber length of 1, and an active
974
+ fiber force of 0 at normalized fiber lengths of 0 and 2.
975
+
976
+ Examples
977
+ ========
978
+
979
+ The preferred way to instantiate :class:`FiberForceLengthActiveDeGroote2016` is
980
+ using the :meth:`~.with_defaults` constructor because this will automatically
981
+ populate the constants within the characteristic curve equation with the
982
+ floating point values from the original publication. This constructor takes
983
+ a single argument corresponding to normalized muscle fiber length. We'll
984
+ create a :class:`~.Symbol` called ``l_M_tilde`` to represent this.
985
+
986
+ >>> from sympy import Symbol
987
+ >>> from sympy.physics.biomechanics import FiberForceLengthActiveDeGroote2016
988
+ >>> l_M_tilde = Symbol('l_M_tilde')
989
+ >>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
990
+ >>> fl_M
991
+ FiberForceLengthActiveDeGroote2016(l_M_tilde, 0.814, 1.06, 0.162, 0.0633,
992
+ 0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
993
+
994
+ It's also possible to populate the two constants with your own values too.
995
+
996
+ >>> from sympy import symbols
997
+ >>> c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = symbols('c0:12')
998
+ >>> fl_M = FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3,
999
+ ... c4, c5, c6, c7, c8, c9, c10, c11)
1000
+ >>> fl_M
1001
+ FiberForceLengthActiveDeGroote2016(l_M_tilde, c0, c1, c2, c3, c4, c5, c6,
1002
+ c7, c8, c9, c10, c11)
1003
+
1004
+ You don't just have to use symbols as the arguments, it's also possible to
1005
+ use expressions. Let's create a new pair of symbols, ``l_M`` and
1006
+ ``l_M_opt``, representing muscle fiber length and optimal muscle fiber
1007
+ length respectively. We can then represent ``l_M_tilde`` as an expression,
1008
+ the ratio of these.
1009
+
1010
+ >>> l_M, l_M_opt = symbols('l_M l_M_opt')
1011
+ >>> l_M_tilde = l_M/l_M_opt
1012
+ >>> fl_M = FiberForceLengthActiveDeGroote2016.with_defaults(l_M_tilde)
1013
+ >>> fl_M
1014
+ FiberForceLengthActiveDeGroote2016(l_M/l_M_opt, 0.814, 1.06, 0.162, 0.0633,
1015
+ 0.433, 0.717, -0.0299, 0.2, 0.1, 1.0, 0.354, 0.0)
1016
+
1017
+ To inspect the actual symbolic expression that this function represents,
1018
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1019
+ argument ``evaluate=False`` as this will keep the expression in its
1020
+ canonical form and won't simplify any constants.
1021
+
1022
+ >>> fl_M.doit(evaluate=False)
1023
+ 0.814*exp(-(l_M/l_M_opt
1024
+ - 1.06)**2/(2*(0.0633*l_M/l_M_opt + 0.162)**2))
1025
+ + 0.433*exp(-(l_M/l_M_opt - 0.717)**2/(2*(0.2*l_M/l_M_opt - 0.0299)**2))
1026
+ + 0.1*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
1027
+
1028
+ The function can also be differentiated. We'll differentiate with respect
1029
+ to l_M using the ``diff`` method on an instance with the single positional
1030
+ argument ``l_M``.
1031
+
1032
+ >>> fl_M.diff(l_M)
1033
+ ((-0.79798269973507*l_M/l_M_opt
1034
+ + 0.79798269973507)*exp(-3.98991349867535*(l_M/l_M_opt - 1.0)**2)
1035
+ + (0.433*(-l_M/l_M_opt + 0.717)/(0.2*l_M/l_M_opt - 0.0299)**2
1036
+ + 0.0866*(l_M/l_M_opt - 0.717)**2/(0.2*l_M/l_M_opt
1037
+ - 0.0299)**3)*exp(-(l_M/l_M_opt - 0.717)**2/(2*(0.2*l_M/l_M_opt - 0.0299)**2))
1038
+ + (0.814*(-l_M/l_M_opt + 1.06)/(0.0633*l_M/l_M_opt
1039
+ + 0.162)**2 + 0.0515262*(l_M/l_M_opt
1040
+ - 1.06)**2/(0.0633*l_M/l_M_opt
1041
+ + 0.162)**3)*exp(-(l_M/l_M_opt
1042
+ - 1.06)**2/(2*(0.0633*l_M/l_M_opt + 0.162)**2)))/l_M_opt
1043
+
1044
+ References
1045
+ ==========
1046
+
1047
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1048
+ of direct collocation optimal control problem formulations for
1049
+ solving the muscle redundancy problem, Annals of biomedical
1050
+ engineering, 44(10), (2016) pp. 2922-2936
1051
+
1052
+ """
1053
+
1054
+ @classmethod
1055
+ def with_defaults(cls, l_M_tilde):
1056
+ r"""Recommended constructor that will use the published constants.
1057
+
1058
+ Explanation
1059
+ ===========
1060
+
1061
+ Returns a new instance of the inverse muscle fiber act force-length
1062
+ function using the four constant values specified in the original
1063
+ publication.
1064
+
1065
+ These have the values:
1066
+
1067
+ $c0 = 0.814$
1068
+ $c1 = 1.06$
1069
+ $c2 = 0.162$
1070
+ $c3 = 0.0633$
1071
+ $c4 = 0.433$
1072
+ $c5 = 0.717$
1073
+ $c6 = -0.0299$
1074
+ $c7 = 0.2$
1075
+ $c8 = 0.1$
1076
+ $c9 = 1.0$
1077
+ $c10 = 0.354$
1078
+ $c11 = 0.0$
1079
+
1080
+ Parameters
1081
+ ==========
1082
+
1083
+ fl_M_act : Any (sympifiable)
1084
+ Normalized passive muscle fiber force as a function of muscle fiber
1085
+ length.
1086
+
1087
+ """
1088
+ c0 = Float('0.814')
1089
+ c1 = Float('1.06')
1090
+ c2 = Float('0.162')
1091
+ c3 = Float('0.0633')
1092
+ c4 = Float('0.433')
1093
+ c5 = Float('0.717')
1094
+ c6 = Float('-0.0299')
1095
+ c7 = Float('0.2')
1096
+ c8 = Float('0.1')
1097
+ c9 = Float('1.0')
1098
+ c10 = Float('0.354')
1099
+ c11 = Float('0.0')
1100
+ return cls(l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11)
1101
+
1102
+ @classmethod
1103
+ def eval(cls, l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11):
1104
+ """Evaluation of basic inputs.
1105
+
1106
+ Parameters
1107
+ ==========
1108
+
1109
+ l_M_tilde : Any (sympifiable)
1110
+ Normalized muscle fiber length.
1111
+ c0 : Any (sympifiable)
1112
+ The first constant in the characteristic equation. The published
1113
+ value is ``0.814``.
1114
+ c1 : Any (sympifiable)
1115
+ The second constant in the characteristic equation. The published
1116
+ value is ``1.06``.
1117
+ c2 : Any (sympifiable)
1118
+ The third constant in the characteristic equation. The published
1119
+ value is ``0.162``.
1120
+ c3 : Any (sympifiable)
1121
+ The fourth constant in the characteristic equation. The published
1122
+ value is ``0.0633``.
1123
+ c4 : Any (sympifiable)
1124
+ The fifth constant in the characteristic equation. The published
1125
+ value is ``0.433``.
1126
+ c5 : Any (sympifiable)
1127
+ The sixth constant in the characteristic equation. The published
1128
+ value is ``0.717``.
1129
+ c6 : Any (sympifiable)
1130
+ The seventh constant in the characteristic equation. The published
1131
+ value is ``-0.0299``.
1132
+ c7 : Any (sympifiable)
1133
+ The eighth constant in the characteristic equation. The published
1134
+ value is ``0.2``.
1135
+ c8 : Any (sympifiable)
1136
+ The ninth constant in the characteristic equation. The published
1137
+ value is ``0.1``.
1138
+ c9 : Any (sympifiable)
1139
+ The tenth constant in the characteristic equation. The published
1140
+ value is ``1.0``.
1141
+ c10 : Any (sympifiable)
1142
+ The eleventh constant in the characteristic equation. The published
1143
+ value is ``0.354``.
1144
+ c11 : Any (sympifiable)
1145
+ The tweflth constant in the characteristic equation. The published
1146
+ value is ``0.0``.
1147
+
1148
+ """
1149
+ pass
1150
+
1151
+ def _eval_evalf(self, prec):
1152
+ """Evaluate the expression numerically using ``evalf``."""
1153
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1154
+
1155
+ def doit(self, deep=True, evaluate=True, **hints):
1156
+ """Evaluate the expression defining the function.
1157
+
1158
+ Parameters
1159
+ ==========
1160
+
1161
+ deep : bool
1162
+ Whether ``doit`` should be recursively called. Default is ``True``.
1163
+ evaluate : bool.
1164
+ Whether the SymPy expression should be evaluated as it is
1165
+ constructed. If ``False``, then no constant folding will be
1166
+ conducted which will leave the expression in a more numerically-
1167
+ stable for values of ``l_M_tilde`` that correspond to a sensible
1168
+ operating range for a musculotendon. Default is ``True``.
1169
+ **kwargs : dict[str, Any]
1170
+ Additional keyword argument pairs to be recursively passed to
1171
+ ``doit``.
1172
+
1173
+ """
1174
+ l_M_tilde, *constants = self.args
1175
+ if deep:
1176
+ hints['evaluate'] = evaluate
1177
+ l_M_tilde = l_M_tilde.doit(deep=deep, **hints)
1178
+ constants = [c.doit(deep=deep, **hints) for c in constants]
1179
+ c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = constants
1180
+
1181
+ if evaluate:
1182
+ return (
1183
+ c0*exp(-(((l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
1184
+ + c4*exp(-(((l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
1185
+ + c8*exp(-(((l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
1186
+ )
1187
+
1188
+ return (
1189
+ c0*exp(-((UnevaluatedExpr(l_M_tilde - c1)/(c2 + c3*l_M_tilde))**2)/2)
1190
+ + c4*exp(-((UnevaluatedExpr(l_M_tilde - c5)/(c6 + c7*l_M_tilde))**2)/2)
1191
+ + c8*exp(-((UnevaluatedExpr(l_M_tilde - c9)/(c10 + c11*l_M_tilde))**2)/2)
1192
+ )
1193
+
1194
+ def fdiff(self, argindex=1):
1195
+ """Derivative of the function with respect to a single argument.
1196
+
1197
+ Parameters
1198
+ ==========
1199
+
1200
+ argindex : int
1201
+ The index of the function's arguments with respect to which the
1202
+ derivative should be taken. Argument indexes start at ``1``.
1203
+ Default is ``1``.
1204
+
1205
+ """
1206
+ l_M_tilde, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11 = self.args
1207
+ if argindex == 1:
1208
+ return (
1209
+ c0*(
1210
+ c3*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1211
+ + (c1 - l_M_tilde)/((c2 + c3*l_M_tilde)**2)
1212
+ )*exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1213
+ + c4*(
1214
+ c7*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1215
+ + (c5 - l_M_tilde)/((c6 + c7*l_M_tilde)**2)
1216
+ )*exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1217
+ + c8*(
1218
+ c11*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1219
+ + (c9 - l_M_tilde)/((c10 + c11*l_M_tilde)**2)
1220
+ )*exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1221
+ )
1222
+ elif argindex == 2:
1223
+ return exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1224
+ elif argindex == 3:
1225
+ return (
1226
+ c0*(l_M_tilde - c1)/(c2 + c3*l_M_tilde)**2
1227
+ *exp(-(l_M_tilde - c1)**2 /(2*(c2 + c3*l_M_tilde)**2))
1228
+ )
1229
+ elif argindex == 4:
1230
+ return (
1231
+ c0*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1232
+ *exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1233
+ )
1234
+ elif argindex == 5:
1235
+ return (
1236
+ c0*l_M_tilde*(l_M_tilde - c1)**2/(c2 + c3*l_M_tilde)**3
1237
+ *exp(-(l_M_tilde - c1)**2/(2*(c2 + c3*l_M_tilde)**2))
1238
+ )
1239
+ elif argindex == 6:
1240
+ return exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1241
+ elif argindex == 7:
1242
+ return (
1243
+ c4*(l_M_tilde - c5)/(c6 + c7*l_M_tilde)**2
1244
+ *exp(-(l_M_tilde - c5)**2 /(2*(c6 + c7*l_M_tilde)**2))
1245
+ )
1246
+ elif argindex == 8:
1247
+ return (
1248
+ c4*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1249
+ *exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1250
+ )
1251
+ elif argindex == 9:
1252
+ return (
1253
+ c4*l_M_tilde*(l_M_tilde - c5)**2/(c6 + c7*l_M_tilde)**3
1254
+ *exp(-(l_M_tilde - c5)**2/(2*(c6 + c7*l_M_tilde)**2))
1255
+ )
1256
+ elif argindex == 10:
1257
+ return exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1258
+ elif argindex == 11:
1259
+ return (
1260
+ c8*(l_M_tilde - c9)/(c10 + c11*l_M_tilde)**2
1261
+ *exp(-(l_M_tilde - c9)**2 /(2*(c10 + c11*l_M_tilde)**2))
1262
+ )
1263
+ elif argindex == 12:
1264
+ return (
1265
+ c8*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1266
+ *exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1267
+ )
1268
+ elif argindex == 13:
1269
+ return (
1270
+ c8*l_M_tilde*(l_M_tilde - c9)**2/(c10 + c11*l_M_tilde)**3
1271
+ *exp(-(l_M_tilde - c9)**2/(2*(c10 + c11*l_M_tilde)**2))
1272
+ )
1273
+
1274
+ raise ArgumentIndexError(self, argindex)
1275
+
1276
+ def _latex(self, printer):
1277
+ """Print a LaTeX representation of the function defining the curve.
1278
+
1279
+ Parameters
1280
+ ==========
1281
+
1282
+ printer : Printer
1283
+ The printer to be used to print the LaTeX string representation.
1284
+
1285
+ """
1286
+ l_M_tilde = self.args[0]
1287
+ _l_M_tilde = printer._print(l_M_tilde)
1288
+ return r'\operatorname{fl}^M_{act} \left( %s \right)' % _l_M_tilde
1289
+
1290
+
1291
+ class FiberForceVelocityDeGroote2016(CharacteristicCurveFunction):
1292
+ r"""Muscle fiber force-velocity curve based on De Groote et al., 2016 [1]_.
1293
+
1294
+ Explanation
1295
+ ===========
1296
+
1297
+ Gives the normalized muscle fiber force produced as a function of
1298
+ normalized tendon velocity.
1299
+
1300
+ The function is defined by the equation:
1301
+
1302
+ $fv^M = c_0 \log{\left(c_1 \tilde{v}_m + c_2\right) + \sqrt{\left(c_1 \tilde{v}_m + c_2\right)^2 + 1}} + c_3$
1303
+
1304
+ with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
1305
+ $c_3 = 0.886$.
1306
+
1307
+ While it is possible to change the constant values, these were carefully
1308
+ selected in the original publication to give the characteristic curve
1309
+ specific and required properties. For example, the function produces a
1310
+ normalized muscle fiber force of 1 when the muscle fibers are contracting
1311
+ isometrically (they have an extension rate of 0).
1312
+
1313
+ Examples
1314
+ ========
1315
+
1316
+ The preferred way to instantiate :class:`FiberForceVelocityDeGroote2016` is using
1317
+ the :meth:`~.with_defaults` constructor because this will automatically populate
1318
+ the constants within the characteristic curve equation with the floating
1319
+ point values from the original publication. This constructor takes a single
1320
+ argument corresponding to normalized muscle fiber extension velocity. We'll
1321
+ create a :class:`~.Symbol` called ``v_M_tilde`` to represent this.
1322
+
1323
+ >>> from sympy import Symbol
1324
+ >>> from sympy.physics.biomechanics import FiberForceVelocityDeGroote2016
1325
+ >>> v_M_tilde = Symbol('v_M_tilde')
1326
+ >>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
1327
+ >>> fv_M
1328
+ FiberForceVelocityDeGroote2016(v_M_tilde, -0.318, -8.149, -0.374, 0.886)
1329
+
1330
+ It's also possible to populate the four constants with your own values too.
1331
+
1332
+ >>> from sympy import symbols
1333
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
1334
+ >>> fv_M = FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
1335
+ >>> fv_M
1336
+ FiberForceVelocityDeGroote2016(v_M_tilde, c0, c1, c2, c3)
1337
+
1338
+ You don't just have to use symbols as the arguments, it's also possible to
1339
+ use expressions. Let's create a new pair of symbols, ``v_M`` and
1340
+ ``v_M_max``, representing muscle fiber extension velocity and maximum
1341
+ muscle fiber extension velocity respectively. We can then represent
1342
+ ``v_M_tilde`` as an expression, the ratio of these.
1343
+
1344
+ >>> v_M, v_M_max = symbols('v_M v_M_max')
1345
+ >>> v_M_tilde = v_M/v_M_max
1346
+ >>> fv_M = FiberForceVelocityDeGroote2016.with_defaults(v_M_tilde)
1347
+ >>> fv_M
1348
+ FiberForceVelocityDeGroote2016(v_M/v_M_max, -0.318, -8.149, -0.374, 0.886)
1349
+
1350
+ To inspect the actual symbolic expression that this function represents,
1351
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1352
+ argument ``evaluate=False`` as this will keep the expression in its
1353
+ canonical form and won't simplify any constants.
1354
+
1355
+ >>> fv_M.doit(evaluate=False)
1356
+ 0.886 - 0.318*log(-8.149*v_M/v_M_max - 0.374 + sqrt(1 + (-8.149*v_M/v_M_max
1357
+ - 0.374)**2))
1358
+
1359
+ The function can also be differentiated. We'll differentiate with respect
1360
+ to v_M using the ``diff`` method on an instance with the single positional
1361
+ argument ``v_M``.
1362
+
1363
+ >>> fv_M.diff(v_M)
1364
+ 2.591382*(1 + (-8.149*v_M/v_M_max - 0.374)**2)**(-1/2)/v_M_max
1365
+
1366
+ References
1367
+ ==========
1368
+
1369
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1370
+ of direct collocation optimal control problem formulations for
1371
+ solving the muscle redundancy problem, Annals of biomedical
1372
+ engineering, 44(10), (2016) pp. 2922-2936
1373
+
1374
+ """
1375
+
1376
+ @classmethod
1377
+ def with_defaults(cls, v_M_tilde):
1378
+ r"""Recommended constructor that will use the published constants.
1379
+
1380
+ Explanation
1381
+ ===========
1382
+
1383
+ Returns a new instance of the muscle fiber force-velocity function
1384
+ using the four constant values specified in the original publication.
1385
+
1386
+ These have the values:
1387
+
1388
+ $c_0 = -0.318$
1389
+ $c_1 = -8.149$
1390
+ $c_2 = -0.374$
1391
+ $c_3 = 0.886$
1392
+
1393
+ Parameters
1394
+ ==========
1395
+
1396
+ v_M_tilde : Any (sympifiable)
1397
+ Normalized muscle fiber extension velocity.
1398
+
1399
+ """
1400
+ c0 = Float('-0.318')
1401
+ c1 = Float('-8.149')
1402
+ c2 = Float('-0.374')
1403
+ c3 = Float('0.886')
1404
+ return cls(v_M_tilde, c0, c1, c2, c3)
1405
+
1406
+ @classmethod
1407
+ def eval(cls, v_M_tilde, c0, c1, c2, c3):
1408
+ """Evaluation of basic inputs.
1409
+
1410
+ Parameters
1411
+ ==========
1412
+
1413
+ v_M_tilde : Any (sympifiable)
1414
+ Normalized muscle fiber extension velocity.
1415
+ c0 : Any (sympifiable)
1416
+ The first constant in the characteristic equation. The published
1417
+ value is ``-0.318``.
1418
+ c1 : Any (sympifiable)
1419
+ The second constant in the characteristic equation. The published
1420
+ value is ``-8.149``.
1421
+ c2 : Any (sympifiable)
1422
+ The third constant in the characteristic equation. The published
1423
+ value is ``-0.374``.
1424
+ c3 : Any (sympifiable)
1425
+ The fourth constant in the characteristic equation. The published
1426
+ value is ``0.886``.
1427
+
1428
+ """
1429
+ pass
1430
+
1431
+ def _eval_evalf(self, prec):
1432
+ """Evaluate the expression numerically using ``evalf``."""
1433
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1434
+
1435
+ def doit(self, deep=True, evaluate=True, **hints):
1436
+ """Evaluate the expression defining the function.
1437
+
1438
+ Parameters
1439
+ ==========
1440
+
1441
+ deep : bool
1442
+ Whether ``doit`` should be recursively called. Default is ``True``.
1443
+ evaluate : bool.
1444
+ Whether the SymPy expression should be evaluated as it is
1445
+ constructed. If ``False``, then no constant folding will be
1446
+ conducted which will leave the expression in a more numerically-
1447
+ stable for values of ``v_M_tilde`` that correspond to a sensible
1448
+ operating range for a musculotendon. Default is ``True``.
1449
+ **kwargs : dict[str, Any]
1450
+ Additional keyword argument pairs to be recursively passed to
1451
+ ``doit``.
1452
+
1453
+ """
1454
+ v_M_tilde, *constants = self.args
1455
+ if deep:
1456
+ hints['evaluate'] = evaluate
1457
+ v_M_tilde = v_M_tilde.doit(deep=deep, **hints)
1458
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
1459
+ else:
1460
+ c0, c1, c2, c3 = constants
1461
+
1462
+ if evaluate:
1463
+ return c0*log(c1*v_M_tilde + c2 + sqrt((c1*v_M_tilde + c2)**2 + 1)) + c3
1464
+
1465
+ return c0*log(c1*v_M_tilde + c2 + sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)) + c3
1466
+
1467
+ def fdiff(self, argindex=1):
1468
+ """Derivative of the function with respect to a single argument.
1469
+
1470
+ Parameters
1471
+ ==========
1472
+
1473
+ argindex : int
1474
+ The index of the function's arguments with respect to which the
1475
+ derivative should be taken. Argument indexes start at ``1``.
1476
+ Default is ``1``.
1477
+
1478
+ """
1479
+ v_M_tilde, c0, c1, c2, c3 = self.args
1480
+ if argindex == 1:
1481
+ return c0*c1/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1482
+ elif argindex == 2:
1483
+ return log(
1484
+ c1*v_M_tilde + c2
1485
+ + sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1486
+ )
1487
+ elif argindex == 3:
1488
+ return c0*v_M_tilde/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1489
+ elif argindex == 4:
1490
+ return c0/sqrt(UnevaluatedExpr(c1*v_M_tilde + c2)**2 + 1)
1491
+ elif argindex == 5:
1492
+ return Integer(1)
1493
+
1494
+ raise ArgumentIndexError(self, argindex)
1495
+
1496
+ def inverse(self, argindex=1):
1497
+ """Inverse function.
1498
+
1499
+ Parameters
1500
+ ==========
1501
+
1502
+ argindex : int
1503
+ Value to start indexing the arguments at. Default is ``1``.
1504
+
1505
+ """
1506
+ return FiberForceVelocityInverseDeGroote2016
1507
+
1508
+ def _latex(self, printer):
1509
+ """Print a LaTeX representation of the function defining the curve.
1510
+
1511
+ Parameters
1512
+ ==========
1513
+
1514
+ printer : Printer
1515
+ The printer to be used to print the LaTeX string representation.
1516
+
1517
+ """
1518
+ v_M_tilde = self.args[0]
1519
+ _v_M_tilde = printer._print(v_M_tilde)
1520
+ return r'\operatorname{fv}^M \left( %s \right)' % _v_M_tilde
1521
+
1522
+
1523
+ class FiberForceVelocityInverseDeGroote2016(CharacteristicCurveFunction):
1524
+ r"""Inverse muscle fiber force-velocity curve based on De Groote et al.,
1525
+ 2016 [1]_.
1526
+
1527
+ Explanation
1528
+ ===========
1529
+
1530
+ Gives the normalized muscle fiber velocity that produces a specific
1531
+ normalized muscle fiber force.
1532
+
1533
+ The function is defined by the equation:
1534
+
1535
+ ${fv^M}^{-1} = \frac{\sinh{\frac{fv^M - c_3}{c_0}} - c_2}{c_1}$
1536
+
1537
+ with constant values of $c_0 = -0.318$, $c_1 = -8.149$, $c_2 = -0.374$, and
1538
+ $c_3 = 0.886$. This function is the exact analytical inverse of the related
1539
+ muscle fiber force-velocity curve ``FiberForceVelocityDeGroote2016``.
1540
+
1541
+ While it is possible to change the constant values, these were carefully
1542
+ selected in the original publication to give the characteristic curve
1543
+ specific and required properties. For example, the function produces a
1544
+ normalized muscle fiber force of 1 when the muscle fibers are contracting
1545
+ isometrically (they have an extension rate of 0).
1546
+
1547
+ Examples
1548
+ ========
1549
+
1550
+ The preferred way to instantiate :class:`FiberForceVelocityInverseDeGroote2016`
1551
+ is using the :meth:`~.with_defaults` constructor because this will automatically
1552
+ populate the constants within the characteristic curve equation with the
1553
+ floating point values from the original publication. This constructor takes
1554
+ a single argument corresponding to normalized muscle fiber force-velocity
1555
+ component of the muscle fiber force. We'll create a :class:`~.Symbol` called
1556
+ ``fv_M`` to represent this.
1557
+
1558
+ >>> from sympy import Symbol
1559
+ >>> from sympy.physics.biomechanics import FiberForceVelocityInverseDeGroote2016
1560
+ >>> fv_M = Symbol('fv_M')
1561
+ >>> v_M_tilde = FiberForceVelocityInverseDeGroote2016.with_defaults(fv_M)
1562
+ >>> v_M_tilde
1563
+ FiberForceVelocityInverseDeGroote2016(fv_M, -0.318, -8.149, -0.374, 0.886)
1564
+
1565
+ It's also possible to populate the four constants with your own values too.
1566
+
1567
+ >>> from sympy import symbols
1568
+ >>> c0, c1, c2, c3 = symbols('c0 c1 c2 c3')
1569
+ >>> v_M_tilde = FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
1570
+ >>> v_M_tilde
1571
+ FiberForceVelocityInverseDeGroote2016(fv_M, c0, c1, c2, c3)
1572
+
1573
+ To inspect the actual symbolic expression that this function represents,
1574
+ we can call the :meth:`~.doit` method on an instance. We'll use the keyword
1575
+ argument ``evaluate=False`` as this will keep the expression in its
1576
+ canonical form and won't simplify any constants.
1577
+
1578
+ >>> v_M_tilde.doit(evaluate=False)
1579
+ (-c2 + sinh((-c3 + fv_M)/c0))/c1
1580
+
1581
+ The function can also be differentiated. We'll differentiate with respect
1582
+ to fv_M using the ``diff`` method on an instance with the single positional
1583
+ argument ``fv_M``.
1584
+
1585
+ >>> v_M_tilde.diff(fv_M)
1586
+ cosh((-c3 + fv_M)/c0)/(c0*c1)
1587
+
1588
+ References
1589
+ ==========
1590
+
1591
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1592
+ of direct collocation optimal control problem formulations for
1593
+ solving the muscle redundancy problem, Annals of biomedical
1594
+ engineering, 44(10), (2016) pp. 2922-2936
1595
+
1596
+ """
1597
+
1598
+ @classmethod
1599
+ def with_defaults(cls, fv_M):
1600
+ r"""Recommended constructor that will use the published constants.
1601
+
1602
+ Explanation
1603
+ ===========
1604
+
1605
+ Returns a new instance of the inverse muscle fiber force-velocity
1606
+ function using the four constant values specified in the original
1607
+ publication.
1608
+
1609
+ These have the values:
1610
+
1611
+ $c_0 = -0.318$
1612
+ $c_1 = -8.149$
1613
+ $c_2 = -0.374$
1614
+ $c_3 = 0.886$
1615
+
1616
+ Parameters
1617
+ ==========
1618
+
1619
+ fv_M : Any (sympifiable)
1620
+ Normalized muscle fiber extension velocity.
1621
+
1622
+ """
1623
+ c0 = Float('-0.318')
1624
+ c1 = Float('-8.149')
1625
+ c2 = Float('-0.374')
1626
+ c3 = Float('0.886')
1627
+ return cls(fv_M, c0, c1, c2, c3)
1628
+
1629
+ @classmethod
1630
+ def eval(cls, fv_M, c0, c1, c2, c3):
1631
+ """Evaluation of basic inputs.
1632
+
1633
+ Parameters
1634
+ ==========
1635
+
1636
+ fv_M : Any (sympifiable)
1637
+ Normalized muscle fiber force as a function of muscle fiber
1638
+ extension velocity.
1639
+ c0 : Any (sympifiable)
1640
+ The first constant in the characteristic equation. The published
1641
+ value is ``-0.318``.
1642
+ c1 : Any (sympifiable)
1643
+ The second constant in the characteristic equation. The published
1644
+ value is ``-8.149``.
1645
+ c2 : Any (sympifiable)
1646
+ The third constant in the characteristic equation. The published
1647
+ value is ``-0.374``.
1648
+ c3 : Any (sympifiable)
1649
+ The fourth constant in the characteristic equation. The published
1650
+ value is ``0.886``.
1651
+
1652
+ """
1653
+ pass
1654
+
1655
+ def _eval_evalf(self, prec):
1656
+ """Evaluate the expression numerically using ``evalf``."""
1657
+ return self.doit(deep=False, evaluate=False)._eval_evalf(prec)
1658
+
1659
+ def doit(self, deep=True, evaluate=True, **hints):
1660
+ """Evaluate the expression defining the function.
1661
+
1662
+ Parameters
1663
+ ==========
1664
+
1665
+ deep : bool
1666
+ Whether ``doit`` should be recursively called. Default is ``True``.
1667
+ evaluate : bool.
1668
+ Whether the SymPy expression should be evaluated as it is
1669
+ constructed. If ``False``, then no constant folding will be
1670
+ conducted which will leave the expression in a more numerically-
1671
+ stable for values of ``fv_M`` that correspond to a sensible
1672
+ operating range for a musculotendon. Default is ``True``.
1673
+ **kwargs : dict[str, Any]
1674
+ Additional keyword argument pairs to be recursively passed to
1675
+ ``doit``.
1676
+
1677
+ """
1678
+ fv_M, *constants = self.args
1679
+ if deep:
1680
+ hints['evaluate'] = evaluate
1681
+ fv_M = fv_M.doit(deep=deep, **hints)
1682
+ c0, c1, c2, c3 = [c.doit(deep=deep, **hints) for c in constants]
1683
+ else:
1684
+ c0, c1, c2, c3 = constants
1685
+
1686
+ if evaluate:
1687
+ return (sinh((fv_M - c3)/c0) - c2)/c1
1688
+
1689
+ return (sinh(UnevaluatedExpr(fv_M - c3)/c0) - c2)/c1
1690
+
1691
+ def fdiff(self, argindex=1):
1692
+ """Derivative of the function with respect to a single argument.
1693
+
1694
+ Parameters
1695
+ ==========
1696
+
1697
+ argindex : int
1698
+ The index of the function's arguments with respect to which the
1699
+ derivative should be taken. Argument indexes start at ``1``.
1700
+ Default is ``1``.
1701
+
1702
+ """
1703
+ fv_M, c0, c1, c2, c3 = self.args
1704
+ if argindex == 1:
1705
+ return cosh((fv_M - c3)/c0)/(c0*c1)
1706
+ elif argindex == 2:
1707
+ return (c3 - fv_M)*cosh((fv_M - c3)/c0)/(c0**2*c1)
1708
+ elif argindex == 3:
1709
+ return (c2 - sinh((fv_M - c3)/c0))/c1**2
1710
+ elif argindex == 4:
1711
+ return -1/c1
1712
+ elif argindex == 5:
1713
+ return -cosh((fv_M - c3)/c0)/(c0*c1)
1714
+
1715
+ raise ArgumentIndexError(self, argindex)
1716
+
1717
+ def inverse(self, argindex=1):
1718
+ """Inverse function.
1719
+
1720
+ Parameters
1721
+ ==========
1722
+
1723
+ argindex : int
1724
+ Value to start indexing the arguments at. Default is ``1``.
1725
+
1726
+ """
1727
+ return FiberForceVelocityDeGroote2016
1728
+
1729
+ def _latex(self, printer):
1730
+ """Print a LaTeX representation of the function defining the curve.
1731
+
1732
+ Parameters
1733
+ ==========
1734
+
1735
+ printer : Printer
1736
+ The printer to be used to print the LaTeX string representation.
1737
+
1738
+ """
1739
+ fv_M = self.args[0]
1740
+ _fv_M = printer._print(fv_M)
1741
+ return r'\left( \operatorname{fv}^M \right)^{-1} \left( %s \right)' % _fv_M
1742
+
1743
+
1744
+ @dataclass(frozen=True)
1745
+ class CharacteristicCurveCollection:
1746
+ """Simple data container to group together related characteristic curves."""
1747
+ tendon_force_length: CharacteristicCurveFunction
1748
+ tendon_force_length_inverse: CharacteristicCurveFunction
1749
+ fiber_force_length_passive: CharacteristicCurveFunction
1750
+ fiber_force_length_passive_inverse: CharacteristicCurveFunction
1751
+ fiber_force_length_active: CharacteristicCurveFunction
1752
+ fiber_force_velocity: CharacteristicCurveFunction
1753
+ fiber_force_velocity_inverse: CharacteristicCurveFunction
1754
+
1755
+ def __iter__(self):
1756
+ """Iterator support for ``CharacteristicCurveCollection``."""
1757
+ yield self.tendon_force_length
1758
+ yield self.tendon_force_length_inverse
1759
+ yield self.fiber_force_length_passive
1760
+ yield self.fiber_force_length_passive_inverse
1761
+ yield self.fiber_force_length_active
1762
+ yield self.fiber_force_velocity
1763
+ yield self.fiber_force_velocity_inverse
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/musculotendon.py ADDED
@@ -0,0 +1,1424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of musculotendon models.
2
+
3
+ Musculotendon models are a critical component of biomechanical models, one that
4
+ differentiates them from pure multibody systems. Musculotendon models produce a
5
+ force dependent on their level of activation, their length, and their
6
+ extension velocity. Length- and extension velocity-dependent force production
7
+ are governed by force-length and force-velocity characteristics.
8
+ These are normalized functions that are dependent on the musculotendon's state
9
+ and are specific to a given musculotendon model.
10
+
11
+ """
12
+
13
+ from abc import abstractmethod
14
+ from enum import IntEnum, unique
15
+
16
+ from sympy.core.numbers import Float, Integer
17
+ from sympy.core.symbol import Symbol, symbols
18
+ from sympy.functions.elementary.miscellaneous import sqrt
19
+ from sympy.functions.elementary.trigonometric import cos, sin
20
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, diag, eye, zeros
21
+ from sympy.physics.biomechanics.activation import ActivationBase
22
+ from sympy.physics.biomechanics.curve import (
23
+ CharacteristicCurveCollection,
24
+ FiberForceLengthActiveDeGroote2016,
25
+ FiberForceLengthPassiveDeGroote2016,
26
+ FiberForceLengthPassiveInverseDeGroote2016,
27
+ FiberForceVelocityDeGroote2016,
28
+ FiberForceVelocityInverseDeGroote2016,
29
+ TendonForceLengthDeGroote2016,
30
+ TendonForceLengthInverseDeGroote2016,
31
+ )
32
+ from sympy.physics.biomechanics._mixin import _NamedMixin
33
+ from sympy.physics.mechanics.actuator import ForceActuator
34
+ from sympy.physics.vector.functions import dynamicsymbols
35
+
36
+
37
+ __all__ = [
38
+ 'MusculotendonBase',
39
+ 'MusculotendonDeGroote2016',
40
+ 'MusculotendonFormulation',
41
+ ]
42
+
43
+
44
+ @unique
45
+ class MusculotendonFormulation(IntEnum):
46
+ """Enumeration of types of musculotendon dynamics formulations.
47
+
48
+ Explanation
49
+ ===========
50
+
51
+ An (integer) enumeration is used as it allows for clearer selection of the
52
+ different formulations of musculotendon dynamics.
53
+
54
+ Members
55
+ =======
56
+
57
+ RIGID_TENDON : 0
58
+ A rigid tendon model.
59
+ FIBER_LENGTH_EXPLICIT : 1
60
+ An explicit elastic tendon model with the muscle fiber length (l_M) as
61
+ the state variable.
62
+ TENDON_FORCE_EXPLICIT : 2
63
+ An explicit elastic tendon model with the tendon force (F_T) as the
64
+ state variable.
65
+ FIBER_LENGTH_IMPLICIT : 3
66
+ An implicit elastic tendon model with the muscle fiber length (l_M) as
67
+ the state variable and the muscle fiber velocity as an additional input
68
+ variable.
69
+ TENDON_FORCE_IMPLICIT : 4
70
+ An implicit elastic tendon model with the tendon force (F_T) as the
71
+ state variable as the muscle fiber velocity as an additional input
72
+ variable.
73
+
74
+ """
75
+
76
+ RIGID_TENDON = 0
77
+ FIBER_LENGTH_EXPLICIT = 1
78
+ TENDON_FORCE_EXPLICIT = 2
79
+ FIBER_LENGTH_IMPLICIT = 3
80
+ TENDON_FORCE_IMPLICIT = 4
81
+
82
+ def __str__(self):
83
+ """Returns a string representation of the enumeration value.
84
+
85
+ Notes
86
+ =====
87
+
88
+ This hard coding is required due to an incompatibility between the
89
+ ``IntEnum`` implementations in Python 3.10 and Python 3.11
90
+ (https://github.com/python/cpython/issues/84247). From Python 3.11
91
+ onwards, the ``__str__`` method uses ``int.__str__``, whereas prior it
92
+ used ``Enum.__str__``. Once Python 3.11 becomes the minimum version
93
+ supported by SymPy, this method override can be removed.
94
+
95
+ """
96
+ return str(self.value)
97
+
98
+
99
+ _DEFAULT_MUSCULOTENDON_FORMULATION = MusculotendonFormulation.RIGID_TENDON
100
+
101
+
102
+ class MusculotendonBase(ForceActuator, _NamedMixin):
103
+ r"""Abstract base class for all musculotendon classes to inherit from.
104
+
105
+ Explanation
106
+ ===========
107
+
108
+ A musculotendon generates a contractile force based on its activation,
109
+ length, and shortening velocity. This abstract base class is to be inherited
110
+ by all musculotendon subclasses that implement different characteristic
111
+ musculotendon curves. Characteristic musculotendon curves are required for
112
+ the tendon force-length, passive fiber force-length, active fiber force-
113
+ length, and fiber force-velocity relationships.
114
+
115
+ Parameters
116
+ ==========
117
+
118
+ name : str
119
+ The name identifier associated with the musculotendon. This name is used
120
+ as a suffix when automatically generated symbols are instantiated. It
121
+ must be a string of nonzero length.
122
+ pathway : PathwayBase
123
+ The pathway that the actuator follows. This must be an instance of a
124
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
125
+ activation_dynamics : ActivationBase
126
+ The activation dynamics that will be modeled within the musculotendon.
127
+ This must be an instance of a concrete subclass of ``ActivationBase``,
128
+ e.g. ``FirstOrderActivationDeGroote2016``.
129
+ musculotendon_dynamics : MusculotendonFormulation | int
130
+ The formulation of musculotendon dynamics that should be used
131
+ internally, i.e. rigid or elastic tendon model, the choice of
132
+ musculotendon state etc. This must be a member of the integer
133
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
134
+ to a member. To use a rigid tendon formulation, set this to
135
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
136
+ which will be cast to the enumeration member). There are four possible
137
+ formulations for an elastic tendon model. To use an explicit formulation
138
+ with the fiber length as the state, set this to
139
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
140
+ ``1``). To use an explicit formulation with the tendon force as the
141
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
142
+ (or the integer value ``2``). To use an implicit formulation with the
143
+ fiber length as the state, set this to
144
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
145
+ ``3``). To use an implicit formulation with the tendon force as the
146
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
147
+ (or the integer value ``4``). The default is
148
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
149
+ tendon formulation.
150
+ tendon_slack_length : Expr | None
151
+ The length of the tendon when the musculotendon is in its unloaded
152
+ state. In a rigid tendon model the tendon length is the tendon slack
153
+ length. In all musculotendon models, tendon slack length is used to
154
+ normalize tendon length to give
155
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
156
+ peak_isometric_force : Expr | None
157
+ The maximum force that the muscle fiber can produce when it is
158
+ undergoing an isometric contraction (no lengthening velocity). In all
159
+ musculotendon models, peak isometric force is used to normalized tendon
160
+ and muscle fiber force to give
161
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
162
+ optimal_fiber_length : Expr | None
163
+ The muscle fiber length at which the muscle fibers produce no passive
164
+ force and their maximum active force. In all musculotendon models,
165
+ optimal fiber length is used to normalize muscle fiber length to give
166
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
167
+ maximal_fiber_velocity : Expr | None
168
+ The fiber velocity at which, during muscle fiber shortening, the muscle
169
+ fibers are unable to produce any active force. In all musculotendon
170
+ models, maximal fiber velocity is used to normalize muscle fiber
171
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
172
+ optimal_pennation_angle : Expr | None
173
+ The pennation angle when muscle fiber length equals the optimal fiber
174
+ length.
175
+ fiber_damping_coefficient : Expr | None
176
+ The coefficient of damping to be used in the damping element in the
177
+ muscle fiber model.
178
+ with_defaults : bool
179
+ Whether ``with_defaults`` alternate constructors should be used when
180
+ automatically constructing child classes. Default is ``False``.
181
+
182
+ """
183
+
184
+ def __init__(
185
+ self,
186
+ name,
187
+ pathway,
188
+ activation_dynamics,
189
+ *,
190
+ musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
191
+ tendon_slack_length=None,
192
+ peak_isometric_force=None,
193
+ optimal_fiber_length=None,
194
+ maximal_fiber_velocity=None,
195
+ optimal_pennation_angle=None,
196
+ fiber_damping_coefficient=None,
197
+ with_defaults=False,
198
+ ):
199
+ self.name = name
200
+
201
+ # Supply a placeholder force to the super initializer, this will be
202
+ # replaced later
203
+ super().__init__(Symbol('F'), pathway)
204
+
205
+ # Activation dynamics
206
+ if not isinstance(activation_dynamics, ActivationBase):
207
+ msg = (
208
+ f'Can\'t set attribute `activation_dynamics` to '
209
+ f'{activation_dynamics} as it must be of type '
210
+ f'`ActivationBase`, not {type(activation_dynamics)}.'
211
+ )
212
+ raise TypeError(msg)
213
+ self._activation_dynamics = activation_dynamics
214
+ self._child_objects = (self._activation_dynamics, )
215
+
216
+ # Constants
217
+ if tendon_slack_length is not None:
218
+ self._l_T_slack = tendon_slack_length
219
+ else:
220
+ self._l_T_slack = Symbol(f'l_T_slack_{self.name}')
221
+ if peak_isometric_force is not None:
222
+ self._F_M_max = peak_isometric_force
223
+ else:
224
+ self._F_M_max = Symbol(f'F_M_max_{self.name}')
225
+ if optimal_fiber_length is not None:
226
+ self._l_M_opt = optimal_fiber_length
227
+ else:
228
+ self._l_M_opt = Symbol(f'l_M_opt_{self.name}')
229
+ if maximal_fiber_velocity is not None:
230
+ self._v_M_max = maximal_fiber_velocity
231
+ else:
232
+ self._v_M_max = Symbol(f'v_M_max_{self.name}')
233
+ if optimal_pennation_angle is not None:
234
+ self._alpha_opt = optimal_pennation_angle
235
+ else:
236
+ self._alpha_opt = Symbol(f'alpha_opt_{self.name}')
237
+ if fiber_damping_coefficient is not None:
238
+ self._beta = fiber_damping_coefficient
239
+ else:
240
+ self._beta = Symbol(f'beta_{self.name}')
241
+
242
+ # Musculotendon dynamics
243
+ self._with_defaults = with_defaults
244
+ if musculotendon_dynamics == MusculotendonFormulation.RIGID_TENDON:
245
+ self._rigid_tendon_musculotendon_dynamics()
246
+ elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_EXPLICIT:
247
+ self._fiber_length_explicit_musculotendon_dynamics()
248
+ elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_EXPLICIT:
249
+ self._tendon_force_explicit_musculotendon_dynamics()
250
+ elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_IMPLICIT:
251
+ self._fiber_length_implicit_musculotendon_dynamics()
252
+ elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_IMPLICIT:
253
+ self._tendon_force_implicit_musculotendon_dynamics()
254
+ else:
255
+ msg = (
256
+ f'Musculotendon dynamics {repr(musculotendon_dynamics)} '
257
+ f'passed to `musculotendon_dynamics` was of type '
258
+ f'{type(musculotendon_dynamics)}, must be '
259
+ f'{MusculotendonFormulation}.'
260
+ )
261
+ raise TypeError(msg)
262
+ self._musculotendon_dynamics = musculotendon_dynamics
263
+
264
+ # Must override the placeholder value in `self._force` now that the
265
+ # actual force has been calculated by
266
+ # `self._<MUSCULOTENDON FORMULATION>_musculotendon_dynamics`.
267
+ # Note that `self._force` assumes forces are expansile, musculotendon
268
+ # forces are contractile hence the minus sign preceding `self._F_T`
269
+ # (the tendon force).
270
+ self._force = -self._F_T
271
+
272
+ @classmethod
273
+ def with_defaults(
274
+ cls,
275
+ name,
276
+ pathway,
277
+ activation_dynamics,
278
+ *,
279
+ musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
280
+ tendon_slack_length=None,
281
+ peak_isometric_force=None,
282
+ optimal_fiber_length=None,
283
+ maximal_fiber_velocity=Float('10.0'),
284
+ optimal_pennation_angle=Float('0.0'),
285
+ fiber_damping_coefficient=Float('0.1'),
286
+ ):
287
+ r"""Recommended constructor that will use the published constants.
288
+
289
+ Explanation
290
+ ===========
291
+
292
+ Returns a new instance of the musculotendon class using recommended
293
+ values for ``v_M_max``, ``alpha_opt``, and ``beta``. The values are:
294
+
295
+ :math:`v^M_{max} = 10`
296
+ :math:`\alpha_{opt} = 0`
297
+ :math:`\beta = \frac{1}{10}`
298
+
299
+ The musculotendon curves are also instantiated using the constants from
300
+ the original publication.
301
+
302
+ Parameters
303
+ ==========
304
+
305
+ name : str
306
+ The name identifier associated with the musculotendon. This name is
307
+ used as a suffix when automatically generated symbols are
308
+ instantiated. It must be a string of nonzero length.
309
+ pathway : PathwayBase
310
+ The pathway that the actuator follows. This must be an instance of a
311
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
312
+ activation_dynamics : ActivationBase
313
+ The activation dynamics that will be modeled within the
314
+ musculotendon. This must be an instance of a concrete subclass of
315
+ ``ActivationBase``, e.g. ``FirstOrderActivationDeGroote2016``.
316
+ musculotendon_dynamics : MusculotendonFormulation | int
317
+ The formulation of musculotendon dynamics that should be used
318
+ internally, i.e. rigid or elastic tendon model, the choice of
319
+ musculotendon state etc. This must be a member of the integer
320
+ enumeration ``MusculotendonFormulation`` or an integer that can be
321
+ cast to a member. To use a rigid tendon formulation, set this to
322
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value
323
+ ``0``, which will be cast to the enumeration member). There are four
324
+ possible formulations for an elastic tendon model. To use an
325
+ explicit formulation with the fiber length as the state, set this to
326
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer
327
+ value ``1``). To use an explicit formulation with the tendon force
328
+ as the state, set this to
329
+ ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT`` (or the integer
330
+ value ``2``). To use an implicit formulation with the fiber length
331
+ as the state, set this to
332
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer
333
+ value ``3``). To use an implicit formulation with the tendon force
334
+ as the state, set this to
335
+ ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT`` (or the integer
336
+ value ``4``). The default is
337
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a
338
+ rigid tendon formulation.
339
+ tendon_slack_length : Expr | None
340
+ The length of the tendon when the musculotendon is in its unloaded
341
+ state. In a rigid tendon model the tendon length is the tendon slack
342
+ length. In all musculotendon models, tendon slack length is used to
343
+ normalize tendon length to give
344
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
345
+ peak_isometric_force : Expr | None
346
+ The maximum force that the muscle fiber can produce when it is
347
+ undergoing an isometric contraction (no lengthening velocity). In
348
+ all musculotendon models, peak isometric force is used to normalized
349
+ tendon and muscle fiber force to give
350
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
351
+ optimal_fiber_length : Expr | None
352
+ The muscle fiber length at which the muscle fibers produce no
353
+ passive force and their maximum active force. In all musculotendon
354
+ models, optimal fiber length is used to normalize muscle fiber
355
+ length to give :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
356
+ maximal_fiber_velocity : Expr | None
357
+ The fiber velocity at which, during muscle fiber shortening, the
358
+ muscle fibers are unable to produce any active force. In all
359
+ musculotendon models, maximal fiber velocity is used to normalize
360
+ muscle fiber extension velocity to give
361
+ :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
362
+ optimal_pennation_angle : Expr | None
363
+ The pennation angle when muscle fiber length equals the optimal
364
+ fiber length.
365
+ fiber_damping_coefficient : Expr | None
366
+ The coefficient of damping to be used in the damping element in the
367
+ muscle fiber model.
368
+
369
+ """
370
+ return cls(
371
+ name,
372
+ pathway,
373
+ activation_dynamics=activation_dynamics,
374
+ musculotendon_dynamics=musculotendon_dynamics,
375
+ tendon_slack_length=tendon_slack_length,
376
+ peak_isometric_force=peak_isometric_force,
377
+ optimal_fiber_length=optimal_fiber_length,
378
+ maximal_fiber_velocity=maximal_fiber_velocity,
379
+ optimal_pennation_angle=optimal_pennation_angle,
380
+ fiber_damping_coefficient=fiber_damping_coefficient,
381
+ with_defaults=True,
382
+ )
383
+
384
+ @abstractmethod
385
+ def curves(cls):
386
+ """Return a ``CharacteristicCurveCollection`` of the curves related to
387
+ the specific model."""
388
+ pass
389
+
390
+ @property
391
+ def tendon_slack_length(self):
392
+ r"""Symbol or value corresponding to the tendon slack length constant.
393
+
394
+ Explanation
395
+ ===========
396
+
397
+ The length of the tendon when the musculotendon is in its unloaded
398
+ state. In a rigid tendon model the tendon length is the tendon slack
399
+ length. In all musculotendon models, tendon slack length is used to
400
+ normalize tendon length to give
401
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
402
+
403
+ The alias ``l_T_slack`` can also be used to access the same attribute.
404
+
405
+ """
406
+ return self._l_T_slack
407
+
408
+ @property
409
+ def l_T_slack(self):
410
+ r"""Symbol or value corresponding to the tendon slack length constant.
411
+
412
+ Explanation
413
+ ===========
414
+
415
+ The length of the tendon when the musculotendon is in its unloaded
416
+ state. In a rigid tendon model the tendon length is the tendon slack
417
+ length. In all musculotendon models, tendon slack length is used to
418
+ normalize tendon length to give
419
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
420
+
421
+ The alias ``tendon_slack_length`` can also be used to access the same
422
+ attribute.
423
+
424
+ """
425
+ return self._l_T_slack
426
+
427
+ @property
428
+ def peak_isometric_force(self):
429
+ r"""Symbol or value corresponding to the peak isometric force constant.
430
+
431
+ Explanation
432
+ ===========
433
+
434
+ The maximum force that the muscle fiber can produce when it is
435
+ undergoing an isometric contraction (no lengthening velocity). In all
436
+ musculotendon models, peak isometric force is used to normalized tendon
437
+ and muscle fiber force to give
438
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
439
+
440
+ The alias ``F_M_max`` can also be used to access the same attribute.
441
+
442
+ """
443
+ return self._F_M_max
444
+
445
+ @property
446
+ def F_M_max(self):
447
+ r"""Symbol or value corresponding to the peak isometric force constant.
448
+
449
+ Explanation
450
+ ===========
451
+
452
+ The maximum force that the muscle fiber can produce when it is
453
+ undergoing an isometric contraction (no lengthening velocity). In all
454
+ musculotendon models, peak isometric force is used to normalized tendon
455
+ and muscle fiber force to give
456
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
457
+
458
+ The alias ``peak_isometric_force`` can also be used to access the same
459
+ attribute.
460
+
461
+ """
462
+ return self._F_M_max
463
+
464
+ @property
465
+ def optimal_fiber_length(self):
466
+ r"""Symbol or value corresponding to the optimal fiber length constant.
467
+
468
+ Explanation
469
+ ===========
470
+
471
+ The muscle fiber length at which the muscle fibers produce no passive
472
+ force and their maximum active force. In all musculotendon models,
473
+ optimal fiber length is used to normalize muscle fiber length to give
474
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
475
+
476
+ The alias ``l_M_opt`` can also be used to access the same attribute.
477
+
478
+ """
479
+ return self._l_M_opt
480
+
481
+ @property
482
+ def l_M_opt(self):
483
+ r"""Symbol or value corresponding to the optimal fiber length constant.
484
+
485
+ Explanation
486
+ ===========
487
+
488
+ The muscle fiber length at which the muscle fibers produce no passive
489
+ force and their maximum active force. In all musculotendon models,
490
+ optimal fiber length is used to normalize muscle fiber length to give
491
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
492
+
493
+ The alias ``optimal_fiber_length`` can also be used to access the same
494
+ attribute.
495
+
496
+ """
497
+ return self._l_M_opt
498
+
499
+ @property
500
+ def maximal_fiber_velocity(self):
501
+ r"""Symbol or value corresponding to the maximal fiber velocity constant.
502
+
503
+ Explanation
504
+ ===========
505
+
506
+ The fiber velocity at which, during muscle fiber shortening, the muscle
507
+ fibers are unable to produce any active force. In all musculotendon
508
+ models, maximal fiber velocity is used to normalize muscle fiber
509
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
510
+
511
+ The alias ``v_M_max`` can also be used to access the same attribute.
512
+
513
+ """
514
+ return self._v_M_max
515
+
516
+ @property
517
+ def v_M_max(self):
518
+ r"""Symbol or value corresponding to the maximal fiber velocity constant.
519
+
520
+ Explanation
521
+ ===========
522
+
523
+ The fiber velocity at which, during muscle fiber shortening, the muscle
524
+ fibers are unable to produce any active force. In all musculotendon
525
+ models, maximal fiber velocity is used to normalize muscle fiber
526
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
527
+
528
+ The alias ``maximal_fiber_velocity`` can also be used to access the same
529
+ attribute.
530
+
531
+ """
532
+ return self._v_M_max
533
+
534
+ @property
535
+ def optimal_pennation_angle(self):
536
+ """Symbol or value corresponding to the optimal pennation angle
537
+ constant.
538
+
539
+ Explanation
540
+ ===========
541
+
542
+ The pennation angle when muscle fiber length equals the optimal fiber
543
+ length.
544
+
545
+ The alias ``alpha_opt`` can also be used to access the same attribute.
546
+
547
+ """
548
+ return self._alpha_opt
549
+
550
+ @property
551
+ def alpha_opt(self):
552
+ """Symbol or value corresponding to the optimal pennation angle
553
+ constant.
554
+
555
+ Explanation
556
+ ===========
557
+
558
+ The pennation angle when muscle fiber length equals the optimal fiber
559
+ length.
560
+
561
+ The alias ``optimal_pennation_angle`` can also be used to access the
562
+ same attribute.
563
+
564
+ """
565
+ return self._alpha_opt
566
+
567
+ @property
568
+ def fiber_damping_coefficient(self):
569
+ """Symbol or value corresponding to the fiber damping coefficient
570
+ constant.
571
+
572
+ Explanation
573
+ ===========
574
+
575
+ The coefficient of damping to be used in the damping element in the
576
+ muscle fiber model.
577
+
578
+ The alias ``beta`` can also be used to access the same attribute.
579
+
580
+ """
581
+ return self._beta
582
+
583
+ @property
584
+ def beta(self):
585
+ """Symbol or value corresponding to the fiber damping coefficient
586
+ constant.
587
+
588
+ Explanation
589
+ ===========
590
+
591
+ The coefficient of damping to be used in the damping element in the
592
+ muscle fiber model.
593
+
594
+ The alias ``fiber_damping_coefficient`` can also be used to access the
595
+ same attribute.
596
+
597
+ """
598
+ return self._beta
599
+
600
+ @property
601
+ def activation_dynamics(self):
602
+ """Activation dynamics model governing this musculotendon's activation.
603
+
604
+ Explanation
605
+ ===========
606
+
607
+ Returns the instance of a subclass of ``ActivationBase`` that governs
608
+ the relationship between excitation and activation that is used to
609
+ represent the activation dynamics of this musculotendon.
610
+
611
+ """
612
+ return self._activation_dynamics
613
+
614
+ @property
615
+ def excitation(self):
616
+ """Dynamic symbol representing excitation.
617
+
618
+ Explanation
619
+ ===========
620
+
621
+ The alias ``e`` can also be used to access the same attribute.
622
+
623
+ """
624
+ return self._activation_dynamics._e
625
+
626
+ @property
627
+ def e(self):
628
+ """Dynamic symbol representing excitation.
629
+
630
+ Explanation
631
+ ===========
632
+
633
+ The alias ``excitation`` can also be used to access the same attribute.
634
+
635
+ """
636
+ return self._activation_dynamics._e
637
+
638
+ @property
639
+ def activation(self):
640
+ """Dynamic symbol representing activation.
641
+
642
+ Explanation
643
+ ===========
644
+
645
+ The alias ``a`` can also be used to access the same attribute.
646
+
647
+ """
648
+ return self._activation_dynamics._a
649
+
650
+ @property
651
+ def a(self):
652
+ """Dynamic symbol representing activation.
653
+
654
+ Explanation
655
+ ===========
656
+
657
+ The alias ``activation`` can also be used to access the same attribute.
658
+
659
+ """
660
+ return self._activation_dynamics._a
661
+
662
+ @property
663
+ def musculotendon_dynamics(self):
664
+ """The choice of rigid or type of elastic tendon musculotendon dynamics.
665
+
666
+ Explanation
667
+ ===========
668
+
669
+ The formulation of musculotendon dynamics that should be used
670
+ internally, i.e. rigid or elastic tendon model, the choice of
671
+ musculotendon state etc. This must be a member of the integer
672
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
673
+ to a member. To use a rigid tendon formulation, set this to
674
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
675
+ which will be cast to the enumeration member). There are four possible
676
+ formulations for an elastic tendon model. To use an explicit formulation
677
+ with the fiber length as the state, set this to
678
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
679
+ ``1``). To use an explicit formulation with the tendon force as the
680
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
681
+ (or the integer value ``2``). To use an implicit formulation with the
682
+ fiber length as the state, set this to
683
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
684
+ ``3``). To use an implicit formulation with the tendon force as the
685
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
686
+ (or the integer value ``4``). The default is
687
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
688
+ tendon formulation.
689
+
690
+ """
691
+ return self._musculotendon_dynamics
692
+
693
+ def _rigid_tendon_musculotendon_dynamics(self):
694
+ """Rigid tendon musculotendon."""
695
+ self._l_MT = self.pathway.length
696
+ self._v_MT = self.pathway.extension_velocity
697
+ self._l_T = self._l_T_slack
698
+ self._l_T_tilde = Integer(1)
699
+ self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
700
+ self._l_M_tilde = self._l_M/self._l_M_opt
701
+ self._v_M = self._v_MT*(self._l_MT - self._l_T_slack)/self._l_M
702
+ self._v_M_tilde = self._v_M/self._v_M_max
703
+ if self._with_defaults:
704
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
705
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
706
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
707
+ self._fv_M = self.curves.fiber_force_velocity.with_defaults(self._v_M_tilde)
708
+ else:
709
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
710
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
711
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
712
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
713
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
714
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
715
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
716
+ self._fv_M = self.curves.fiber_force_velocity(self._v_M_tilde, *fv_M_constants)
717
+ self._F_M_tilde = self.a*self._fl_M_act*self._fv_M + self._fl_M_pas + self._beta*self._v_M_tilde
718
+ self._F_T_tilde = self._F_M_tilde
719
+ self._F_M = self._F_M_tilde*self._F_M_max
720
+ self._cos_alpha = cos(self._alpha_opt)
721
+ self._F_T = self._F_M*self._cos_alpha
722
+
723
+ # Containers
724
+ self._state_vars = zeros(0, 1)
725
+ self._input_vars = zeros(0, 1)
726
+ self._state_eqns = zeros(0, 1)
727
+ self._curve_constants = Matrix(
728
+ fl_T_constants
729
+ + fl_M_pas_constants
730
+ + fl_M_act_constants
731
+ + fv_M_constants
732
+ ) if not self._with_defaults else zeros(0, 1)
733
+
734
+ def _fiber_length_explicit_musculotendon_dynamics(self):
735
+ """Elastic tendon musculotendon using `l_M_tilde` as a state."""
736
+ self._l_M_tilde = dynamicsymbols(f'l_M_tilde_{self.name}')
737
+ self._l_MT = self.pathway.length
738
+ self._v_MT = self.pathway.extension_velocity
739
+ self._l_M = self._l_M_tilde*self._l_M_opt
740
+ self._l_T = self._l_MT - sqrt(self._l_M**2 - (self._l_M_opt*sin(self._alpha_opt))**2)
741
+ self._l_T_tilde = self._l_T/self._l_T_slack
742
+ self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
743
+ if self._with_defaults:
744
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
745
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
746
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
747
+ else:
748
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
749
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
750
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
751
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
752
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
753
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
754
+ self._F_T_tilde = self._fl_T
755
+ self._F_T = self._F_T_tilde*self._F_M_max
756
+ self._F_M = self._F_T/self._cos_alpha
757
+ self._F_M_tilde = self._F_M/self._F_M_max
758
+ self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
759
+ if self._with_defaults:
760
+ self._v_M_tilde = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
761
+ else:
762
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
763
+ self._v_M_tilde = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
764
+ self._dl_M_tilde_dt = (self._v_M_max/self._l_M_opt)*self._v_M_tilde
765
+
766
+ self._state_vars = Matrix([self._l_M_tilde])
767
+ self._input_vars = zeros(0, 1)
768
+ self._state_eqns = Matrix([self._dl_M_tilde_dt])
769
+ self._curve_constants = Matrix(
770
+ fl_T_constants
771
+ + fl_M_pas_constants
772
+ + fl_M_act_constants
773
+ + fv_M_constants
774
+ ) if not self._with_defaults else zeros(0, 1)
775
+
776
+ def _tendon_force_explicit_musculotendon_dynamics(self):
777
+ """Elastic tendon musculotendon using `F_T_tilde` as a state."""
778
+ self._F_T_tilde = dynamicsymbols(f'F_T_tilde_{self.name}')
779
+ self._l_MT = self.pathway.length
780
+ self._v_MT = self.pathway.extension_velocity
781
+ self._fl_T = self._F_T_tilde
782
+ if self._with_defaults:
783
+ self._fl_T_inv = self.curves.tendon_force_length_inverse.with_defaults(self._fl_T)
784
+ else:
785
+ fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
786
+ self._fl_T_inv = self.curves.tendon_force_length_inverse(self._fl_T, *fl_T_constants)
787
+ self._l_T_tilde = self._fl_T_inv
788
+ self._l_T = self._l_T_tilde*self._l_T_slack
789
+ self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
790
+ self._l_M_tilde = self._l_M/self._l_M_opt
791
+ if self._with_defaults:
792
+ self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
793
+ self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
794
+ else:
795
+ fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
796
+ self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
797
+ fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
798
+ self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
799
+ self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
800
+ self._F_T = self._F_T_tilde*self._F_M_max
801
+ self._F_M = self._F_T/self._cos_alpha
802
+ self._F_M_tilde = self._F_M/self._F_M_max
803
+ self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
804
+ if self._with_defaults:
805
+ self._fv_M_inv = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
806
+ else:
807
+ fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
808
+ self._fv_M_inv = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
809
+ self._v_M_tilde = self._fv_M_inv
810
+ self._v_M = self._v_M_tilde*self._v_M_max
811
+ self._v_T = self._v_MT - (self._v_M/self._cos_alpha)
812
+ self._v_T_tilde = self._v_T/self._l_T_slack
813
+ if self._with_defaults:
814
+ self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
815
+ else:
816
+ self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
817
+ self._dF_T_tilde_dt = self._fl_T.diff(dynamicsymbols._t).subs({self._l_T_tilde.diff(dynamicsymbols._t): self._v_T_tilde})
818
+
819
+ self._state_vars = Matrix([self._F_T_tilde])
820
+ self._input_vars = zeros(0, 1)
821
+ self._state_eqns = Matrix([self._dF_T_tilde_dt])
822
+ self._curve_constants = Matrix(
823
+ fl_T_constants
824
+ + fl_M_pas_constants
825
+ + fl_M_act_constants
826
+ + fv_M_constants
827
+ ) if not self._with_defaults else zeros(0, 1)
828
+
829
+ def _fiber_length_implicit_musculotendon_dynamics(self):
830
+ raise NotImplementedError
831
+
832
+ def _tendon_force_implicit_musculotendon_dynamics(self):
833
+ raise NotImplementedError
834
+
835
+ @property
836
+ def state_vars(self):
837
+ """Ordered column matrix of functions of time that represent the state
838
+ variables.
839
+
840
+ Explanation
841
+ ===========
842
+
843
+ The alias ``x`` can also be used to access the same attribute.
844
+
845
+ """
846
+ state_vars = [self._state_vars]
847
+ for child in self._child_objects:
848
+ state_vars.append(child.state_vars)
849
+ return Matrix.vstack(*state_vars)
850
+
851
+ @property
852
+ def x(self):
853
+ """Ordered column matrix of functions of time that represent the state
854
+ variables.
855
+
856
+ Explanation
857
+ ===========
858
+
859
+ The alias ``state_vars`` can also be used to access the same attribute.
860
+
861
+ """
862
+ state_vars = [self._state_vars]
863
+ for child in self._child_objects:
864
+ state_vars.append(child.state_vars)
865
+ return Matrix.vstack(*state_vars)
866
+
867
+ @property
868
+ def input_vars(self):
869
+ """Ordered column matrix of functions of time that represent the input
870
+ variables.
871
+
872
+ Explanation
873
+ ===========
874
+
875
+ The alias ``r`` can also be used to access the same attribute.
876
+
877
+ """
878
+ input_vars = [self._input_vars]
879
+ for child in self._child_objects:
880
+ input_vars.append(child.input_vars)
881
+ return Matrix.vstack(*input_vars)
882
+
883
+ @property
884
+ def r(self):
885
+ """Ordered column matrix of functions of time that represent the input
886
+ variables.
887
+
888
+ Explanation
889
+ ===========
890
+
891
+ The alias ``input_vars`` can also be used to access the same attribute.
892
+
893
+ """
894
+ input_vars = [self._input_vars]
895
+ for child in self._child_objects:
896
+ input_vars.append(child.input_vars)
897
+ return Matrix.vstack(*input_vars)
898
+
899
+ @property
900
+ def constants(self):
901
+ """Ordered column matrix of non-time varying symbols present in ``M``
902
+ and ``F``.
903
+
904
+ Explanation
905
+ ===========
906
+
907
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
908
+ has been used instead of ``Symbol`` for a constant then that attribute
909
+ will not be included in the matrix returned by this property. This is
910
+ because the primary use of this property attribute is to provide an
911
+ ordered sequence of the still-free symbols that require numeric values
912
+ during code generation.
913
+
914
+ The alias ``p`` can also be used to access the same attribute.
915
+
916
+ """
917
+ musculotendon_constants = [
918
+ self._l_T_slack,
919
+ self._F_M_max,
920
+ self._l_M_opt,
921
+ self._v_M_max,
922
+ self._alpha_opt,
923
+ self._beta,
924
+ ]
925
+ musculotendon_constants = [
926
+ c for c in musculotendon_constants if not c.is_number
927
+ ]
928
+ constants = [
929
+ Matrix(musculotendon_constants)
930
+ if musculotendon_constants
931
+ else zeros(0, 1)
932
+ ]
933
+ for child in self._child_objects:
934
+ constants.append(child.constants)
935
+ constants.append(self._curve_constants)
936
+ return Matrix.vstack(*constants)
937
+
938
+ @property
939
+ def p(self):
940
+ """Ordered column matrix of non-time varying symbols present in ``M``
941
+ and ``F``.
942
+
943
+ Explanation
944
+ ===========
945
+
946
+ Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
947
+ has been used instead of ``Symbol`` for a constant then that attribute
948
+ will not be included in the matrix returned by this property. This is
949
+ because the primary use of this property attribute is to provide an
950
+ ordered sequence of the still-free symbols that require numeric values
951
+ during code generation.
952
+
953
+ The alias ``constants`` can also be used to access the same attribute.
954
+
955
+ """
956
+ musculotendon_constants = [
957
+ self._l_T_slack,
958
+ self._F_M_max,
959
+ self._l_M_opt,
960
+ self._v_M_max,
961
+ self._alpha_opt,
962
+ self._beta,
963
+ ]
964
+ musculotendon_constants = [
965
+ c for c in musculotendon_constants if not c.is_number
966
+ ]
967
+ constants = [
968
+ Matrix(musculotendon_constants)
969
+ if musculotendon_constants
970
+ else zeros(0, 1)
971
+ ]
972
+ for child in self._child_objects:
973
+ constants.append(child.constants)
974
+ constants.append(self._curve_constants)
975
+ return Matrix.vstack(*constants)
976
+
977
+ @property
978
+ def M(self):
979
+ """Ordered square matrix of coefficients on the LHS of ``M x' = F``.
980
+
981
+ Explanation
982
+ ===========
983
+
984
+ The square matrix that forms part of the LHS of the linear system of
985
+ ordinary differential equations governing the activation dynamics:
986
+
987
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
988
+
989
+ As zeroth-order activation dynamics have no state variables, this
990
+ linear system has dimension 0 and therefore ``M`` is an empty square
991
+ ``Matrix`` with shape (0, 0).
992
+
993
+ """
994
+ M = [eye(len(self._state_vars))]
995
+ for child in self._child_objects:
996
+ M.append(child.M)
997
+ return diag(*M)
998
+
999
+ @property
1000
+ def F(self):
1001
+ """Ordered column matrix of equations on the RHS of ``M x' = F``.
1002
+
1003
+ Explanation
1004
+ ===========
1005
+
1006
+ The column matrix that forms the RHS of the linear system of ordinary
1007
+ differential equations governing the activation dynamics:
1008
+
1009
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
1010
+
1011
+ As zeroth-order activation dynamics have no state variables, this
1012
+ linear system has dimension 0 and therefore ``F`` is an empty column
1013
+ ``Matrix`` with shape (0, 1).
1014
+
1015
+ """
1016
+ F = [self._state_eqns]
1017
+ for child in self._child_objects:
1018
+ F.append(child.F)
1019
+ return Matrix.vstack(*F)
1020
+
1021
+ def rhs(self):
1022
+ """Ordered column matrix of equations for the solution of ``M x' = F``.
1023
+
1024
+ Explanation
1025
+ ===========
1026
+
1027
+ The solution to the linear system of ordinary differential equations
1028
+ governing the activation dynamics:
1029
+
1030
+ ``M(x, r, t, p) x' = F(x, r, t, p)``.
1031
+
1032
+ As zeroth-order activation dynamics have no state variables, this
1033
+ linear has dimension 0 and therefore this method returns an empty
1034
+ column ``Matrix`` with shape (0, 1).
1035
+
1036
+ """
1037
+ is_explicit = (
1038
+ MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1039
+ MusculotendonFormulation.TENDON_FORCE_EXPLICIT,
1040
+ )
1041
+ if self.musculotendon_dynamics is MusculotendonFormulation.RIGID_TENDON:
1042
+ child_rhs = [child.rhs() for child in self._child_objects]
1043
+ return Matrix.vstack(*child_rhs)
1044
+ elif self.musculotendon_dynamics in is_explicit:
1045
+ rhs = self._state_eqns
1046
+ child_rhs = [child.rhs() for child in self._child_objects]
1047
+ return Matrix.vstack(rhs, *child_rhs)
1048
+ return self.M.solve(self.F)
1049
+
1050
+ def __repr__(self):
1051
+ """Returns a string representation to reinstantiate the model."""
1052
+ return (
1053
+ f'{self.__class__.__name__}({self.name!r}, '
1054
+ f'pathway={self.pathway!r}, '
1055
+ f'activation_dynamics={self.activation_dynamics!r}, '
1056
+ f'musculotendon_dynamics={self.musculotendon_dynamics}, '
1057
+ f'tendon_slack_length={self._l_T_slack!r}, '
1058
+ f'peak_isometric_force={self._F_M_max!r}, '
1059
+ f'optimal_fiber_length={self._l_M_opt!r}, '
1060
+ f'maximal_fiber_velocity={self._v_M_max!r}, '
1061
+ f'optimal_pennation_angle={self._alpha_opt!r}, '
1062
+ f'fiber_damping_coefficient={self._beta!r})'
1063
+ )
1064
+
1065
+ def __str__(self):
1066
+ """Returns a string representation of the expression for musculotendon
1067
+ force."""
1068
+ return str(self.force)
1069
+
1070
+
1071
+ class MusculotendonDeGroote2016(MusculotendonBase):
1072
+ r"""Musculotendon model using the curves of De Groote et al., 2016 [1]_.
1073
+
1074
+ Examples
1075
+ ========
1076
+
1077
+ This class models the musculotendon actuator parametrized by the
1078
+ characteristic curves described in De Groote et al., 2016 [1]_. Like all
1079
+ musculotendon models in SymPy's biomechanics module, it requires a pathway
1080
+ to define its line of action. We'll begin by creating a simple
1081
+ ``LinearPathway`` between two points that our musculotendon will follow.
1082
+ We'll create a point ``O`` to represent the musculotendon's origin and
1083
+ another ``I`` to represent its insertion.
1084
+
1085
+ >>> from sympy import symbols
1086
+ >>> from sympy.physics.mechanics import (LinearPathway, Point,
1087
+ ... ReferenceFrame, dynamicsymbols)
1088
+
1089
+ >>> N = ReferenceFrame('N')
1090
+ >>> O, I = O, P = symbols('O, I', cls=Point)
1091
+ >>> q, u = dynamicsymbols('q, u', real=True)
1092
+ >>> I.set_pos(O, q*N.x)
1093
+ >>> O.set_vel(N, 0)
1094
+ >>> I.set_vel(N, u*N.x)
1095
+ >>> pathway = LinearPathway(O, I)
1096
+ >>> pathway.attachments
1097
+ (O, I)
1098
+ >>> pathway.length
1099
+ Abs(q(t))
1100
+ >>> pathway.extension_velocity
1101
+ sign(q(t))*Derivative(q(t), t)
1102
+
1103
+ A musculotendon also takes an instance of an activation dynamics model as
1104
+ this will be used to provide symbols for the activation in the formulation
1105
+ of the musculotendon dynamics. We'll use an instance of
1106
+ ``FirstOrderActivationDeGroote2016`` to represent first-order activation
1107
+ dynamics. Note that a single name argument needs to be provided as SymPy
1108
+ will use this as a suffix.
1109
+
1110
+ >>> from sympy.physics.biomechanics import FirstOrderActivationDeGroote2016
1111
+
1112
+ >>> activation = FirstOrderActivationDeGroote2016('muscle')
1113
+ >>> activation.x
1114
+ Matrix([[a_muscle(t)]])
1115
+ >>> activation.r
1116
+ Matrix([[e_muscle(t)]])
1117
+ >>> activation.p
1118
+ Matrix([
1119
+ [tau_a_muscle],
1120
+ [tau_d_muscle],
1121
+ [ b_muscle]])
1122
+ >>> activation.rhs()
1123
+ Matrix([[((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1124
+
1125
+ The musculotendon class requires symbols or values to be passed to represent
1126
+ the constants in the musculotendon dynamics. We'll use SymPy's ``symbols``
1127
+ function to create symbols for the maximum isometric force ``F_M_max``,
1128
+ optimal fiber length ``l_M_opt``, tendon slack length ``l_T_slack``, maximum
1129
+ fiber velocity ``v_M_max``, optimal pennation angle ``alpha_opt, and fiber
1130
+ damping coefficient ``beta``.
1131
+
1132
+ >>> F_M_max = symbols('F_M_max', real=True)
1133
+ >>> l_M_opt = symbols('l_M_opt', real=True)
1134
+ >>> l_T_slack = symbols('l_T_slack', real=True)
1135
+ >>> v_M_max = symbols('v_M_max', real=True)
1136
+ >>> alpha_opt = symbols('alpha_opt', real=True)
1137
+ >>> beta = symbols('beta', real=True)
1138
+
1139
+ We can then import the class ``MusculotendonDeGroote2016`` from the
1140
+ biomechanics module and create an instance by passing in the various objects
1141
+ we have previously instantiated. By default, a musculotendon model with
1142
+ rigid tendon musculotendon dynamics will be created.
1143
+
1144
+ >>> from sympy.physics.biomechanics import MusculotendonDeGroote2016
1145
+
1146
+ >>> rigid_tendon_muscle = MusculotendonDeGroote2016(
1147
+ ... 'muscle',
1148
+ ... pathway,
1149
+ ... activation,
1150
+ ... tendon_slack_length=l_T_slack,
1151
+ ... peak_isometric_force=F_M_max,
1152
+ ... optimal_fiber_length=l_M_opt,
1153
+ ... maximal_fiber_velocity=v_M_max,
1154
+ ... optimal_pennation_angle=alpha_opt,
1155
+ ... fiber_damping_coefficient=beta,
1156
+ ... )
1157
+
1158
+ We can inspect the various properties of the musculotendon, including
1159
+ getting the symbolic expression describing the force it produces using its
1160
+ ``force`` attribute.
1161
+
1162
+ >>> rigid_tendon_muscle.force
1163
+ -F_M_max*(beta*(-l_T_slack + Abs(q(t)))*sign(q(t))*Derivative(q(t), t)...
1164
+
1165
+ When we created the musculotendon object, we passed in an instance of an
1166
+ activation dynamics object that governs the activation within the
1167
+ musculotendon. SymPy makes a design choice here that the activation dynamics
1168
+ instance will be treated as a child object of the musculotendon dynamics.
1169
+ Therefore, if we want to inspect the state and input variables associated
1170
+ with the musculotendon model, we will also be returned the state and input
1171
+ variables associated with the child object, or the activation dynamics in
1172
+ this case. As the musculotendon model that we created here uses rigid tendon
1173
+ dynamics, no additional states or inputs relating to the musculotendon are
1174
+ introduces. Consequently, the model has a single state associated with it,
1175
+ the activation, and a single input associated with it, the excitation. The
1176
+ states and inputs can be inspected using the ``x`` and ``r`` attributes
1177
+ respectively. Note that both ``x`` and ``r`` have the alias attributes of
1178
+ ``state_vars`` and ``input_vars``.
1179
+
1180
+ >>> rigid_tendon_muscle.x
1181
+ Matrix([[a_muscle(t)]])
1182
+ >>> rigid_tendon_muscle.r
1183
+ Matrix([[e_muscle(t)]])
1184
+
1185
+ To see which constants are symbolic in the musculotendon model, we can use
1186
+ the ``p`` or ``constants`` attribute. This returns a ``Matrix`` populated
1187
+ by the constants that are represented by a ``Symbol`` rather than a numeric
1188
+ value.
1189
+
1190
+ >>> rigid_tendon_muscle.p
1191
+ Matrix([
1192
+ [ l_T_slack],
1193
+ [ F_M_max],
1194
+ [ l_M_opt],
1195
+ [ v_M_max],
1196
+ [ alpha_opt],
1197
+ [ beta],
1198
+ [ tau_a_muscle],
1199
+ [ tau_d_muscle],
1200
+ [ b_muscle],
1201
+ [ c_0_fl_T_muscle],
1202
+ [ c_1_fl_T_muscle],
1203
+ [ c_2_fl_T_muscle],
1204
+ [ c_3_fl_T_muscle],
1205
+ [ c_0_fl_M_pas_muscle],
1206
+ [ c_1_fl_M_pas_muscle],
1207
+ [ c_0_fl_M_act_muscle],
1208
+ [ c_1_fl_M_act_muscle],
1209
+ [ c_2_fl_M_act_muscle],
1210
+ [ c_3_fl_M_act_muscle],
1211
+ [ c_4_fl_M_act_muscle],
1212
+ [ c_5_fl_M_act_muscle],
1213
+ [ c_6_fl_M_act_muscle],
1214
+ [ c_7_fl_M_act_muscle],
1215
+ [ c_8_fl_M_act_muscle],
1216
+ [ c_9_fl_M_act_muscle],
1217
+ [c_10_fl_M_act_muscle],
1218
+ [c_11_fl_M_act_muscle],
1219
+ [ c_0_fv_M_muscle],
1220
+ [ c_1_fv_M_muscle],
1221
+ [ c_2_fv_M_muscle],
1222
+ [ c_3_fv_M_muscle]])
1223
+
1224
+ Finally, we can call the ``rhs`` method to return a ``Matrix`` that
1225
+ contains as its elements the righthand side of the ordinary differential
1226
+ equations corresponding to each of the musculotendon's states. Like the
1227
+ method with the same name on the ``Method`` classes in SymPy's mechanics
1228
+ module, this returns a column vector where the number of rows corresponds to
1229
+ the number of states. For our example here, we have a single state, the
1230
+ dynamic symbol ``a_muscle(t)``, so the returned value is a 1-by-1
1231
+ ``Matrix``.
1232
+
1233
+ >>> rigid_tendon_muscle.rhs()
1234
+ Matrix([[((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1235
+
1236
+ The musculotendon class supports elastic tendon musculotendon models in
1237
+ addition to rigid tendon ones. You can choose to either use the fiber length
1238
+ or tendon force as an additional state. You can also specify whether an
1239
+ explicit or implicit formulation should be used. To select a formulation,
1240
+ pass a member of the ``MusculotendonFormulation`` enumeration to the
1241
+ ``musculotendon_dynamics`` parameter when calling the constructor. This
1242
+ enumeration is an ``IntEnum``, so you can also pass an integer, however it
1243
+ is recommended to use the enumeration as it is clearer which formulation you
1244
+ are actually selecting. Below, we'll use the ``FIBER_LENGTH_EXPLICIT``
1245
+ member to create a musculotendon with an elastic tendon that will use the
1246
+ (normalized) muscle fiber length as an additional state and will produce
1247
+ the governing ordinary differential equation in explicit form.
1248
+
1249
+ >>> from sympy.physics.biomechanics import MusculotendonFormulation
1250
+
1251
+ >>> elastic_tendon_muscle = MusculotendonDeGroote2016(
1252
+ ... 'muscle',
1253
+ ... pathway,
1254
+ ... activation,
1255
+ ... musculotendon_dynamics=MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1256
+ ... tendon_slack_length=l_T_slack,
1257
+ ... peak_isometric_force=F_M_max,
1258
+ ... optimal_fiber_length=l_M_opt,
1259
+ ... maximal_fiber_velocity=v_M_max,
1260
+ ... optimal_pennation_angle=alpha_opt,
1261
+ ... fiber_damping_coefficient=beta,
1262
+ ... )
1263
+
1264
+ >>> elastic_tendon_muscle.force
1265
+ -F_M_max*TendonForceLengthDeGroote2016((-sqrt(l_M_opt**2*...
1266
+ >>> elastic_tendon_muscle.x
1267
+ Matrix([
1268
+ [l_M_tilde_muscle(t)],
1269
+ [ a_muscle(t)]])
1270
+ >>> elastic_tendon_muscle.r
1271
+ Matrix([[e_muscle(t)]])
1272
+ >>> elastic_tendon_muscle.p
1273
+ Matrix([
1274
+ [ l_T_slack],
1275
+ [ F_M_max],
1276
+ [ l_M_opt],
1277
+ [ v_M_max],
1278
+ [ alpha_opt],
1279
+ [ beta],
1280
+ [ tau_a_muscle],
1281
+ [ tau_d_muscle],
1282
+ [ b_muscle],
1283
+ [ c_0_fl_T_muscle],
1284
+ [ c_1_fl_T_muscle],
1285
+ [ c_2_fl_T_muscle],
1286
+ [ c_3_fl_T_muscle],
1287
+ [ c_0_fl_M_pas_muscle],
1288
+ [ c_1_fl_M_pas_muscle],
1289
+ [ c_0_fl_M_act_muscle],
1290
+ [ c_1_fl_M_act_muscle],
1291
+ [ c_2_fl_M_act_muscle],
1292
+ [ c_3_fl_M_act_muscle],
1293
+ [ c_4_fl_M_act_muscle],
1294
+ [ c_5_fl_M_act_muscle],
1295
+ [ c_6_fl_M_act_muscle],
1296
+ [ c_7_fl_M_act_muscle],
1297
+ [ c_8_fl_M_act_muscle],
1298
+ [ c_9_fl_M_act_muscle],
1299
+ [c_10_fl_M_act_muscle],
1300
+ [c_11_fl_M_act_muscle],
1301
+ [ c_0_fv_M_muscle],
1302
+ [ c_1_fv_M_muscle],
1303
+ [ c_2_fv_M_muscle],
1304
+ [ c_3_fv_M_muscle]])
1305
+ >>> elastic_tendon_muscle.rhs()
1306
+ Matrix([
1307
+ [v_M_max*FiberForceVelocityInverseDeGroote2016((l_M_opt*...],
1308
+ [ ((1/2 - tanh(b_muscle*(-a_muscle(t) + e_muscle(t)))/2)*(3*...]])
1309
+
1310
+ It is strongly recommended to use the alternate ``with_defaults``
1311
+ constructor when creating an instance because this will ensure that the
1312
+ published constants are used in the musculotendon characteristic curves.
1313
+
1314
+ >>> elastic_tendon_muscle = MusculotendonDeGroote2016.with_defaults(
1315
+ ... 'muscle',
1316
+ ... pathway,
1317
+ ... activation,
1318
+ ... musculotendon_dynamics=MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
1319
+ ... tendon_slack_length=l_T_slack,
1320
+ ... peak_isometric_force=F_M_max,
1321
+ ... optimal_fiber_length=l_M_opt,
1322
+ ... )
1323
+
1324
+ >>> elastic_tendon_muscle.x
1325
+ Matrix([
1326
+ [l_M_tilde_muscle(t)],
1327
+ [ a_muscle(t)]])
1328
+ >>> elastic_tendon_muscle.r
1329
+ Matrix([[e_muscle(t)]])
1330
+ >>> elastic_tendon_muscle.p
1331
+ Matrix([
1332
+ [ l_T_slack],
1333
+ [ F_M_max],
1334
+ [ l_M_opt],
1335
+ [tau_a_muscle],
1336
+ [tau_d_muscle],
1337
+ [ b_muscle]])
1338
+
1339
+ Parameters
1340
+ ==========
1341
+
1342
+ name : str
1343
+ The name identifier associated with the musculotendon. This name is used
1344
+ as a suffix when automatically generated symbols are instantiated. It
1345
+ must be a string of nonzero length.
1346
+ pathway : PathwayBase
1347
+ The pathway that the actuator follows. This must be an instance of a
1348
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
1349
+ activation_dynamics : ActivationBase
1350
+ The activation dynamics that will be modeled within the musculotendon.
1351
+ This must be an instance of a concrete subclass of ``ActivationBase``,
1352
+ e.g. ``FirstOrderActivationDeGroote2016``.
1353
+ musculotendon_dynamics : MusculotendonFormulation | int
1354
+ The formulation of musculotendon dynamics that should be used
1355
+ internally, i.e. rigid or elastic tendon model, the choice of
1356
+ musculotendon state etc. This must be a member of the integer
1357
+ enumeration ``MusculotendonFormulation`` or an integer that can be cast
1358
+ to a member. To use a rigid tendon formulation, set this to
1359
+ ``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
1360
+ which will be cast to the enumeration member). There are four possible
1361
+ formulations for an elastic tendon model. To use an explicit formulation
1362
+ with the fiber length as the state, set this to
1363
+ ``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
1364
+ ``1``). To use an explicit formulation with the tendon force as the
1365
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
1366
+ (or the integer value ``2``). To use an implicit formulation with the
1367
+ fiber length as the state, set this to
1368
+ ``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
1369
+ ``3``). To use an implicit formulation with the tendon force as the
1370
+ state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
1371
+ (or the integer value ``4``). The default is
1372
+ ``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
1373
+ tendon formulation.
1374
+ tendon_slack_length : Expr | None
1375
+ The length of the tendon when the musculotendon is in its unloaded
1376
+ state. In a rigid tendon model the tendon length is the tendon slack
1377
+ length. In all musculotendon models, tendon slack length is used to
1378
+ normalize tendon length to give
1379
+ :math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
1380
+ peak_isometric_force : Expr | None
1381
+ The maximum force that the muscle fiber can produce when it is
1382
+ undergoing an isometric contraction (no lengthening velocity). In all
1383
+ musculotendon models, peak isometric force is used to normalized tendon
1384
+ and muscle fiber force to give
1385
+ :math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
1386
+ optimal_fiber_length : Expr | None
1387
+ The muscle fiber length at which the muscle fibers produce no passive
1388
+ force and their maximum active force. In all musculotendon models,
1389
+ optimal fiber length is used to normalize muscle fiber length to give
1390
+ :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
1391
+ maximal_fiber_velocity : Expr | None
1392
+ The fiber velocity at which, during muscle fiber shortening, the muscle
1393
+ fibers are unable to produce any active force. In all musculotendon
1394
+ models, maximal fiber velocity is used to normalize muscle fiber
1395
+ extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
1396
+ optimal_pennation_angle : Expr | None
1397
+ The pennation angle when muscle fiber length equals the optimal fiber
1398
+ length.
1399
+ fiber_damping_coefficient : Expr | None
1400
+ The coefficient of damping to be used in the damping element in the
1401
+ muscle fiber model.
1402
+ with_defaults : bool
1403
+ Whether ``with_defaults`` alternate constructors should be used when
1404
+ automatically constructing child classes. Default is ``False``.
1405
+
1406
+ References
1407
+ ==========
1408
+
1409
+ .. [1] De Groote, F., Kinney, A. L., Rao, A. V., & Fregly, B. J., Evaluation
1410
+ of direct collocation optimal control problem formulations for
1411
+ solving the muscle redundancy problem, Annals of biomedical
1412
+ engineering, 44(10), (2016) pp. 2922-2936
1413
+
1414
+ """
1415
+
1416
+ curves = CharacteristicCurveCollection(
1417
+ tendon_force_length=TendonForceLengthDeGroote2016,
1418
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1419
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1420
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1421
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1422
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1423
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1424
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_activation.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.activation.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy import Symbol
6
+ from sympy.core.numbers import Float, Integer, Rational
7
+ from sympy.functions.elementary.hyperbolic import tanh
8
+ from sympy.matrices import Matrix
9
+ from sympy.matrices.dense import zeros
10
+ from sympy.physics.mechanics import dynamicsymbols
11
+ from sympy.physics.biomechanics import (
12
+ ActivationBase,
13
+ FirstOrderActivationDeGroote2016,
14
+ ZerothOrderActivation,
15
+ )
16
+ from sympy.physics.biomechanics._mixin import _NamedMixin
17
+ from sympy.simplify.simplify import simplify
18
+
19
+
20
+ class TestZerothOrderActivation:
21
+
22
+ @staticmethod
23
+ def test_class():
24
+ assert issubclass(ZerothOrderActivation, ActivationBase)
25
+ assert issubclass(ZerothOrderActivation, _NamedMixin)
26
+ assert ZerothOrderActivation.__name__ == 'ZerothOrderActivation'
27
+
28
+ @pytest.fixture(autouse=True)
29
+ def _zeroth_order_activation_fixture(self):
30
+ self.name = 'name'
31
+ self.e = dynamicsymbols('e_name')
32
+ self.instance = ZerothOrderActivation(self.name)
33
+
34
+ def test_instance(self):
35
+ instance = ZerothOrderActivation(self.name)
36
+ assert isinstance(instance, ZerothOrderActivation)
37
+
38
+ def test_with_defaults(self):
39
+ instance = ZerothOrderActivation.with_defaults(self.name)
40
+ assert isinstance(instance, ZerothOrderActivation)
41
+ assert instance == ZerothOrderActivation(self.name)
42
+
43
+ def test_name(self):
44
+ assert hasattr(self.instance, 'name')
45
+ assert self.instance.name == self.name
46
+
47
+ def test_order(self):
48
+ assert hasattr(self.instance, 'order')
49
+ assert self.instance.order == 0
50
+
51
+ def test_excitation_attribute(self):
52
+ assert hasattr(self.instance, 'e')
53
+ assert hasattr(self.instance, 'excitation')
54
+ e_expected = dynamicsymbols('e_name')
55
+ assert self.instance.e == e_expected
56
+ assert self.instance.excitation == e_expected
57
+ assert self.instance.e is self.instance.excitation
58
+
59
+ def test_activation_attribute(self):
60
+ assert hasattr(self.instance, 'a')
61
+ assert hasattr(self.instance, 'activation')
62
+ a_expected = dynamicsymbols('e_name')
63
+ assert self.instance.a == a_expected
64
+ assert self.instance.activation == a_expected
65
+ assert self.instance.a is self.instance.activation is self.instance.e
66
+
67
+ def test_state_vars_attribute(self):
68
+ assert hasattr(self.instance, 'x')
69
+ assert hasattr(self.instance, 'state_vars')
70
+ assert self.instance.x == self.instance.state_vars
71
+ x_expected = zeros(0, 1)
72
+ assert self.instance.x == x_expected
73
+ assert self.instance.state_vars == x_expected
74
+ assert isinstance(self.instance.x, Matrix)
75
+ assert isinstance(self.instance.state_vars, Matrix)
76
+ assert self.instance.x.shape == (0, 1)
77
+ assert self.instance.state_vars.shape == (0, 1)
78
+
79
+ def test_input_vars_attribute(self):
80
+ assert hasattr(self.instance, 'r')
81
+ assert hasattr(self.instance, 'input_vars')
82
+ assert self.instance.r == self.instance.input_vars
83
+ r_expected = Matrix([self.e])
84
+ assert self.instance.r == r_expected
85
+ assert self.instance.input_vars == r_expected
86
+ assert isinstance(self.instance.r, Matrix)
87
+ assert isinstance(self.instance.input_vars, Matrix)
88
+ assert self.instance.r.shape == (1, 1)
89
+ assert self.instance.input_vars.shape == (1, 1)
90
+
91
+ def test_constants_attribute(self):
92
+ assert hasattr(self.instance, 'p')
93
+ assert hasattr(self.instance, 'constants')
94
+ assert self.instance.p == self.instance.constants
95
+ p_expected = zeros(0, 1)
96
+ assert self.instance.p == p_expected
97
+ assert self.instance.constants == p_expected
98
+ assert isinstance(self.instance.p, Matrix)
99
+ assert isinstance(self.instance.constants, Matrix)
100
+ assert self.instance.p.shape == (0, 1)
101
+ assert self.instance.constants.shape == (0, 1)
102
+
103
+ def test_M_attribute(self):
104
+ assert hasattr(self.instance, 'M')
105
+ M_expected = Matrix([])
106
+ assert self.instance.M == M_expected
107
+ assert isinstance(self.instance.M, Matrix)
108
+ assert self.instance.M.shape == (0, 0)
109
+
110
+ def test_F(self):
111
+ assert hasattr(self.instance, 'F')
112
+ F_expected = zeros(0, 1)
113
+ assert self.instance.F == F_expected
114
+ assert isinstance(self.instance.F, Matrix)
115
+ assert self.instance.F.shape == (0, 1)
116
+
117
+ def test_rhs(self):
118
+ assert hasattr(self.instance, 'rhs')
119
+ rhs_expected = zeros(0, 1)
120
+ rhs = self.instance.rhs()
121
+ assert rhs == rhs_expected
122
+ assert isinstance(rhs, Matrix)
123
+ assert rhs.shape == (0, 1)
124
+
125
+ def test_repr(self):
126
+ expected = 'ZerothOrderActivation(\'name\')'
127
+ assert repr(self.instance) == expected
128
+
129
+
130
+ class TestFirstOrderActivationDeGroote2016:
131
+
132
+ @staticmethod
133
+ def test_class():
134
+ assert issubclass(FirstOrderActivationDeGroote2016, ActivationBase)
135
+ assert issubclass(FirstOrderActivationDeGroote2016, _NamedMixin)
136
+ assert FirstOrderActivationDeGroote2016.__name__ == 'FirstOrderActivationDeGroote2016'
137
+
138
+ @pytest.fixture(autouse=True)
139
+ def _first_order_activation_de_groote_2016_fixture(self):
140
+ self.name = 'name'
141
+ self.e = dynamicsymbols('e_name')
142
+ self.a = dynamicsymbols('a_name')
143
+ self.tau_a = Symbol('tau_a')
144
+ self.tau_d = Symbol('tau_d')
145
+ self.b = Symbol('b')
146
+ self.instance = FirstOrderActivationDeGroote2016(
147
+ self.name,
148
+ self.tau_a,
149
+ self.tau_d,
150
+ self.b,
151
+ )
152
+
153
+ def test_instance(self):
154
+ instance = FirstOrderActivationDeGroote2016(self.name)
155
+ assert isinstance(instance, FirstOrderActivationDeGroote2016)
156
+
157
+ def test_with_defaults(self):
158
+ instance = FirstOrderActivationDeGroote2016.with_defaults(self.name)
159
+ assert isinstance(instance, FirstOrderActivationDeGroote2016)
160
+ assert instance.tau_a == Float('0.015')
161
+ assert instance.activation_time_constant == Float('0.015')
162
+ assert instance.tau_d == Float('0.060')
163
+ assert instance.deactivation_time_constant == Float('0.060')
164
+ assert instance.b == Float('10.0')
165
+ assert instance.smoothing_rate == Float('10.0')
166
+
167
+ def test_name(self):
168
+ assert hasattr(self.instance, 'name')
169
+ assert self.instance.name == self.name
170
+
171
+ def test_order(self):
172
+ assert hasattr(self.instance, 'order')
173
+ assert self.instance.order == 1
174
+
175
+ def test_excitation(self):
176
+ assert hasattr(self.instance, 'e')
177
+ assert hasattr(self.instance, 'excitation')
178
+ e_expected = dynamicsymbols('e_name')
179
+ assert self.instance.e == e_expected
180
+ assert self.instance.excitation == e_expected
181
+ assert self.instance.e is self.instance.excitation
182
+
183
+ def test_excitation_is_immutable(self):
184
+ with pytest.raises(AttributeError):
185
+ self.instance.e = None
186
+ with pytest.raises(AttributeError):
187
+ self.instance.excitation = None
188
+
189
+ def test_activation(self):
190
+ assert hasattr(self.instance, 'a')
191
+ assert hasattr(self.instance, 'activation')
192
+ a_expected = dynamicsymbols('a_name')
193
+ assert self.instance.a == a_expected
194
+ assert self.instance.activation == a_expected
195
+
196
+ def test_activation_is_immutable(self):
197
+ with pytest.raises(AttributeError):
198
+ self.instance.a = None
199
+ with pytest.raises(AttributeError):
200
+ self.instance.activation = None
201
+
202
+ @pytest.mark.parametrize(
203
+ 'tau_a, expected',
204
+ [
205
+ (None, Symbol('tau_a_name')),
206
+ (Symbol('tau_a'), Symbol('tau_a')),
207
+ (Float('0.015'), Float('0.015')),
208
+ ]
209
+ )
210
+ def test_activation_time_constant(self, tau_a, expected):
211
+ instance = FirstOrderActivationDeGroote2016(
212
+ 'name', activation_time_constant=tau_a,
213
+ )
214
+ assert instance.tau_a == expected
215
+ assert instance.activation_time_constant == expected
216
+ assert instance.tau_a is instance.activation_time_constant
217
+
218
+ def test_activation_time_constant_is_immutable(self):
219
+ with pytest.raises(AttributeError):
220
+ self.instance.tau_a = None
221
+ with pytest.raises(AttributeError):
222
+ self.instance.activation_time_constant = None
223
+
224
+ @pytest.mark.parametrize(
225
+ 'tau_d, expected',
226
+ [
227
+ (None, Symbol('tau_d_name')),
228
+ (Symbol('tau_d'), Symbol('tau_d')),
229
+ (Float('0.060'), Float('0.060')),
230
+ ]
231
+ )
232
+ def test_deactivation_time_constant(self, tau_d, expected):
233
+ instance = FirstOrderActivationDeGroote2016(
234
+ 'name', deactivation_time_constant=tau_d,
235
+ )
236
+ assert instance.tau_d == expected
237
+ assert instance.deactivation_time_constant == expected
238
+ assert instance.tau_d is instance.deactivation_time_constant
239
+
240
+ def test_deactivation_time_constant_is_immutable(self):
241
+ with pytest.raises(AttributeError):
242
+ self.instance.tau_d = None
243
+ with pytest.raises(AttributeError):
244
+ self.instance.deactivation_time_constant = None
245
+
246
+ @pytest.mark.parametrize(
247
+ 'b, expected',
248
+ [
249
+ (None, Symbol('b_name')),
250
+ (Symbol('b'), Symbol('b')),
251
+ (Integer('10'), Integer('10')),
252
+ ]
253
+ )
254
+ def test_smoothing_rate(self, b, expected):
255
+ instance = FirstOrderActivationDeGroote2016(
256
+ 'name', smoothing_rate=b,
257
+ )
258
+ assert instance.b == expected
259
+ assert instance.smoothing_rate == expected
260
+ assert instance.b is instance.smoothing_rate
261
+
262
+ def test_smoothing_rate_is_immutable(self):
263
+ with pytest.raises(AttributeError):
264
+ self.instance.b = None
265
+ with pytest.raises(AttributeError):
266
+ self.instance.smoothing_rate = None
267
+
268
+ def test_state_vars(self):
269
+ assert hasattr(self.instance, 'x')
270
+ assert hasattr(self.instance, 'state_vars')
271
+ assert self.instance.x == self.instance.state_vars
272
+ x_expected = Matrix([self.a])
273
+ assert self.instance.x == x_expected
274
+ assert self.instance.state_vars == x_expected
275
+ assert isinstance(self.instance.x, Matrix)
276
+ assert isinstance(self.instance.state_vars, Matrix)
277
+ assert self.instance.x.shape == (1, 1)
278
+ assert self.instance.state_vars.shape == (1, 1)
279
+
280
+ def test_input_vars(self):
281
+ assert hasattr(self.instance, 'r')
282
+ assert hasattr(self.instance, 'input_vars')
283
+ assert self.instance.r == self.instance.input_vars
284
+ r_expected = Matrix([self.e])
285
+ assert self.instance.r == r_expected
286
+ assert self.instance.input_vars == r_expected
287
+ assert isinstance(self.instance.r, Matrix)
288
+ assert isinstance(self.instance.input_vars, Matrix)
289
+ assert self.instance.r.shape == (1, 1)
290
+ assert self.instance.input_vars.shape == (1, 1)
291
+
292
+ def test_constants(self):
293
+ assert hasattr(self.instance, 'p')
294
+ assert hasattr(self.instance, 'constants')
295
+ assert self.instance.p == self.instance.constants
296
+ p_expected = Matrix([self.tau_a, self.tau_d, self.b])
297
+ assert self.instance.p == p_expected
298
+ assert self.instance.constants == p_expected
299
+ assert isinstance(self.instance.p, Matrix)
300
+ assert isinstance(self.instance.constants, Matrix)
301
+ assert self.instance.p.shape == (3, 1)
302
+ assert self.instance.constants.shape == (3, 1)
303
+
304
+ def test_M(self):
305
+ assert hasattr(self.instance, 'M')
306
+ M_expected = Matrix([1])
307
+ assert self.instance.M == M_expected
308
+ assert isinstance(self.instance.M, Matrix)
309
+ assert self.instance.M.shape == (1, 1)
310
+
311
+ def test_F(self):
312
+ assert hasattr(self.instance, 'F')
313
+ da_expr = (
314
+ ((1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
315
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
316
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
317
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a))))
318
+ *(self.e - self.a)
319
+ )
320
+ F_expected = Matrix([da_expr])
321
+ assert self.instance.F == F_expected
322
+ assert isinstance(self.instance.F, Matrix)
323
+ assert self.instance.F.shape == (1, 1)
324
+
325
+ def test_rhs(self):
326
+ assert hasattr(self.instance, 'rhs')
327
+ da_expr = (
328
+ ((1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
329
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
330
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
331
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a))))
332
+ *(self.e - self.a)
333
+ )
334
+ rhs_expected = Matrix([da_expr])
335
+ rhs = self.instance.rhs()
336
+ assert rhs == rhs_expected
337
+ assert isinstance(rhs, Matrix)
338
+ assert rhs.shape == (1, 1)
339
+ assert simplify(self.instance.M.solve(self.instance.F) - rhs) == zeros(1)
340
+
341
+ def test_repr(self):
342
+ expected = (
343
+ 'FirstOrderActivationDeGroote2016(\'name\', '
344
+ 'activation_time_constant=tau_a, '
345
+ 'deactivation_time_constant=tau_d, '
346
+ 'smoothing_rate=b)'
347
+ )
348
+ assert repr(self.instance) == expected
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_curve.py ADDED
@@ -0,0 +1,1695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.characteristic.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy.core.expr import UnevaluatedExpr
6
+ from sympy.core.function import Function
7
+ from sympy.core.numbers import Float, Integer
8
+ from sympy.core.symbol import Symbol, symbols
9
+ from sympy.external.importtools import import_module
10
+ from sympy.functions.elementary.exponential import exp, log
11
+ from sympy.functions.elementary.hyperbolic import cosh, sinh
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.physics.biomechanics.curve import (
14
+ CharacteristicCurveCollection,
15
+ CharacteristicCurveFunction,
16
+ FiberForceLengthActiveDeGroote2016,
17
+ FiberForceLengthPassiveDeGroote2016,
18
+ FiberForceLengthPassiveInverseDeGroote2016,
19
+ FiberForceVelocityDeGroote2016,
20
+ FiberForceVelocityInverseDeGroote2016,
21
+ TendonForceLengthDeGroote2016,
22
+ TendonForceLengthInverseDeGroote2016,
23
+ )
24
+ from sympy.printing.c import C89CodePrinter, C99CodePrinter, C11CodePrinter
25
+ from sympy.printing.cxx import (
26
+ CXX98CodePrinter,
27
+ CXX11CodePrinter,
28
+ CXX17CodePrinter,
29
+ )
30
+ from sympy.printing.fortran import FCodePrinter
31
+ from sympy.printing.lambdarepr import LambdaPrinter
32
+ from sympy.printing.latex import LatexPrinter
33
+ from sympy.printing.octave import OctaveCodePrinter
34
+ from sympy.printing.numpy import (
35
+ CuPyPrinter,
36
+ JaxPrinter,
37
+ NumPyPrinter,
38
+ SciPyPrinter,
39
+ )
40
+ from sympy.printing.pycode import MpmathPrinter, PythonCodePrinter
41
+ from sympy.utilities.lambdify import lambdify
42
+
43
+ jax = import_module('jax')
44
+ numpy = import_module('numpy')
45
+
46
+ if jax:
47
+ jax.config.update('jax_enable_x64', True)
48
+
49
+
50
+ class TestCharacteristicCurveFunction:
51
+
52
+ @staticmethod
53
+ @pytest.mark.parametrize(
54
+ 'code_printer, expected',
55
+ [
56
+ (C89CodePrinter, '(a + b)*(c + d)*(e + f)'),
57
+ (C99CodePrinter, '(a + b)*(c + d)*(e + f)'),
58
+ (C11CodePrinter, '(a + b)*(c + d)*(e + f)'),
59
+ (CXX98CodePrinter, '(a + b)*(c + d)*(e + f)'),
60
+ (CXX11CodePrinter, '(a + b)*(c + d)*(e + f)'),
61
+ (CXX17CodePrinter, '(a + b)*(c + d)*(e + f)'),
62
+ (FCodePrinter, ' (a + b)*(c + d)*(e + f)'),
63
+ (OctaveCodePrinter, '(a + b).*(c + d).*(e + f)'),
64
+ (PythonCodePrinter, '(a + b)*(c + d)*(e + f)'),
65
+ (NumPyPrinter, '(a + b)*(c + d)*(e + f)'),
66
+ (SciPyPrinter, '(a + b)*(c + d)*(e + f)'),
67
+ (CuPyPrinter, '(a + b)*(c + d)*(e + f)'),
68
+ (JaxPrinter, '(a + b)*(c + d)*(e + f)'),
69
+ (MpmathPrinter, '(a + b)*(c + d)*(e + f)'),
70
+ (LambdaPrinter, '(a + b)*(c + d)*(e + f)'),
71
+ ]
72
+ )
73
+ def test_print_code_parenthesize(code_printer, expected):
74
+
75
+ class ExampleFunction(CharacteristicCurveFunction):
76
+
77
+ @classmethod
78
+ def eval(cls, a, b):
79
+ pass
80
+
81
+ def doit(self, **kwargs):
82
+ a, b = self.args
83
+ return a + b
84
+
85
+ a, b, c, d, e, f = symbols('a, b, c, d, e, f')
86
+ f1 = ExampleFunction(a, b)
87
+ f2 = ExampleFunction(c, d)
88
+ f3 = ExampleFunction(e, f)
89
+ assert code_printer().doprint(f1*f2*f3) == expected
90
+
91
+
92
+ class TestTendonForceLengthDeGroote2016:
93
+
94
+ @pytest.fixture(autouse=True)
95
+ def _tendon_force_length_arguments_fixture(self):
96
+ self.l_T_tilde = Symbol('l_T_tilde')
97
+ self.c0 = Symbol('c_0')
98
+ self.c1 = Symbol('c_1')
99
+ self.c2 = Symbol('c_2')
100
+ self.c3 = Symbol('c_3')
101
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
102
+
103
+ @staticmethod
104
+ def test_class():
105
+ assert issubclass(TendonForceLengthDeGroote2016, Function)
106
+ assert issubclass(TendonForceLengthDeGroote2016, CharacteristicCurveFunction)
107
+ assert TendonForceLengthDeGroote2016.__name__ == 'TendonForceLengthDeGroote2016'
108
+
109
+ def test_instance(self):
110
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
111
+ assert isinstance(fl_T, TendonForceLengthDeGroote2016)
112
+ assert str(fl_T) == 'TendonForceLengthDeGroote2016(l_T_tilde, c_0, c_1, c_2, c_3)'
113
+
114
+ def test_doit(self):
115
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants).doit()
116
+ assert fl_T == self.c0*exp(self.c3*(self.l_T_tilde - self.c1)) - self.c2
117
+
118
+ def test_doit_evaluate_false(self):
119
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants).doit(evaluate=False)
120
+ assert fl_T == self.c0*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1)) - self.c2
121
+
122
+ def test_with_defaults(self):
123
+ constants = (
124
+ Float('0.2'),
125
+ Float('0.995'),
126
+ Float('0.25'),
127
+ Float('33.93669377311689'),
128
+ )
129
+ fl_T_manual = TendonForceLengthDeGroote2016(self.l_T_tilde, *constants)
130
+ fl_T_constants = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
131
+ assert fl_T_manual == fl_T_constants
132
+
133
+ def test_differentiate_wrt_l_T_tilde(self):
134
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
135
+ expected = self.c0*self.c3*exp(self.c3*UnevaluatedExpr(-self.c1 + self.l_T_tilde))
136
+ assert fl_T.diff(self.l_T_tilde) == expected
137
+
138
+ def test_differentiate_wrt_c0(self):
139
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
140
+ expected = exp(self.c3*UnevaluatedExpr(-self.c1 + self.l_T_tilde))
141
+ assert fl_T.diff(self.c0) == expected
142
+
143
+ def test_differentiate_wrt_c1(self):
144
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
145
+ expected = -self.c0*self.c3*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1))
146
+ assert fl_T.diff(self.c1) == expected
147
+
148
+ def test_differentiate_wrt_c2(self):
149
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
150
+ expected = Integer(-1)
151
+ assert fl_T.diff(self.c2) == expected
152
+
153
+ def test_differentiate_wrt_c3(self):
154
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
155
+ expected = self.c0*(self.l_T_tilde - self.c1)*exp(self.c3*UnevaluatedExpr(self.l_T_tilde - self.c1))
156
+ assert fl_T.diff(self.c3) == expected
157
+
158
+ def test_inverse(self):
159
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
160
+ assert fl_T.inverse() is TendonForceLengthInverseDeGroote2016
161
+
162
+ def test_function_print_latex(self):
163
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
164
+ expected = r'\operatorname{fl}^T \left( l_{T tilde} \right)'
165
+ assert LatexPrinter().doprint(fl_T) == expected
166
+
167
+ def test_expression_print_latex(self):
168
+ fl_T = TendonForceLengthDeGroote2016(self.l_T_tilde, *self.constants)
169
+ expected = r'c_{0} e^{c_{3} \left(- c_{1} + l_{T tilde}\right)} - c_{2}'
170
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
171
+
172
+ @pytest.mark.parametrize(
173
+ 'code_printer, expected',
174
+ [
175
+ (
176
+ C89CodePrinter,
177
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
178
+ ),
179
+ (
180
+ C99CodePrinter,
181
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
182
+ ),
183
+ (
184
+ C11CodePrinter,
185
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
186
+ ),
187
+ (
188
+ CXX98CodePrinter,
189
+ '(-0.25 + 0.20000000000000001*exp(33.93669377311689*(l_T_tilde - 0.995)))',
190
+ ),
191
+ (
192
+ CXX11CodePrinter,
193
+ '(-0.25 + 0.20000000000000001*std::exp(33.93669377311689*(l_T_tilde - 0.995)))',
194
+ ),
195
+ (
196
+ CXX17CodePrinter,
197
+ '(-0.25 + 0.20000000000000001*std::exp(33.93669377311689*(l_T_tilde - 0.995)))',
198
+ ),
199
+ (
200
+ FCodePrinter,
201
+ ' (-0.25d0 + 0.2d0*exp(33.93669377311689d0*(l_T_tilde - 0.995d0)))',
202
+ ),
203
+ (
204
+ OctaveCodePrinter,
205
+ '(-0.25 + 0.2*exp(33.93669377311689*(l_T_tilde - 0.995)))',
206
+ ),
207
+ (
208
+ PythonCodePrinter,
209
+ '(-0.25 + 0.2*math.exp(33.93669377311689*(l_T_tilde - 0.995)))',
210
+ ),
211
+ (
212
+ NumPyPrinter,
213
+ '(-0.25 + 0.2*numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
214
+ ),
215
+ (
216
+ SciPyPrinter,
217
+ '(-0.25 + 0.2*numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
218
+ ),
219
+ (
220
+ CuPyPrinter,
221
+ '(-0.25 + 0.2*cupy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
222
+ ),
223
+ (
224
+ JaxPrinter,
225
+ '(-0.25 + 0.2*jax.numpy.exp(33.93669377311689*(l_T_tilde - 0.995)))',
226
+ ),
227
+ (
228
+ MpmathPrinter,
229
+ '(mpmath.mpf((1, 1, -2, 1)) + mpmath.mpf((0, 3602879701896397, -54, 52))'
230
+ '*mpmath.exp(mpmath.mpf((0, 9552330089424741, -48, 54))*(l_T_tilde + '
231
+ 'mpmath.mpf((1, 8962163258467287, -53, 53)))))',
232
+ ),
233
+ (
234
+ LambdaPrinter,
235
+ '(-0.25 + 0.2*math.exp(33.93669377311689*(l_T_tilde - 0.995)))',
236
+ ),
237
+ ]
238
+ )
239
+ def test_print_code(self, code_printer, expected):
240
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
241
+ assert code_printer().doprint(fl_T) == expected
242
+
243
+ def test_derivative_print_code(self):
244
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
245
+ dfl_T_dl_T_tilde = fl_T.diff(self.l_T_tilde)
246
+ expected = '6.787338754623378*math.exp(33.93669377311689*(l_T_tilde - 0.995))'
247
+ assert PythonCodePrinter().doprint(dfl_T_dl_T_tilde) == expected
248
+
249
+ def test_lambdify(self):
250
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
251
+ fl_T_callable = lambdify(self.l_T_tilde, fl_T)
252
+ assert fl_T_callable(1.0) == pytest.approx(-0.013014055039221595)
253
+
254
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
255
+ def test_lambdify_numpy(self):
256
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
257
+ fl_T_callable = lambdify(self.l_T_tilde, fl_T, 'numpy')
258
+ l_T_tilde = numpy.array([0.95, 1.0, 1.01, 1.05])
259
+ expected = numpy.array([
260
+ -0.2065693181344816,
261
+ -0.0130140550392216,
262
+ 0.0827421191989246,
263
+ 1.04314889144172,
264
+ ])
265
+ numpy.testing.assert_allclose(fl_T_callable(l_T_tilde), expected)
266
+
267
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
268
+ def test_lambdify_jax(self):
269
+ fl_T = TendonForceLengthDeGroote2016.with_defaults(self.l_T_tilde)
270
+ fl_T_callable = jax.jit(lambdify(self.l_T_tilde, fl_T, 'jax'))
271
+ l_T_tilde = jax.numpy.array([0.95, 1.0, 1.01, 1.05])
272
+ expected = jax.numpy.array([
273
+ -0.2065693181344816,
274
+ -0.0130140550392216,
275
+ 0.0827421191989246,
276
+ 1.04314889144172,
277
+ ])
278
+ numpy.testing.assert_allclose(fl_T_callable(l_T_tilde), expected)
279
+
280
+
281
+ class TestTendonForceLengthInverseDeGroote2016:
282
+
283
+ @pytest.fixture(autouse=True)
284
+ def _tendon_force_length_inverse_arguments_fixture(self):
285
+ self.fl_T = Symbol('fl_T')
286
+ self.c0 = Symbol('c_0')
287
+ self.c1 = Symbol('c_1')
288
+ self.c2 = Symbol('c_2')
289
+ self.c3 = Symbol('c_3')
290
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
291
+
292
+ @staticmethod
293
+ def test_class():
294
+ assert issubclass(TendonForceLengthInverseDeGroote2016, Function)
295
+ assert issubclass(TendonForceLengthInverseDeGroote2016, CharacteristicCurveFunction)
296
+ assert TendonForceLengthInverseDeGroote2016.__name__ == 'TendonForceLengthInverseDeGroote2016'
297
+
298
+ def test_instance(self):
299
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
300
+ assert isinstance(fl_T_inv, TendonForceLengthInverseDeGroote2016)
301
+ assert str(fl_T_inv) == 'TendonForceLengthInverseDeGroote2016(fl_T, c_0, c_1, c_2, c_3)'
302
+
303
+ def test_doit(self):
304
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants).doit()
305
+ assert fl_T_inv == log((self.fl_T + self.c2)/self.c0)/self.c3 + self.c1
306
+
307
+ def test_doit_evaluate_false(self):
308
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants).doit(evaluate=False)
309
+ assert fl_T_inv == log(UnevaluatedExpr((self.fl_T + self.c2)/self.c0))/self.c3 + self.c1
310
+
311
+ def test_with_defaults(self):
312
+ constants = (
313
+ Float('0.2'),
314
+ Float('0.995'),
315
+ Float('0.25'),
316
+ Float('33.93669377311689'),
317
+ )
318
+ fl_T_inv_manual = TendonForceLengthInverseDeGroote2016(self.fl_T, *constants)
319
+ fl_T_inv_constants = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
320
+ assert fl_T_inv_manual == fl_T_inv_constants
321
+
322
+ def test_differentiate_wrt_fl_T(self):
323
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
324
+ expected = 1/(self.c3*(self.fl_T + self.c2))
325
+ assert fl_T_inv.diff(self.fl_T) == expected
326
+
327
+ def test_differentiate_wrt_c0(self):
328
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
329
+ expected = -1/(self.c0*self.c3)
330
+ assert fl_T_inv.diff(self.c0) == expected
331
+
332
+ def test_differentiate_wrt_c1(self):
333
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
334
+ expected = Integer(1)
335
+ assert fl_T_inv.diff(self.c1) == expected
336
+
337
+ def test_differentiate_wrt_c2(self):
338
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
339
+ expected = 1/(self.c3*(self.fl_T + self.c2))
340
+ assert fl_T_inv.diff(self.c2) == expected
341
+
342
+ def test_differentiate_wrt_c3(self):
343
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
344
+ expected = -log(UnevaluatedExpr((self.fl_T + self.c2)/self.c0))/self.c3**2
345
+ assert fl_T_inv.diff(self.c3) == expected
346
+
347
+ def test_inverse(self):
348
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
349
+ assert fl_T_inv.inverse() is TendonForceLengthDeGroote2016
350
+
351
+ def test_function_print_latex(self):
352
+ fl_T_inv = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
353
+ expected = r'\left( \operatorname{fl}^T \right)^{-1} \left( fl_{T} \right)'
354
+ assert LatexPrinter().doprint(fl_T_inv) == expected
355
+
356
+ def test_expression_print_latex(self):
357
+ fl_T = TendonForceLengthInverseDeGroote2016(self.fl_T, *self.constants)
358
+ expected = r'c_{1} + \frac{\log{\left(\frac{c_{2} + fl_{T}}{c_{0}} \right)}}{c_{3}}'
359
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
360
+
361
+ @pytest.mark.parametrize(
362
+ 'code_printer, expected',
363
+ [
364
+ (
365
+ C89CodePrinter,
366
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
367
+ ),
368
+ (
369
+ C99CodePrinter,
370
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
371
+ ),
372
+ (
373
+ C11CodePrinter,
374
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
375
+ ),
376
+ (
377
+ CXX98CodePrinter,
378
+ '(0.995 + 0.029466630034306838*log(5.0*fl_T + 1.25))',
379
+ ),
380
+ (
381
+ CXX11CodePrinter,
382
+ '(0.995 + 0.029466630034306838*std::log(5.0*fl_T + 1.25))',
383
+ ),
384
+ (
385
+ CXX17CodePrinter,
386
+ '(0.995 + 0.029466630034306838*std::log(5.0*fl_T + 1.25))',
387
+ ),
388
+ (
389
+ FCodePrinter,
390
+ ' (0.995d0 + 0.02946663003430684d0*log(5.0d0*fl_T + 1.25d0))',
391
+ ),
392
+ (
393
+ OctaveCodePrinter,
394
+ '(0.995 + 0.02946663003430684*log(5.0*fl_T + 1.25))',
395
+ ),
396
+ (
397
+ PythonCodePrinter,
398
+ '(0.995 + 0.02946663003430684*math.log(5.0*fl_T + 1.25))',
399
+ ),
400
+ (
401
+ NumPyPrinter,
402
+ '(0.995 + 0.02946663003430684*numpy.log(5.0*fl_T + 1.25))',
403
+ ),
404
+ (
405
+ SciPyPrinter,
406
+ '(0.995 + 0.02946663003430684*numpy.log(5.0*fl_T + 1.25))',
407
+ ),
408
+ (
409
+ CuPyPrinter,
410
+ '(0.995 + 0.02946663003430684*cupy.log(5.0*fl_T + 1.25))',
411
+ ),
412
+ (
413
+ JaxPrinter,
414
+ '(0.995 + 0.02946663003430684*jax.numpy.log(5.0*fl_T + 1.25))',
415
+ ),
416
+ (
417
+ MpmathPrinter,
418
+ '(mpmath.mpf((0, 8962163258467287, -53, 53))'
419
+ ' + mpmath.mpf((0, 33972711434846347, -60, 55))'
420
+ '*mpmath.log(mpmath.mpf((0, 5, 0, 3))*fl_T + mpmath.mpf((0, 5, -2, 3))))',
421
+ ),
422
+ (
423
+ LambdaPrinter,
424
+ '(0.995 + 0.02946663003430684*math.log(5.0*fl_T + 1.25))',
425
+ ),
426
+ ]
427
+ )
428
+ def test_print_code(self, code_printer, expected):
429
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
430
+ assert code_printer().doprint(fl_T_inv) == expected
431
+
432
+ def test_derivative_print_code(self):
433
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
434
+ dfl_T_inv_dfl_T = fl_T_inv.diff(self.fl_T)
435
+ expected = '1/(33.93669377311689*fl_T + 8.484173443279222)'
436
+ assert PythonCodePrinter().doprint(dfl_T_inv_dfl_T) == expected
437
+
438
+ def test_lambdify(self):
439
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
440
+ fl_T_inv_callable = lambdify(self.fl_T, fl_T_inv)
441
+ assert fl_T_inv_callable(0.0) == pytest.approx(1.0015752885)
442
+
443
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
444
+ def test_lambdify_numpy(self):
445
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
446
+ fl_T_inv_callable = lambdify(self.fl_T, fl_T_inv, 'numpy')
447
+ fl_T = numpy.array([-0.2, -0.01, 0.0, 1.01, 1.02, 1.05])
448
+ expected = numpy.array([
449
+ 0.9541505769,
450
+ 1.0003724019,
451
+ 1.0015752885,
452
+ 1.0492347951,
453
+ 1.0494677341,
454
+ 1.0501557022,
455
+ ])
456
+ numpy.testing.assert_allclose(fl_T_inv_callable(fl_T), expected)
457
+
458
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
459
+ def test_lambdify_jax(self):
460
+ fl_T_inv = TendonForceLengthInverseDeGroote2016.with_defaults(self.fl_T)
461
+ fl_T_inv_callable = jax.jit(lambdify(self.fl_T, fl_T_inv, 'jax'))
462
+ fl_T = jax.numpy.array([-0.2, -0.01, 0.0, 1.01, 1.02, 1.05])
463
+ expected = jax.numpy.array([
464
+ 0.9541505769,
465
+ 1.0003724019,
466
+ 1.0015752885,
467
+ 1.0492347951,
468
+ 1.0494677341,
469
+ 1.0501557022,
470
+ ])
471
+ numpy.testing.assert_allclose(fl_T_inv_callable(fl_T), expected)
472
+
473
+
474
+ class TestFiberForceLengthPassiveDeGroote2016:
475
+
476
+ @pytest.fixture(autouse=True)
477
+ def _fiber_force_length_passive_arguments_fixture(self):
478
+ self.l_M_tilde = Symbol('l_M_tilde')
479
+ self.c0 = Symbol('c_0')
480
+ self.c1 = Symbol('c_1')
481
+ self.constants = (self.c0, self.c1)
482
+
483
+ @staticmethod
484
+ def test_class():
485
+ assert issubclass(FiberForceLengthPassiveDeGroote2016, Function)
486
+ assert issubclass(FiberForceLengthPassiveDeGroote2016, CharacteristicCurveFunction)
487
+ assert FiberForceLengthPassiveDeGroote2016.__name__ == 'FiberForceLengthPassiveDeGroote2016'
488
+
489
+ def test_instance(self):
490
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
491
+ assert isinstance(fl_M_pas, FiberForceLengthPassiveDeGroote2016)
492
+ assert str(fl_M_pas) == 'FiberForceLengthPassiveDeGroote2016(l_M_tilde, c_0, c_1)'
493
+
494
+ def test_doit(self):
495
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants).doit()
496
+ assert fl_M_pas == (exp((self.c1*(self.l_M_tilde - 1))/self.c0) - 1)/(exp(self.c1) - 1)
497
+
498
+ def test_doit_evaluate_false(self):
499
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants).doit(evaluate=False)
500
+ assert fl_M_pas == (exp((self.c1*UnevaluatedExpr(self.l_M_tilde - 1))/self.c0) - 1)/(exp(self.c1) - 1)
501
+
502
+ def test_with_defaults(self):
503
+ constants = (
504
+ Float('0.6'),
505
+ Float('4.0'),
506
+ )
507
+ fl_M_pas_manual = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *constants)
508
+ fl_M_pas_constants = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
509
+ assert fl_M_pas_manual == fl_M_pas_constants
510
+
511
+ def test_differentiate_wrt_l_M_tilde(self):
512
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
513
+ expected = self.c1*exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)/(self.c0*(exp(self.c1) - 1))
514
+ assert fl_M_pas.diff(self.l_M_tilde) == expected
515
+
516
+ def test_differentiate_wrt_c0(self):
517
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
518
+ expected = (
519
+ -self.c1*exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)
520
+ *UnevaluatedExpr(self.l_M_tilde - 1)/(self.c0**2*(exp(self.c1) - 1))
521
+ )
522
+ assert fl_M_pas.diff(self.c0) == expected
523
+
524
+ def test_differentiate_wrt_c1(self):
525
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
526
+ expected = (
527
+ -exp(self.c1)*(-1 + exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0))/(exp(self.c1) - 1)**2
528
+ + exp(self.c1*UnevaluatedExpr(self.l_M_tilde - 1)/self.c0)*(self.l_M_tilde - 1)/(self.c0*(exp(self.c1) - 1))
529
+ )
530
+ assert fl_M_pas.diff(self.c1) == expected
531
+
532
+ def test_inverse(self):
533
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
534
+ assert fl_M_pas.inverse() is FiberForceLengthPassiveInverseDeGroote2016
535
+
536
+ def test_function_print_latex(self):
537
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
538
+ expected = r'\operatorname{fl}^M_{pas} \left( l_{M tilde} \right)'
539
+ assert LatexPrinter().doprint(fl_M_pas) == expected
540
+
541
+ def test_expression_print_latex(self):
542
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016(self.l_M_tilde, *self.constants)
543
+ expected = r'\frac{e^{\frac{c_{1} \left(l_{M tilde} - 1\right)}{c_{0}}} - 1}{e^{c_{1}} - 1}'
544
+ assert LatexPrinter().doprint(fl_M_pas.doit()) == expected
545
+
546
+ @pytest.mark.parametrize(
547
+ 'code_printer, expected',
548
+ [
549
+ (
550
+ C89CodePrinter,
551
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
552
+ ),
553
+ (
554
+ C99CodePrinter,
555
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
556
+ ),
557
+ (
558
+ C11CodePrinter,
559
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
560
+ ),
561
+ (
562
+ CXX98CodePrinter,
563
+ '(0.01865736036377405*(-1 + exp(6.666666666666667*(l_M_tilde - 1))))',
564
+ ),
565
+ (
566
+ CXX11CodePrinter,
567
+ '(0.01865736036377405*(-1 + std::exp(6.666666666666667*(l_M_tilde - 1))))',
568
+ ),
569
+ (
570
+ CXX17CodePrinter,
571
+ '(0.01865736036377405*(-1 + std::exp(6.666666666666667*(l_M_tilde - 1))))',
572
+ ),
573
+ (
574
+ FCodePrinter,
575
+ ' (0.0186573603637741d0*(-1 + exp(6.666666666666667d0*(l_M_tilde - 1\n'
576
+ ' @ ))))',
577
+ ),
578
+ (
579
+ OctaveCodePrinter,
580
+ '(0.0186573603637741*(-1 + exp(6.66666666666667*(l_M_tilde - 1))))',
581
+ ),
582
+ (
583
+ PythonCodePrinter,
584
+ '(0.0186573603637741*(-1 + math.exp(6.66666666666667*(l_M_tilde - 1))))',
585
+ ),
586
+ (
587
+ NumPyPrinter,
588
+ '(0.0186573603637741*(-1 + numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
589
+ ),
590
+ (
591
+ SciPyPrinter,
592
+ '(0.0186573603637741*(-1 + numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
593
+ ),
594
+ (
595
+ CuPyPrinter,
596
+ '(0.0186573603637741*(-1 + cupy.exp(6.66666666666667*(l_M_tilde - 1))))',
597
+ ),
598
+ (
599
+ JaxPrinter,
600
+ '(0.0186573603637741*(-1 + jax.numpy.exp(6.66666666666667*(l_M_tilde - 1))))',
601
+ ),
602
+ (
603
+ MpmathPrinter,
604
+ '(mpmath.mpf((0, 672202249456079, -55, 50))*(-1 + mpmath.exp('
605
+ 'mpmath.mpf((0, 7505999378950827, -50, 53))*(l_M_tilde - 1))))',
606
+ ),
607
+ (
608
+ LambdaPrinter,
609
+ '(0.0186573603637741*(-1 + math.exp(6.66666666666667*(l_M_tilde - 1))))',
610
+ ),
611
+ ]
612
+ )
613
+ def test_print_code(self, code_printer, expected):
614
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
615
+ assert code_printer().doprint(fl_M_pas) == expected
616
+
617
+ def test_derivative_print_code(self):
618
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
619
+ fl_M_pas_dl_M_tilde = fl_M_pas.diff(self.l_M_tilde)
620
+ expected = '0.12438240242516*math.exp(6.66666666666667*(l_M_tilde - 1))'
621
+ assert PythonCodePrinter().doprint(fl_M_pas_dl_M_tilde) == expected
622
+
623
+ def test_lambdify(self):
624
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
625
+ fl_M_pas_callable = lambdify(self.l_M_tilde, fl_M_pas)
626
+ assert fl_M_pas_callable(1.0) == pytest.approx(0.0)
627
+
628
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
629
+ def test_lambdify_numpy(self):
630
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
631
+ fl_M_pas_callable = lambdify(self.l_M_tilde, fl_M_pas, 'numpy')
632
+ l_M_tilde = numpy.array([0.5, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5])
633
+ expected = numpy.array([
634
+ -0.0179917778,
635
+ -0.0137393336,
636
+ -0.0090783522,
637
+ 0.0,
638
+ 0.0176822155,
639
+ 0.0521224686,
640
+ 0.5043387669,
641
+ ])
642
+ numpy.testing.assert_allclose(fl_M_pas_callable(l_M_tilde), expected)
643
+
644
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
645
+ def test_lambdify_jax(self):
646
+ fl_M_pas = FiberForceLengthPassiveDeGroote2016.with_defaults(self.l_M_tilde)
647
+ fl_M_pas_callable = jax.jit(lambdify(self.l_M_tilde, fl_M_pas, 'jax'))
648
+ l_M_tilde = jax.numpy.array([0.5, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5])
649
+ expected = jax.numpy.array([
650
+ -0.0179917778,
651
+ -0.0137393336,
652
+ -0.0090783522,
653
+ 0.0,
654
+ 0.0176822155,
655
+ 0.0521224686,
656
+ 0.5043387669,
657
+ ])
658
+ numpy.testing.assert_allclose(fl_M_pas_callable(l_M_tilde), expected)
659
+
660
+
661
+ class TestFiberForceLengthPassiveInverseDeGroote2016:
662
+
663
+ @pytest.fixture(autouse=True)
664
+ def _fiber_force_length_passive_arguments_fixture(self):
665
+ self.fl_M_pas = Symbol('fl_M_pas')
666
+ self.c0 = Symbol('c_0')
667
+ self.c1 = Symbol('c_1')
668
+ self.constants = (self.c0, self.c1)
669
+
670
+ @staticmethod
671
+ def test_class():
672
+ assert issubclass(FiberForceLengthPassiveInverseDeGroote2016, Function)
673
+ assert issubclass(FiberForceLengthPassiveInverseDeGroote2016, CharacteristicCurveFunction)
674
+ assert FiberForceLengthPassiveInverseDeGroote2016.__name__ == 'FiberForceLengthPassiveInverseDeGroote2016'
675
+
676
+ def test_instance(self):
677
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
678
+ assert isinstance(fl_M_pas_inv, FiberForceLengthPassiveInverseDeGroote2016)
679
+ assert str(fl_M_pas_inv) == 'FiberForceLengthPassiveInverseDeGroote2016(fl_M_pas, c_0, c_1)'
680
+
681
+ def test_doit(self):
682
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants).doit()
683
+ assert fl_M_pas_inv == self.c0*log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1 + 1
684
+
685
+ def test_doit_evaluate_false(self):
686
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants).doit(evaluate=False)
687
+ assert fl_M_pas_inv == self.c0*log(UnevaluatedExpr(self.fl_M_pas*(exp(self.c1) - 1)) + 1)/self.c1 + 1
688
+
689
+ def test_with_defaults(self):
690
+ constants = (
691
+ Float('0.6'),
692
+ Float('4.0'),
693
+ )
694
+ fl_M_pas_inv_manual = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *constants)
695
+ fl_M_pas_inv_constants = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
696
+ assert fl_M_pas_inv_manual == fl_M_pas_inv_constants
697
+
698
+ def test_differentiate_wrt_fl_T(self):
699
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
700
+ expected = self.c0*(exp(self.c1) - 1)/(self.c1*(self.fl_M_pas*(exp(self.c1) - 1) + 1))
701
+ assert fl_M_pas_inv.diff(self.fl_M_pas) == expected
702
+
703
+ def test_differentiate_wrt_c0(self):
704
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
705
+ expected = log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1
706
+ assert fl_M_pas_inv.diff(self.c0) == expected
707
+
708
+ def test_differentiate_wrt_c1(self):
709
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
710
+ expected = (
711
+ self.c0*self.fl_M_pas*exp(self.c1)/(self.c1*(self.fl_M_pas*(exp(self.c1) - 1) + 1))
712
+ - self.c0*log(self.fl_M_pas*(exp(self.c1) - 1) + 1)/self.c1**2
713
+ )
714
+ assert fl_M_pas_inv.diff(self.c1) == expected
715
+
716
+ def test_inverse(self):
717
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
718
+ assert fl_M_pas_inv.inverse() is FiberForceLengthPassiveDeGroote2016
719
+
720
+ def test_function_print_latex(self):
721
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
722
+ expected = r'\left( \operatorname{fl}^M_{pas} \right)^{-1} \left( fl_{M pas} \right)'
723
+ assert LatexPrinter().doprint(fl_M_pas_inv) == expected
724
+
725
+ def test_expression_print_latex(self):
726
+ fl_T = FiberForceLengthPassiveInverseDeGroote2016(self.fl_M_pas, *self.constants)
727
+ expected = r'\frac{c_{0} \log{\left(fl_{M pas} \left(e^{c_{1}} - 1\right) + 1 \right)}}{c_{1}} + 1'
728
+ assert LatexPrinter().doprint(fl_T.doit()) == expected
729
+
730
+ @pytest.mark.parametrize(
731
+ 'code_printer, expected',
732
+ [
733
+ (
734
+ C89CodePrinter,
735
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
736
+ ),
737
+ (
738
+ C99CodePrinter,
739
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
740
+ ),
741
+ (
742
+ C11CodePrinter,
743
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
744
+ ),
745
+ (
746
+ CXX98CodePrinter,
747
+ '(1 + 0.14999999999999999*log(1 + 53.598150033144236*fl_M_pas))',
748
+ ),
749
+ (
750
+ CXX11CodePrinter,
751
+ '(1 + 0.14999999999999999*std::log(1 + 53.598150033144236*fl_M_pas))',
752
+ ),
753
+ (
754
+ CXX17CodePrinter,
755
+ '(1 + 0.14999999999999999*std::log(1 + 53.598150033144236*fl_M_pas))',
756
+ ),
757
+ (
758
+ FCodePrinter,
759
+ ' (1 + 0.15d0*log(1.0d0 + 53.5981500331442d0*fl_M_pas))',
760
+ ),
761
+ (
762
+ OctaveCodePrinter,
763
+ '(1 + 0.15*log(1 + 53.5981500331442*fl_M_pas))',
764
+ ),
765
+ (
766
+ PythonCodePrinter,
767
+ '(1 + 0.15*math.log(1 + 53.5981500331442*fl_M_pas))',
768
+ ),
769
+ (
770
+ NumPyPrinter,
771
+ '(1 + 0.15*numpy.log(1 + 53.5981500331442*fl_M_pas))',
772
+ ),
773
+ (
774
+ SciPyPrinter,
775
+ '(1 + 0.15*numpy.log(1 + 53.5981500331442*fl_M_pas))',
776
+ ),
777
+ (
778
+ CuPyPrinter,
779
+ '(1 + 0.15*cupy.log(1 + 53.5981500331442*fl_M_pas))',
780
+ ),
781
+ (
782
+ JaxPrinter,
783
+ '(1 + 0.15*jax.numpy.log(1 + 53.5981500331442*fl_M_pas))',
784
+ ),
785
+ (
786
+ MpmathPrinter,
787
+ '(1 + mpmath.mpf((0, 5404319552844595, -55, 53))*mpmath.log(1 '
788
+ '+ mpmath.mpf((0, 942908627019595, -44, 50))*fl_M_pas))',
789
+ ),
790
+ (
791
+ LambdaPrinter,
792
+ '(1 + 0.15*math.log(1 + 53.5981500331442*fl_M_pas))',
793
+ ),
794
+ ]
795
+ )
796
+ def test_print_code(self, code_printer, expected):
797
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
798
+ assert code_printer().doprint(fl_M_pas_inv) == expected
799
+
800
+ def test_derivative_print_code(self):
801
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
802
+ dfl_M_pas_inv_dfl_T = fl_M_pas_inv.diff(self.fl_M_pas)
803
+ expected = '32.1588900198865/(214.392600132577*fl_M_pas + 4.0)'
804
+ assert PythonCodePrinter().doprint(dfl_M_pas_inv_dfl_T) == expected
805
+
806
+ def test_lambdify(self):
807
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
808
+ fl_M_pas_inv_callable = lambdify(self.fl_M_pas, fl_M_pas_inv)
809
+ assert fl_M_pas_inv_callable(0.0) == pytest.approx(1.0)
810
+
811
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
812
+ def test_lambdify_numpy(self):
813
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
814
+ fl_M_pas_inv_callable = lambdify(self.fl_M_pas, fl_M_pas_inv, 'numpy')
815
+ fl_M_pas = numpy.array([-0.01, 0.0, 0.01, 0.02, 0.05, 0.1])
816
+ expected = numpy.array([
817
+ 0.8848253714,
818
+ 1.0,
819
+ 1.0643754386,
820
+ 1.1092744701,
821
+ 1.1954331425,
822
+ 1.2774998934,
823
+ ])
824
+ numpy.testing.assert_allclose(fl_M_pas_inv_callable(fl_M_pas), expected)
825
+
826
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
827
+ def test_lambdify_jax(self):
828
+ fl_M_pas_inv = FiberForceLengthPassiveInverseDeGroote2016.with_defaults(self.fl_M_pas)
829
+ fl_M_pas_inv_callable = jax.jit(lambdify(self.fl_M_pas, fl_M_pas_inv, 'jax'))
830
+ fl_M_pas = jax.numpy.array([-0.01, 0.0, 0.01, 0.02, 0.05, 0.1])
831
+ expected = jax.numpy.array([
832
+ 0.8848253714,
833
+ 1.0,
834
+ 1.0643754386,
835
+ 1.1092744701,
836
+ 1.1954331425,
837
+ 1.2774998934,
838
+ ])
839
+ numpy.testing.assert_allclose(fl_M_pas_inv_callable(fl_M_pas), expected)
840
+
841
+
842
+ class TestFiberForceLengthActiveDeGroote2016:
843
+
844
+ @pytest.fixture(autouse=True)
845
+ def _fiber_force_length_active_arguments_fixture(self):
846
+ self.l_M_tilde = Symbol('l_M_tilde')
847
+ self.c0 = Symbol('c_0')
848
+ self.c1 = Symbol('c_1')
849
+ self.c2 = Symbol('c_2')
850
+ self.c3 = Symbol('c_3')
851
+ self.c4 = Symbol('c_4')
852
+ self.c5 = Symbol('c_5')
853
+ self.c6 = Symbol('c_6')
854
+ self.c7 = Symbol('c_7')
855
+ self.c8 = Symbol('c_8')
856
+ self.c9 = Symbol('c_9')
857
+ self.c10 = Symbol('c_10')
858
+ self.c11 = Symbol('c_11')
859
+ self.constants = (
860
+ self.c0, self.c1, self.c2, self.c3, self.c4, self.c5,
861
+ self.c6, self.c7, self.c8, self.c9, self.c10, self.c11,
862
+ )
863
+
864
+ @staticmethod
865
+ def test_class():
866
+ assert issubclass(FiberForceLengthActiveDeGroote2016, Function)
867
+ assert issubclass(FiberForceLengthActiveDeGroote2016, CharacteristicCurveFunction)
868
+ assert FiberForceLengthActiveDeGroote2016.__name__ == 'FiberForceLengthActiveDeGroote2016'
869
+
870
+ def test_instance(self):
871
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
872
+ assert isinstance(fl_M_act, FiberForceLengthActiveDeGroote2016)
873
+ assert str(fl_M_act) == (
874
+ 'FiberForceLengthActiveDeGroote2016(l_M_tilde, c_0, c_1, c_2, c_3, '
875
+ 'c_4, c_5, c_6, c_7, c_8, c_9, c_10, c_11)'
876
+ )
877
+
878
+ def test_doit(self):
879
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants).doit()
880
+ assert fl_M_act == (
881
+ self.c0*exp(-(((self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde))**2)/2)
882
+ + self.c4*exp(-(((self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde))**2)/2)
883
+ + self.c8*exp(-(((self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde))**2)/2)
884
+ )
885
+
886
+ def test_doit_evaluate_false(self):
887
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants).doit(evaluate=False)
888
+ assert fl_M_act == (
889
+ self.c0*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde))**2)/2)
890
+ + self.c4*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde))**2)/2)
891
+ + self.c8*exp(-((UnevaluatedExpr(self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde))**2)/2)
892
+ )
893
+
894
+ def test_with_defaults(self):
895
+ constants = (
896
+ Float('0.814'),
897
+ Float('1.06'),
898
+ Float('0.162'),
899
+ Float('0.0633'),
900
+ Float('0.433'),
901
+ Float('0.717'),
902
+ Float('-0.0299'),
903
+ Float('0.2'),
904
+ Float('0.1'),
905
+ Float('1.0'),
906
+ Float('0.354'),
907
+ Float('0.0'),
908
+ )
909
+ fl_M_act_manual = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *constants)
910
+ fl_M_act_constants = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
911
+ assert fl_M_act_manual == fl_M_act_constants
912
+
913
+ def test_differentiate_wrt_l_M_tilde(self):
914
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
915
+ expected = (
916
+ self.c0*(
917
+ self.c3*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
918
+ + (self.c1 - self.l_M_tilde)/((self.c2 + self.c3*self.l_M_tilde)**2)
919
+ )*exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
920
+ + self.c4*(
921
+ self.c7*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
922
+ + (self.c5 - self.l_M_tilde)/((self.c6 + self.c7*self.l_M_tilde)**2)
923
+ )*exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
924
+ + self.c8*(
925
+ self.c11*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
926
+ + (self.c9 - self.l_M_tilde)/((self.c10 + self.c11*self.l_M_tilde)**2)
927
+ )*exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
928
+ )
929
+ assert fl_M_act.diff(self.l_M_tilde) == expected
930
+
931
+ def test_differentiate_wrt_c0(self):
932
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
933
+ expected = exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
934
+ assert fl_M_act.doit().diff(self.c0) == expected
935
+
936
+ def test_differentiate_wrt_c1(self):
937
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
938
+ expected = (
939
+ self.c0*(self.l_M_tilde - self.c1)/(self.c2 + self.c3*self.l_M_tilde)**2
940
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
941
+ )
942
+ assert fl_M_act.diff(self.c1) == expected
943
+
944
+ def test_differentiate_wrt_c2(self):
945
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
946
+ expected = (
947
+ self.c0*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
948
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
949
+ )
950
+ assert fl_M_act.diff(self.c2) == expected
951
+
952
+ def test_differentiate_wrt_c3(self):
953
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
954
+ expected = (
955
+ self.c0*self.l_M_tilde*(self.l_M_tilde - self.c1)**2/(self.c2 + self.c3*self.l_M_tilde)**3
956
+ *exp(-(self.l_M_tilde - self.c1)**2/(2*(self.c2 + self.c3*self.l_M_tilde)**2))
957
+ )
958
+ assert fl_M_act.diff(self.c3) == expected
959
+
960
+ def test_differentiate_wrt_c4(self):
961
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
962
+ expected = exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
963
+ assert fl_M_act.diff(self.c4) == expected
964
+
965
+ def test_differentiate_wrt_c5(self):
966
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
967
+ expected = (
968
+ self.c4*(self.l_M_tilde - self.c5)/(self.c6 + self.c7*self.l_M_tilde)**2
969
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
970
+ )
971
+ assert fl_M_act.diff(self.c5) == expected
972
+
973
+ def test_differentiate_wrt_c6(self):
974
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
975
+ expected = (
976
+ self.c4*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
977
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
978
+ )
979
+ assert fl_M_act.diff(self.c6) == expected
980
+
981
+ def test_differentiate_wrt_c7(self):
982
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
983
+ expected = (
984
+ self.c4*self.l_M_tilde*(self.l_M_tilde - self.c5)**2/(self.c6 + self.c7*self.l_M_tilde)**3
985
+ *exp(-(self.l_M_tilde - self.c5)**2/(2*(self.c6 + self.c7*self.l_M_tilde)**2))
986
+ )
987
+ assert fl_M_act.diff(self.c7) == expected
988
+
989
+ def test_differentiate_wrt_c8(self):
990
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
991
+ expected = exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
992
+ assert fl_M_act.diff(self.c8) == expected
993
+
994
+ def test_differentiate_wrt_c9(self):
995
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
996
+ expected = (
997
+ self.c8*(self.l_M_tilde - self.c9)/(self.c10 + self.c11*self.l_M_tilde)**2
998
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
999
+ )
1000
+ assert fl_M_act.diff(self.c9) == expected
1001
+
1002
+ def test_differentiate_wrt_c10(self):
1003
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1004
+ expected = (
1005
+ self.c8*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
1006
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
1007
+ )
1008
+ assert fl_M_act.diff(self.c10) == expected
1009
+
1010
+ def test_differentiate_wrt_c11(self):
1011
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1012
+ expected = (
1013
+ self.c8*self.l_M_tilde*(self.l_M_tilde - self.c9)**2/(self.c10 + self.c11*self.l_M_tilde)**3
1014
+ *exp(-(self.l_M_tilde - self.c9)**2/(2*(self.c10 + self.c11*self.l_M_tilde)**2))
1015
+ )
1016
+ assert fl_M_act.diff(self.c11) == expected
1017
+
1018
+ def test_function_print_latex(self):
1019
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1020
+ expected = r'\operatorname{fl}^M_{act} \left( l_{M tilde} \right)'
1021
+ assert LatexPrinter().doprint(fl_M_act) == expected
1022
+
1023
+ def test_expression_print_latex(self):
1024
+ fl_M_act = FiberForceLengthActiveDeGroote2016(self.l_M_tilde, *self.constants)
1025
+ expected = (
1026
+ r'c_{0} e^{- \frac{\left(- c_{1} + l_{M tilde}\right)^{2}}{2 \left(c_{2} + c_{3} l_{M tilde}\right)^{2}}} '
1027
+ r'+ c_{4} e^{- \frac{\left(- c_{5} + l_{M tilde}\right)^{2}}{2 \left(c_{6} + c_{7} l_{M tilde}\right)^{2}}} '
1028
+ r'+ c_{8} e^{- \frac{\left(- c_{9} + l_{M tilde}\right)^{2}}{2 \left(c_{10} + c_{11} l_{M tilde}\right)^{2}}}'
1029
+ )
1030
+ assert LatexPrinter().doprint(fl_M_act.doit()) == expected
1031
+
1032
+ @pytest.mark.parametrize(
1033
+ 'code_printer, expected',
1034
+ [
1035
+ (
1036
+ C89CodePrinter,
1037
+ (
1038
+ '(0.81399999999999995*exp(-1.0/2.0*pow(l_M_tilde - 1.0600000000000001, 2)/pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*exp(-1.0/2.0*pow(l_M_tilde - 0.71699999999999997, 2)/pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*exp(-3.9899134986753491*pow(l_M_tilde - 1.0, 2)))'
1039
+ ),
1040
+ ),
1041
+ (
1042
+ C99CodePrinter,
1043
+ (
1044
+ '(0.81399999999999995*exp(-1.0/2.0*pow(l_M_tilde - 1.0600000000000001, 2)/pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*exp(-1.0/2.0*pow(l_M_tilde - 0.71699999999999997, 2)/pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*exp(-3.9899134986753491*pow(l_M_tilde - 1.0, 2)))'
1045
+ ),
1046
+ ),
1047
+ (
1048
+ C11CodePrinter,
1049
+ (
1050
+ '(0.81399999999999995*exp(-1.0/2.0*pow(l_M_tilde - 1.0600000000000001, 2)/pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*exp(-1.0/2.0*pow(l_M_tilde - 0.71699999999999997, 2)/pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*exp(-3.9899134986753491*pow(l_M_tilde - 1.0, 2)))'
1051
+ ),
1052
+ ),
1053
+ (
1054
+ CXX98CodePrinter,
1055
+ (
1056
+ '(0.81399999999999995*exp(-1.0/2.0*std::pow(l_M_tilde - 1.0600000000000001, 2)/std::pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*exp(-1.0/2.0*std::pow(l_M_tilde - 0.71699999999999997, 2)/std::pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*exp(-3.9899134986753491*std::pow(l_M_tilde - 1.0, 2)))'
1057
+ ),
1058
+ ),
1059
+ (
1060
+ CXX11CodePrinter,
1061
+ (
1062
+ '(0.81399999999999995*std::exp(-1.0/2.0*std::pow(l_M_tilde - 1.0600000000000001, 2)/std::pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*std::exp(-1.0/2.0*std::pow(l_M_tilde - 0.71699999999999997, 2)/std::pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*std::exp(-3.9899134986753491*std::pow(l_M_tilde - 1.0, 2)))'
1063
+ ),
1064
+ ),
1065
+ (
1066
+ CXX17CodePrinter,
1067
+ (
1068
+ '(0.81399999999999995*std::exp(-1.0/2.0*std::pow(l_M_tilde - 1.0600000000000001, 2)/std::pow(0.063299999999999995*l_M_tilde + 0.16200000000000001, 2)) + 0.433*std::exp(-1.0/2.0*std::pow(l_M_tilde - 0.71699999999999997, 2)/std::pow(0.20000000000000001*l_M_tilde - 0.029899999999999999, 2)) + 0.10000000000000001*std::exp(-3.9899134986753491*std::pow(l_M_tilde - 1.0, 2)))'
1069
+ ),
1070
+ ),
1071
+ (
1072
+ FCodePrinter,
1073
+ (
1074
+ ' (0.814d0*exp(-0.5d0*(l_M_tilde - 1.06d0)**2/(\n'
1075
+ ' @ 0.063299999999999995d0*l_M_tilde + 0.16200000000000001d0)**2) +\n'
1076
+ ' @ 0.433d0*exp(-0.5d0*(l_M_tilde - 0.717d0)**2/(\n'
1077
+ ' @ 0.20000000000000001d0*l_M_tilde - 0.029899999999999999d0)**2) +\n'
1078
+ ' @ 0.1d0*exp(-3.9899134986753491d0*(l_M_tilde - 1.0d0)**2))'
1079
+ ),
1080
+ ),
1081
+ (
1082
+ OctaveCodePrinter,
1083
+ (
1084
+ '(0.814*exp(-(l_M_tilde - 1.06).^2./(2*(0.0633*l_M_tilde + 0.162).^2)) + 0.433*exp(-(l_M_tilde - 0.717).^2./(2*(0.2*l_M_tilde - 0.0299).^2)) + 0.1*exp(-3.98991349867535*(l_M_tilde - 1.0).^2))'
1085
+ ),
1086
+ ),
1087
+ (
1088
+ PythonCodePrinter,
1089
+ (
1090
+ '(0.814*math.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*math.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1091
+ ),
1092
+ ),
1093
+ (
1094
+ NumPyPrinter,
1095
+ (
1096
+ '(0.814*numpy.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*numpy.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1097
+ ),
1098
+ ),
1099
+ (
1100
+ SciPyPrinter,
1101
+ (
1102
+ '(0.814*numpy.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*numpy.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1103
+ ),
1104
+ ),
1105
+ (
1106
+ CuPyPrinter,
1107
+ (
1108
+ '(0.814*cupy.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*cupy.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*cupy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1109
+ ),
1110
+ ),
1111
+ (
1112
+ JaxPrinter,
1113
+ (
1114
+ '(0.814*jax.numpy.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*jax.numpy.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*jax.numpy.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1115
+ ),
1116
+ ),
1117
+ (
1118
+ MpmathPrinter,
1119
+ (
1120
+ '(mpmath.mpf((0, 7331860193359167, -53, 53))*mpmath.exp(-mpmath.mpf(1)/mpmath.mpf(2)*(l_M_tilde + mpmath.mpf((1, 2386907802506363, -51, 52)))**2/(mpmath.mpf((0, 2280622851300419, -55, 52))*l_M_tilde + mpmath.mpf((0, 5836665117072163, -55, 53)))**2) + mpmath.mpf((0, 7800234554605699, -54, 53))*mpmath.exp(-mpmath.mpf(1)/mpmath.mpf(2)*(l_M_tilde + mpmath.mpf((1, 6458161865649291, -53, 53)))**2/(mpmath.mpf((0, 3602879701896397, -54, 52))*l_M_tilde + mpmath.mpf((1, 8618088246936181, -58, 53)))**2) + mpmath.mpf((0, 3602879701896397, -55, 52))*mpmath.exp(-mpmath.mpf((0, 8984486472937407, -51, 53))*(l_M_tilde + mpmath.mpf((1, 1, 0, 1)))**2))'
1121
+ ),
1122
+ ),
1123
+ (
1124
+ LambdaPrinter,
1125
+ (
1126
+ '(0.814*math.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2) + 0.433*math.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + 0.1*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2))'
1127
+ ),
1128
+ ),
1129
+ ]
1130
+ )
1131
+ def test_print_code(self, code_printer, expected):
1132
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1133
+ assert code_printer().doprint(fl_M_act) == expected
1134
+
1135
+ def test_derivative_print_code(self):
1136
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1137
+ fl_M_act_dl_M_tilde = fl_M_act.diff(self.l_M_tilde)
1138
+ expected = (
1139
+ '(0.79798269973507 - 0.79798269973507*l_M_tilde)*math.exp(-3.98991349867535*(l_M_tilde - 1.0)**2) + (0.433*(0.717 - l_M_tilde)/(0.2*l_M_tilde - 0.0299)**2 + 0.0866*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**3)*math.exp(-1/2*(l_M_tilde - 0.717)**2/(0.2*l_M_tilde - 0.0299)**2) + (0.814*(1.06 - l_M_tilde)/(0.0633*l_M_tilde + 0.162)**2 + 0.0515262*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**3)*math.exp(-1/2*(l_M_tilde - 1.06)**2/(0.0633*l_M_tilde + 0.162)**2)'
1140
+ )
1141
+ assert PythonCodePrinter().doprint(fl_M_act_dl_M_tilde) == expected
1142
+
1143
+ def test_lambdify(self):
1144
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1145
+ fl_M_act_callable = lambdify(self.l_M_tilde, fl_M_act)
1146
+ assert fl_M_act_callable(1.0) == pytest.approx(0.9941398866)
1147
+
1148
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1149
+ def test_lambdify_numpy(self):
1150
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1151
+ fl_M_act_callable = lambdify(self.l_M_tilde, fl_M_act, 'numpy')
1152
+ l_M_tilde = numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
1153
+ expected = numpy.array([
1154
+ 0.0018501319,
1155
+ 0.0529122812,
1156
+ 0.9941398866,
1157
+ 0.2312431531,
1158
+ 0.0069595432,
1159
+ ])
1160
+ numpy.testing.assert_allclose(fl_M_act_callable(l_M_tilde), expected)
1161
+
1162
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1163
+ def test_lambdify_jax(self):
1164
+ fl_M_act = FiberForceLengthActiveDeGroote2016.with_defaults(self.l_M_tilde)
1165
+ fl_M_act_callable = jax.jit(lambdify(self.l_M_tilde, fl_M_act, 'jax'))
1166
+ l_M_tilde = jax.numpy.array([0.0, 0.5, 1.0, 1.5, 2.0])
1167
+ expected = jax.numpy.array([
1168
+ 0.0018501319,
1169
+ 0.0529122812,
1170
+ 0.9941398866,
1171
+ 0.2312431531,
1172
+ 0.0069595432,
1173
+ ])
1174
+ numpy.testing.assert_allclose(fl_M_act_callable(l_M_tilde), expected)
1175
+
1176
+
1177
+ class TestFiberForceVelocityDeGroote2016:
1178
+
1179
+ @pytest.fixture(autouse=True)
1180
+ def _muscle_fiber_force_velocity_arguments_fixture(self):
1181
+ self.v_M_tilde = Symbol('v_M_tilde')
1182
+ self.c0 = Symbol('c_0')
1183
+ self.c1 = Symbol('c_1')
1184
+ self.c2 = Symbol('c_2')
1185
+ self.c3 = Symbol('c_3')
1186
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
1187
+
1188
+ @staticmethod
1189
+ def test_class():
1190
+ assert issubclass(FiberForceVelocityDeGroote2016, Function)
1191
+ assert issubclass(FiberForceVelocityDeGroote2016, CharacteristicCurveFunction)
1192
+ assert FiberForceVelocityDeGroote2016.__name__ == 'FiberForceVelocityDeGroote2016'
1193
+
1194
+ def test_instance(self):
1195
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1196
+ assert isinstance(fv_M, FiberForceVelocityDeGroote2016)
1197
+ assert str(fv_M) == 'FiberForceVelocityDeGroote2016(v_M_tilde, c_0, c_1, c_2, c_3)'
1198
+
1199
+ def test_doit(self):
1200
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants).doit()
1201
+ expected = (
1202
+ self.c0 * log((self.c1 * self.v_M_tilde + self.c2)
1203
+ + sqrt((self.c1 * self.v_M_tilde + self.c2)**2 + 1)) + self.c3
1204
+ )
1205
+ assert fv_M == expected
1206
+
1207
+ def test_doit_evaluate_false(self):
1208
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants).doit(evaluate=False)
1209
+ expected = (
1210
+ self.c0 * log((self.c1 * self.v_M_tilde + self.c2)
1211
+ + sqrt(UnevaluatedExpr(self.c1 * self.v_M_tilde + self.c2)**2 + 1)) + self.c3
1212
+ )
1213
+ assert fv_M == expected
1214
+
1215
+ def test_with_defaults(self):
1216
+ constants = (
1217
+ Float('-0.318'),
1218
+ Float('-8.149'),
1219
+ Float('-0.374'),
1220
+ Float('0.886'),
1221
+ )
1222
+ fv_M_manual = FiberForceVelocityDeGroote2016(self.v_M_tilde, *constants)
1223
+ fv_M_constants = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1224
+ assert fv_M_manual == fv_M_constants
1225
+
1226
+ def test_differentiate_wrt_v_M_tilde(self):
1227
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1228
+ expected = (
1229
+ self.c0*self.c1
1230
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1231
+ )
1232
+ assert fv_M.diff(self.v_M_tilde) == expected
1233
+
1234
+ def test_differentiate_wrt_c0(self):
1235
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1236
+ expected = log(
1237
+ self.c1*self.v_M_tilde + self.c2
1238
+ + sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1239
+ )
1240
+ assert fv_M.diff(self.c0) == expected
1241
+
1242
+ def test_differentiate_wrt_c1(self):
1243
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1244
+ expected = (
1245
+ self.c0*self.v_M_tilde
1246
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1247
+ )
1248
+ assert fv_M.diff(self.c1) == expected
1249
+
1250
+ def test_differentiate_wrt_c2(self):
1251
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1252
+ expected = (
1253
+ self.c0
1254
+ /sqrt(UnevaluatedExpr(self.c1*self.v_M_tilde + self.c2)**2 + 1)
1255
+ )
1256
+ assert fv_M.diff(self.c2) == expected
1257
+
1258
+ def test_differentiate_wrt_c3(self):
1259
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1260
+ expected = Integer(1)
1261
+ assert fv_M.diff(self.c3) == expected
1262
+
1263
+ def test_inverse(self):
1264
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1265
+ assert fv_M.inverse() is FiberForceVelocityInverseDeGroote2016
1266
+
1267
+ def test_function_print_latex(self):
1268
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1269
+ expected = r'\operatorname{fv}^M \left( v_{M tilde} \right)'
1270
+ assert LatexPrinter().doprint(fv_M) == expected
1271
+
1272
+ def test_expression_print_latex(self):
1273
+ fv_M = FiberForceVelocityDeGroote2016(self.v_M_tilde, *self.constants)
1274
+ expected = (
1275
+ r'c_{0} \log{\left(c_{1} v_{M tilde} + c_{2} + \sqrt{\left(c_{1} '
1276
+ r'v_{M tilde} + c_{2}\right)^{2} + 1} \right)} + c_{3}'
1277
+ )
1278
+ assert LatexPrinter().doprint(fv_M.doit()) == expected
1279
+
1280
+ @pytest.mark.parametrize(
1281
+ 'code_printer, expected',
1282
+ [
1283
+ (
1284
+ C89CodePrinter,
1285
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1286
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1287
+ ),
1288
+ (
1289
+ C99CodePrinter,
1290
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1291
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1292
+ ),
1293
+ (
1294
+ C11CodePrinter,
1295
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1296
+ '- 0.374 + sqrt(1 + pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1297
+ ),
1298
+ (
1299
+ CXX98CodePrinter,
1300
+ '(0.88600000000000001 - 0.318*log(-8.1489999999999991*v_M_tilde '
1301
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1302
+ ),
1303
+ (
1304
+ CXX11CodePrinter,
1305
+ '(0.88600000000000001 - 0.318*std::log(-8.1489999999999991*v_M_tilde '
1306
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1307
+ ),
1308
+ (
1309
+ CXX17CodePrinter,
1310
+ '(0.88600000000000001 - 0.318*std::log(-8.1489999999999991*v_M_tilde '
1311
+ '- 0.374 + std::sqrt(1 + std::pow(-8.1489999999999991*v_M_tilde - 0.374, 2))))',
1312
+ ),
1313
+ (
1314
+ FCodePrinter,
1315
+ ' (0.886d0 - 0.318d0*log(-8.1489999999999991d0*v_M_tilde - 0.374d0 +\n'
1316
+ ' @ sqrt(1.0d0 + (-8.149d0*v_M_tilde - 0.374d0)**2)))',
1317
+ ),
1318
+ (
1319
+ OctaveCodePrinter,
1320
+ '(0.886 - 0.318*log(-8.149*v_M_tilde - 0.374 '
1321
+ '+ sqrt(1 + (-8.149*v_M_tilde - 0.374).^2)))',
1322
+ ),
1323
+ (
1324
+ PythonCodePrinter,
1325
+ '(0.886 - 0.318*math.log(-8.149*v_M_tilde - 0.374 '
1326
+ '+ math.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1327
+ ),
1328
+ (
1329
+ NumPyPrinter,
1330
+ '(0.886 - 0.318*numpy.log(-8.149*v_M_tilde - 0.374 '
1331
+ '+ numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1332
+ ),
1333
+ (
1334
+ SciPyPrinter,
1335
+ '(0.886 - 0.318*numpy.log(-8.149*v_M_tilde - 0.374 '
1336
+ '+ numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1337
+ ),
1338
+ (
1339
+ CuPyPrinter,
1340
+ '(0.886 - 0.318*cupy.log(-8.149*v_M_tilde - 0.374 '
1341
+ '+ cupy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1342
+ ),
1343
+ (
1344
+ JaxPrinter,
1345
+ '(0.886 - 0.318*jax.numpy.log(-8.149*v_M_tilde - 0.374 '
1346
+ '+ jax.numpy.sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1347
+ ),
1348
+ (
1349
+ MpmathPrinter,
1350
+ '(mpmath.mpf((0, 7980378539700519, -53, 53)) '
1351
+ '- mpmath.mpf((0, 5728578726015271, -54, 53))'
1352
+ '*mpmath.log(-mpmath.mpf((0, 4587479170430271, -49, 53))*v_M_tilde '
1353
+ '+ mpmath.mpf((1, 3368692521273131, -53, 52)) '
1354
+ '+ mpmath.sqrt(1 + (-mpmath.mpf((0, 4587479170430271, -49, 53))*v_M_tilde '
1355
+ '+ mpmath.mpf((1, 3368692521273131, -53, 52)))**2)))',
1356
+ ),
1357
+ (
1358
+ LambdaPrinter,
1359
+ '(0.886 - 0.318*math.log(-8.149*v_M_tilde - 0.374 '
1360
+ '+ sqrt(1 + (-8.149*v_M_tilde - 0.374)**2)))',
1361
+ ),
1362
+ ]
1363
+ )
1364
+ def test_print_code(self, code_printer, expected):
1365
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1366
+ assert code_printer().doprint(fv_M) == expected
1367
+
1368
+ def test_derivative_print_code(self):
1369
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1370
+ dfv_M_dv_M_tilde = fv_M.diff(self.v_M_tilde)
1371
+ expected = '2.591382*(1 + (-8.149*v_M_tilde - 0.374)**2)**(-1/2)'
1372
+ assert PythonCodePrinter().doprint(dfv_M_dv_M_tilde) == expected
1373
+
1374
+ def test_lambdify(self):
1375
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1376
+ fv_M_callable = lambdify(self.v_M_tilde, fv_M)
1377
+ assert fv_M_callable(0.0) == pytest.approx(1.002320622548512)
1378
+
1379
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1380
+ def test_lambdify_numpy(self):
1381
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1382
+ fv_M_callable = lambdify(self.v_M_tilde, fv_M, 'numpy')
1383
+ v_M_tilde = numpy.array([-1.0, -0.5, 0.0, 0.5])
1384
+ expected = numpy.array([
1385
+ 0.0120816781,
1386
+ 0.2438336294,
1387
+ 1.0023206225,
1388
+ 1.5850003903,
1389
+ ])
1390
+ numpy.testing.assert_allclose(fv_M_callable(v_M_tilde), expected)
1391
+
1392
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1393
+ def test_lambdify_jax(self):
1394
+ fv_M = FiberForceVelocityDeGroote2016.with_defaults(self.v_M_tilde)
1395
+ fv_M_callable = jax.jit(lambdify(self.v_M_tilde, fv_M, 'jax'))
1396
+ v_M_tilde = jax.numpy.array([-1.0, -0.5, 0.0, 0.5])
1397
+ expected = jax.numpy.array([
1398
+ 0.0120816781,
1399
+ 0.2438336294,
1400
+ 1.0023206225,
1401
+ 1.5850003903,
1402
+ ])
1403
+ numpy.testing.assert_allclose(fv_M_callable(v_M_tilde), expected)
1404
+
1405
+
1406
+ class TestFiberForceVelocityInverseDeGroote2016:
1407
+
1408
+ @pytest.fixture(autouse=True)
1409
+ def _tendon_force_length_inverse_arguments_fixture(self):
1410
+ self.fv_M = Symbol('fv_M')
1411
+ self.c0 = Symbol('c_0')
1412
+ self.c1 = Symbol('c_1')
1413
+ self.c2 = Symbol('c_2')
1414
+ self.c3 = Symbol('c_3')
1415
+ self.constants = (self.c0, self.c1, self.c2, self.c3)
1416
+
1417
+ @staticmethod
1418
+ def test_class():
1419
+ assert issubclass(FiberForceVelocityInverseDeGroote2016, Function)
1420
+ assert issubclass(FiberForceVelocityInverseDeGroote2016, CharacteristicCurveFunction)
1421
+ assert FiberForceVelocityInverseDeGroote2016.__name__ == 'FiberForceVelocityInverseDeGroote2016'
1422
+
1423
+ def test_instance(self):
1424
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1425
+ assert isinstance(fv_M_inv, FiberForceVelocityInverseDeGroote2016)
1426
+ assert str(fv_M_inv) == 'FiberForceVelocityInverseDeGroote2016(fv_M, c_0, c_1, c_2, c_3)'
1427
+
1428
+ def test_doit(self):
1429
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants).doit()
1430
+ assert fv_M_inv == (sinh((self.fv_M - self.c3)/self.c0) - self.c2)/self.c1
1431
+
1432
+ def test_doit_evaluate_false(self):
1433
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants).doit(evaluate=False)
1434
+ assert fv_M_inv == (sinh(UnevaluatedExpr(self.fv_M - self.c3)/self.c0) - self.c2)/self.c1
1435
+
1436
+ def test_with_defaults(self):
1437
+ constants = (
1438
+ Float('-0.318'),
1439
+ Float('-8.149'),
1440
+ Float('-0.374'),
1441
+ Float('0.886'),
1442
+ )
1443
+ fv_M_inv_manual = FiberForceVelocityInverseDeGroote2016(self.fv_M, *constants)
1444
+ fv_M_inv_constants = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1445
+ assert fv_M_inv_manual == fv_M_inv_constants
1446
+
1447
+ def test_differentiate_wrt_fv_M(self):
1448
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1449
+ expected = cosh((self.fv_M - self.c3)/self.c0)/(self.c0*self.c1)
1450
+ assert fv_M_inv.diff(self.fv_M) == expected
1451
+
1452
+ def test_differentiate_wrt_c0(self):
1453
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1454
+ expected = (self.c3 - self.fv_M)*cosh((self.fv_M - self.c3)/self.c0)/(self.c0**2*self.c1)
1455
+ assert fv_M_inv.diff(self.c0) == expected
1456
+
1457
+ def test_differentiate_wrt_c1(self):
1458
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1459
+ expected = (self.c2 - sinh((self.fv_M - self.c3)/self.c0))/self.c1**2
1460
+ assert fv_M_inv.diff(self.c1) == expected
1461
+
1462
+ def test_differentiate_wrt_c2(self):
1463
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1464
+ expected = -1/self.c1
1465
+ assert fv_M_inv.diff(self.c2) == expected
1466
+
1467
+ def test_differentiate_wrt_c3(self):
1468
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1469
+ expected = -cosh((self.fv_M - self.c3)/self.c0)/(self.c0*self.c1)
1470
+ assert fv_M_inv.diff(self.c3) == expected
1471
+
1472
+ def test_inverse(self):
1473
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1474
+ assert fv_M_inv.inverse() is FiberForceVelocityDeGroote2016
1475
+
1476
+ def test_function_print_latex(self):
1477
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1478
+ expected = r'\left( \operatorname{fv}^M \right)^{-1} \left( fv_{M} \right)'
1479
+ assert LatexPrinter().doprint(fv_M_inv) == expected
1480
+
1481
+ def test_expression_print_latex(self):
1482
+ fv_M = FiberForceVelocityInverseDeGroote2016(self.fv_M, *self.constants)
1483
+ expected = r'\frac{- c_{2} + \sinh{\left(\frac{- c_{3} + fv_{M}}{c_{0}} \right)}}{c_{1}}'
1484
+ assert LatexPrinter().doprint(fv_M.doit()) == expected
1485
+
1486
+ @pytest.mark.parametrize(
1487
+ 'code_printer, expected',
1488
+ [
1489
+ (
1490
+ C89CodePrinter,
1491
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1492
+ '- 0.88600000000000001))))',
1493
+ ),
1494
+ (
1495
+ C99CodePrinter,
1496
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1497
+ '- 0.88600000000000001))))',
1498
+ ),
1499
+ (
1500
+ C11CodePrinter,
1501
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1502
+ '- 0.88600000000000001))))',
1503
+ ),
1504
+ (
1505
+ CXX98CodePrinter,
1506
+ '(-0.12271444348999878*(0.374 - sinh(3.1446540880503142*(fv_M '
1507
+ '- 0.88600000000000001))))',
1508
+ ),
1509
+ (
1510
+ CXX11CodePrinter,
1511
+ '(-0.12271444348999878*(0.374 - std::sinh(3.1446540880503142'
1512
+ '*(fv_M - 0.88600000000000001))))',
1513
+ ),
1514
+ (
1515
+ CXX17CodePrinter,
1516
+ '(-0.12271444348999878*(0.374 - std::sinh(3.1446540880503142'
1517
+ '*(fv_M - 0.88600000000000001))))',
1518
+ ),
1519
+ (
1520
+ FCodePrinter,
1521
+ ' (-0.122714443489999d0*(0.374d0 - sinh(3.1446540880503142d0*(fv_M -\n'
1522
+ ' @ 0.886d0))))',
1523
+ ),
1524
+ (
1525
+ OctaveCodePrinter,
1526
+ '(-0.122714443489999*(0.374 - sinh(3.14465408805031*(fv_M '
1527
+ '- 0.886))))',
1528
+ ),
1529
+ (
1530
+ PythonCodePrinter,
1531
+ '(-0.122714443489999*(0.374 - math.sinh(3.14465408805031*(fv_M '
1532
+ '- 0.886))))',
1533
+ ),
1534
+ (
1535
+ NumPyPrinter,
1536
+ '(-0.122714443489999*(0.374 - numpy.sinh(3.14465408805031'
1537
+ '*(fv_M - 0.886))))',
1538
+ ),
1539
+ (
1540
+ SciPyPrinter,
1541
+ '(-0.122714443489999*(0.374 - numpy.sinh(3.14465408805031'
1542
+ '*(fv_M - 0.886))))',
1543
+ ),
1544
+ (
1545
+ CuPyPrinter,
1546
+ '(-0.122714443489999*(0.374 - cupy.sinh(3.14465408805031*(fv_M '
1547
+ '- 0.886))))',
1548
+ ),
1549
+ (
1550
+ JaxPrinter,
1551
+ '(-0.122714443489999*(0.374 - jax.numpy.sinh(3.14465408805031'
1552
+ '*(fv_M - 0.886))))',
1553
+ ),
1554
+ (
1555
+ MpmathPrinter,
1556
+ '(-mpmath.mpf((0, 8842507551592581, -56, 53))*(mpmath.mpf((0, '
1557
+ '3368692521273131, -53, 52)) - mpmath.sinh(mpmath.mpf((0, '
1558
+ '7081131489576251, -51, 53))*(fv_M + mpmath.mpf((1, '
1559
+ '7980378539700519, -53, 53))))))',
1560
+ ),
1561
+ (
1562
+ LambdaPrinter,
1563
+ '(-0.122714443489999*(0.374 - math.sinh(3.14465408805031*(fv_M '
1564
+ '- 0.886))))',
1565
+ ),
1566
+ ]
1567
+ )
1568
+ def test_print_code(self, code_printer, expected):
1569
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1570
+ assert code_printer().doprint(fv_M_inv) == expected
1571
+
1572
+ def test_derivative_print_code(self):
1573
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1574
+ dfv_M_inv_dfv_M = fv_M_inv.diff(self.fv_M)
1575
+ expected = (
1576
+ '0.385894476383644*math.cosh(3.14465408805031*fv_M '
1577
+ '- 2.78616352201258)'
1578
+ )
1579
+ assert PythonCodePrinter().doprint(dfv_M_inv_dfv_M) == expected
1580
+
1581
+ def test_lambdify(self):
1582
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1583
+ fv_M_inv_callable = lambdify(self.fv_M, fv_M_inv)
1584
+ assert fv_M_inv_callable(1.0) == pytest.approx(-0.0009548832444487479)
1585
+
1586
+ @pytest.mark.skipif(numpy is None, reason='NumPy not installed')
1587
+ def test_lambdify_numpy(self):
1588
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1589
+ fv_M_inv_callable = lambdify(self.fv_M, fv_M_inv, 'numpy')
1590
+ fv_M = numpy.array([0.8, 0.9, 1.0, 1.1, 1.2])
1591
+ expected = numpy.array([
1592
+ -0.0794881459,
1593
+ -0.0404909338,
1594
+ -0.0009548832,
1595
+ 0.043061991,
1596
+ 0.0959484397,
1597
+ ])
1598
+ numpy.testing.assert_allclose(fv_M_inv_callable(fv_M), expected)
1599
+
1600
+ @pytest.mark.skipif(jax is None, reason='JAX not installed')
1601
+ def test_lambdify_jax(self):
1602
+ fv_M_inv = FiberForceVelocityInverseDeGroote2016.with_defaults(self.fv_M)
1603
+ fv_M_inv_callable = jax.jit(lambdify(self.fv_M, fv_M_inv, 'jax'))
1604
+ fv_M = jax.numpy.array([0.8, 0.9, 1.0, 1.1, 1.2])
1605
+ expected = jax.numpy.array([
1606
+ -0.0794881459,
1607
+ -0.0404909338,
1608
+ -0.0009548832,
1609
+ 0.043061991,
1610
+ 0.0959484397,
1611
+ ])
1612
+ numpy.testing.assert_allclose(fv_M_inv_callable(fv_M), expected)
1613
+
1614
+
1615
+ class TestCharacteristicCurveCollection:
1616
+
1617
+ @staticmethod
1618
+ def test_valid_constructor():
1619
+ curves = CharacteristicCurveCollection(
1620
+ tendon_force_length=TendonForceLengthDeGroote2016,
1621
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1622
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1623
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1624
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1625
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1626
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1627
+ )
1628
+ assert curves.tendon_force_length is TendonForceLengthDeGroote2016
1629
+ assert curves.tendon_force_length_inverse is TendonForceLengthInverseDeGroote2016
1630
+ assert curves.fiber_force_length_passive is FiberForceLengthPassiveDeGroote2016
1631
+ assert curves.fiber_force_length_passive_inverse is FiberForceLengthPassiveInverseDeGroote2016
1632
+ assert curves.fiber_force_length_active is FiberForceLengthActiveDeGroote2016
1633
+ assert curves.fiber_force_velocity is FiberForceVelocityDeGroote2016
1634
+ assert curves.fiber_force_velocity_inverse is FiberForceVelocityInverseDeGroote2016
1635
+
1636
+ @staticmethod
1637
+ @pytest.mark.skip(reason='kw_only dataclasses only valid in Python >3.10')
1638
+ def test_invalid_constructor_keyword_only():
1639
+ with pytest.raises(TypeError):
1640
+ _ = CharacteristicCurveCollection(
1641
+ TendonForceLengthDeGroote2016,
1642
+ TendonForceLengthInverseDeGroote2016,
1643
+ FiberForceLengthPassiveDeGroote2016,
1644
+ FiberForceLengthPassiveInverseDeGroote2016,
1645
+ FiberForceLengthActiveDeGroote2016,
1646
+ FiberForceVelocityDeGroote2016,
1647
+ FiberForceVelocityInverseDeGroote2016,
1648
+ )
1649
+
1650
+ @staticmethod
1651
+ @pytest.mark.parametrize(
1652
+ 'kwargs',
1653
+ [
1654
+ {'tendon_force_length': TendonForceLengthDeGroote2016},
1655
+ {
1656
+ 'tendon_force_length': TendonForceLengthDeGroote2016,
1657
+ 'tendon_force_length_inverse': TendonForceLengthInverseDeGroote2016,
1658
+ 'fiber_force_length_passive': FiberForceLengthPassiveDeGroote2016,
1659
+ 'fiber_force_length_passive_inverse': FiberForceLengthPassiveInverseDeGroote2016,
1660
+ 'fiber_force_length_active': FiberForceLengthActiveDeGroote2016,
1661
+ 'fiber_force_velocity': FiberForceVelocityDeGroote2016,
1662
+ 'fiber_force_velocity_inverse': FiberForceVelocityInverseDeGroote2016,
1663
+ 'extra_kwarg': None,
1664
+ },
1665
+ ]
1666
+ )
1667
+ def test_invalid_constructor_wrong_number_args(kwargs):
1668
+ with pytest.raises(TypeError):
1669
+ _ = CharacteristicCurveCollection(**kwargs)
1670
+
1671
+ @staticmethod
1672
+ def test_instance_is_immutable():
1673
+ curves = CharacteristicCurveCollection(
1674
+ tendon_force_length=TendonForceLengthDeGroote2016,
1675
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
1676
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
1677
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
1678
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
1679
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
1680
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
1681
+ )
1682
+ with pytest.raises(AttributeError):
1683
+ curves.tendon_force_length = None
1684
+ with pytest.raises(AttributeError):
1685
+ curves.tendon_force_length_inverse = None
1686
+ with pytest.raises(AttributeError):
1687
+ curves.fiber_force_length_passive = None
1688
+ with pytest.raises(AttributeError):
1689
+ curves.fiber_force_length_passive_inverse = None
1690
+ with pytest.raises(AttributeError):
1691
+ curves.fiber_force_length_active = None
1692
+ with pytest.raises(AttributeError):
1693
+ curves.fiber_force_velocity = None
1694
+ with pytest.raises(AttributeError):
1695
+ curves.fiber_force_velocity_inverse = None
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_mixin.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics._mixin.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy.physics.biomechanics._mixin import _NamedMixin
6
+
7
+
8
+ class TestNamedMixin:
9
+
10
+ @staticmethod
11
+ def test_subclass():
12
+
13
+ class Subclass(_NamedMixin):
14
+
15
+ def __init__(self, name):
16
+ self.name = name
17
+
18
+ instance = Subclass('name')
19
+ assert instance.name == 'name'
20
+
21
+ @pytest.fixture(autouse=True)
22
+ def _named_mixin_fixture(self):
23
+
24
+ class Subclass(_NamedMixin):
25
+
26
+ def __init__(self, name):
27
+ self.name = name
28
+
29
+ self.Subclass = Subclass
30
+
31
+ @pytest.mark.parametrize('name', ['a', 'name', 'long_name'])
32
+ def test_valid_name_argument(self, name):
33
+ instance = self.Subclass(name)
34
+ assert instance.name == name
35
+
36
+ @pytest.mark.parametrize('invalid_name', [0, 0.0, None, False])
37
+ def test_invalid_name_argument_not_str(self, invalid_name):
38
+ with pytest.raises(TypeError):
39
+ _ = self.Subclass(invalid_name)
40
+
41
+ def test_invalid_name_argument_zero_length_str(self):
42
+ with pytest.raises(ValueError):
43
+ _ = self.Subclass('')
44
+
45
+ def test_name_attribute_is_immutable(self):
46
+ instance = self.Subclass('name')
47
+ with pytest.raises(AttributeError):
48
+ instance.name = 'new_name'
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/biomechanics/tests/test_musculotendon.py ADDED
@@ -0,0 +1,837 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.biomechanics.musculotendon.py`` module."""
2
+
3
+ import abc
4
+
5
+ import pytest
6
+
7
+ from sympy.core.expr import UnevaluatedExpr
8
+ from sympy.core.numbers import Float, Integer, Rational
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.functions.elementary.exponential import exp
11
+ from sympy.functions.elementary.hyperbolic import tanh
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.functions.elementary.trigonometric import sin
14
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix, eye, zeros
15
+ from sympy.physics.biomechanics.activation import (
16
+ FirstOrderActivationDeGroote2016
17
+ )
18
+ from sympy.physics.biomechanics.curve import (
19
+ CharacteristicCurveCollection,
20
+ FiberForceLengthActiveDeGroote2016,
21
+ FiberForceLengthPassiveDeGroote2016,
22
+ FiberForceLengthPassiveInverseDeGroote2016,
23
+ FiberForceVelocityDeGroote2016,
24
+ FiberForceVelocityInverseDeGroote2016,
25
+ TendonForceLengthDeGroote2016,
26
+ TendonForceLengthInverseDeGroote2016,
27
+ )
28
+ from sympy.physics.biomechanics.musculotendon import (
29
+ MusculotendonBase,
30
+ MusculotendonDeGroote2016,
31
+ MusculotendonFormulation,
32
+ )
33
+ from sympy.physics.biomechanics._mixin import _NamedMixin
34
+ from sympy.physics.mechanics.actuator import ForceActuator
35
+ from sympy.physics.mechanics.pathway import LinearPathway
36
+ from sympy.physics.vector.frame import ReferenceFrame
37
+ from sympy.physics.vector.functions import dynamicsymbols
38
+ from sympy.physics.vector.point import Point
39
+ from sympy.simplify.simplify import simplify
40
+
41
+
42
+ class TestMusculotendonFormulation:
43
+ @staticmethod
44
+ def test_rigid_tendon_member():
45
+ assert MusculotendonFormulation(0) == 0
46
+ assert MusculotendonFormulation.RIGID_TENDON == 0
47
+
48
+ @staticmethod
49
+ def test_fiber_length_explicit_member():
50
+ assert MusculotendonFormulation(1) == 1
51
+ assert MusculotendonFormulation.FIBER_LENGTH_EXPLICIT == 1
52
+
53
+ @staticmethod
54
+ def test_tendon_force_explicit_member():
55
+ assert MusculotendonFormulation(2) == 2
56
+ assert MusculotendonFormulation.TENDON_FORCE_EXPLICIT == 2
57
+
58
+ @staticmethod
59
+ def test_fiber_length_implicit_member():
60
+ assert MusculotendonFormulation(3) == 3
61
+ assert MusculotendonFormulation.FIBER_LENGTH_IMPLICIT == 3
62
+
63
+ @staticmethod
64
+ def test_tendon_force_implicit_member():
65
+ assert MusculotendonFormulation(4) == 4
66
+ assert MusculotendonFormulation.TENDON_FORCE_IMPLICIT == 4
67
+
68
+
69
+ class TestMusculotendonBase:
70
+
71
+ @staticmethod
72
+ def test_is_abstract_base_class():
73
+ assert issubclass(MusculotendonBase, abc.ABC)
74
+
75
+ @staticmethod
76
+ def test_class():
77
+ assert issubclass(MusculotendonBase, ForceActuator)
78
+ assert issubclass(MusculotendonBase, _NamedMixin)
79
+ assert MusculotendonBase.__name__ == 'MusculotendonBase'
80
+
81
+ @staticmethod
82
+ def test_cannot_instantiate_directly():
83
+ with pytest.raises(TypeError):
84
+ _ = MusculotendonBase()
85
+
86
+
87
+ @pytest.mark.parametrize('musculotendon_concrete', [MusculotendonDeGroote2016])
88
+ class TestMusculotendonRigidTendon:
89
+
90
+ @pytest.fixture(autouse=True)
91
+ def _musculotendon_rigid_tendon_fixture(self, musculotendon_concrete):
92
+ self.name = 'name'
93
+ self.N = ReferenceFrame('N')
94
+ self.q = dynamicsymbols('q')
95
+ self.origin = Point('pO')
96
+ self.insertion = Point('pI')
97
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
98
+ self.pathway = LinearPathway(self.origin, self.insertion)
99
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
100
+ self.e = self.activation.excitation
101
+ self.a = self.activation.activation
102
+ self.tau_a = self.activation.activation_time_constant
103
+ self.tau_d = self.activation.deactivation_time_constant
104
+ self.b = self.activation.smoothing_rate
105
+ self.formulation = MusculotendonFormulation.RIGID_TENDON
106
+ self.l_T_slack = Symbol('l_T_slack')
107
+ self.F_M_max = Symbol('F_M_max')
108
+ self.l_M_opt = Symbol('l_M_opt')
109
+ self.v_M_max = Symbol('v_M_max')
110
+ self.alpha_opt = Symbol('alpha_opt')
111
+ self.beta = Symbol('beta')
112
+ self.instance = musculotendon_concrete(
113
+ self.name,
114
+ self.pathway,
115
+ self.activation,
116
+ musculotendon_dynamics=self.formulation,
117
+ tendon_slack_length=self.l_T_slack,
118
+ peak_isometric_force=self.F_M_max,
119
+ optimal_fiber_length=self.l_M_opt,
120
+ maximal_fiber_velocity=self.v_M_max,
121
+ optimal_pennation_angle=self.alpha_opt,
122
+ fiber_damping_coefficient=self.beta,
123
+ )
124
+ self.da_expr = (
125
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
126
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
127
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
128
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
129
+ )*(self.e - self.a)
130
+
131
+ def test_state_vars(self):
132
+ assert hasattr(self.instance, 'x')
133
+ assert hasattr(self.instance, 'state_vars')
134
+ assert self.instance.x == self.instance.state_vars
135
+ x_expected = Matrix([self.a])
136
+ assert self.instance.x == x_expected
137
+ assert self.instance.state_vars == x_expected
138
+ assert isinstance(self.instance.x, Matrix)
139
+ assert isinstance(self.instance.state_vars, Matrix)
140
+ assert self.instance.x.shape == (1, 1)
141
+ assert self.instance.state_vars.shape == (1, 1)
142
+
143
+ def test_input_vars(self):
144
+ assert hasattr(self.instance, 'r')
145
+ assert hasattr(self.instance, 'input_vars')
146
+ assert self.instance.r == self.instance.input_vars
147
+ r_expected = Matrix([self.e])
148
+ assert self.instance.r == r_expected
149
+ assert self.instance.input_vars == r_expected
150
+ assert isinstance(self.instance.r, Matrix)
151
+ assert isinstance(self.instance.input_vars, Matrix)
152
+ assert self.instance.r.shape == (1, 1)
153
+ assert self.instance.input_vars.shape == (1, 1)
154
+
155
+ def test_constants(self):
156
+ assert hasattr(self.instance, 'p')
157
+ assert hasattr(self.instance, 'constants')
158
+ assert self.instance.p == self.instance.constants
159
+ p_expected = Matrix(
160
+ [
161
+ self.l_T_slack,
162
+ self.F_M_max,
163
+ self.l_M_opt,
164
+ self.v_M_max,
165
+ self.alpha_opt,
166
+ self.beta,
167
+ self.tau_a,
168
+ self.tau_d,
169
+ self.b,
170
+ Symbol('c_0_fl_T_name'),
171
+ Symbol('c_1_fl_T_name'),
172
+ Symbol('c_2_fl_T_name'),
173
+ Symbol('c_3_fl_T_name'),
174
+ Symbol('c_0_fl_M_pas_name'),
175
+ Symbol('c_1_fl_M_pas_name'),
176
+ Symbol('c_0_fl_M_act_name'),
177
+ Symbol('c_1_fl_M_act_name'),
178
+ Symbol('c_2_fl_M_act_name'),
179
+ Symbol('c_3_fl_M_act_name'),
180
+ Symbol('c_4_fl_M_act_name'),
181
+ Symbol('c_5_fl_M_act_name'),
182
+ Symbol('c_6_fl_M_act_name'),
183
+ Symbol('c_7_fl_M_act_name'),
184
+ Symbol('c_8_fl_M_act_name'),
185
+ Symbol('c_9_fl_M_act_name'),
186
+ Symbol('c_10_fl_M_act_name'),
187
+ Symbol('c_11_fl_M_act_name'),
188
+ Symbol('c_0_fv_M_name'),
189
+ Symbol('c_1_fv_M_name'),
190
+ Symbol('c_2_fv_M_name'),
191
+ Symbol('c_3_fv_M_name'),
192
+ ]
193
+ )
194
+ assert self.instance.p == p_expected
195
+ assert self.instance.constants == p_expected
196
+ assert isinstance(self.instance.p, Matrix)
197
+ assert isinstance(self.instance.constants, Matrix)
198
+ assert self.instance.p.shape == (31, 1)
199
+ assert self.instance.constants.shape == (31, 1)
200
+
201
+ def test_M(self):
202
+ assert hasattr(self.instance, 'M')
203
+ M_expected = Matrix([1])
204
+ assert self.instance.M == M_expected
205
+ assert isinstance(self.instance.M, Matrix)
206
+ assert self.instance.M.shape == (1, 1)
207
+
208
+ def test_F(self):
209
+ assert hasattr(self.instance, 'F')
210
+ F_expected = Matrix([self.da_expr])
211
+ assert self.instance.F == F_expected
212
+ assert isinstance(self.instance.F, Matrix)
213
+ assert self.instance.F.shape == (1, 1)
214
+
215
+ def test_rhs(self):
216
+ assert hasattr(self.instance, 'rhs')
217
+ rhs_expected = Matrix([self.da_expr])
218
+ rhs = self.instance.rhs()
219
+ assert isinstance(rhs, Matrix)
220
+ assert rhs.shape == (1, 1)
221
+ assert simplify(rhs - rhs_expected) == zeros(1)
222
+
223
+
224
+ @pytest.mark.parametrize(
225
+ 'musculotendon_concrete, curve',
226
+ [
227
+ (
228
+ MusculotendonDeGroote2016,
229
+ CharacteristicCurveCollection(
230
+ tendon_force_length=TendonForceLengthDeGroote2016,
231
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
232
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
233
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
234
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
235
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
236
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
237
+ ),
238
+ )
239
+ ],
240
+ )
241
+ class TestFiberLengthExplicit:
242
+
243
+ @pytest.fixture(autouse=True)
244
+ def _musculotendon_fiber_length_explicit_fixture(
245
+ self,
246
+ musculotendon_concrete,
247
+ curve,
248
+ ):
249
+ self.name = 'name'
250
+ self.N = ReferenceFrame('N')
251
+ self.q = dynamicsymbols('q')
252
+ self.origin = Point('pO')
253
+ self.insertion = Point('pI')
254
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
255
+ self.pathway = LinearPathway(self.origin, self.insertion)
256
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
257
+ self.e = self.activation.excitation
258
+ self.a = self.activation.activation
259
+ self.tau_a = self.activation.activation_time_constant
260
+ self.tau_d = self.activation.deactivation_time_constant
261
+ self.b = self.activation.smoothing_rate
262
+ self.formulation = MusculotendonFormulation.FIBER_LENGTH_EXPLICIT
263
+ self.l_T_slack = Symbol('l_T_slack')
264
+ self.F_M_max = Symbol('F_M_max')
265
+ self.l_M_opt = Symbol('l_M_opt')
266
+ self.v_M_max = Symbol('v_M_max')
267
+ self.alpha_opt = Symbol('alpha_opt')
268
+ self.beta = Symbol('beta')
269
+ self.instance = musculotendon_concrete(
270
+ self.name,
271
+ self.pathway,
272
+ self.activation,
273
+ musculotendon_dynamics=self.formulation,
274
+ tendon_slack_length=self.l_T_slack,
275
+ peak_isometric_force=self.F_M_max,
276
+ optimal_fiber_length=self.l_M_opt,
277
+ maximal_fiber_velocity=self.v_M_max,
278
+ optimal_pennation_angle=self.alpha_opt,
279
+ fiber_damping_coefficient=self.beta,
280
+ with_defaults=True,
281
+ )
282
+ self.l_M_tilde = dynamicsymbols('l_M_tilde_name')
283
+ l_MT = self.pathway.length
284
+ l_M = self.l_M_tilde*self.l_M_opt
285
+ l_T = l_MT - sqrt(l_M**2 - (self.l_M_opt*sin(self.alpha_opt))**2)
286
+ fl_T = curve.tendon_force_length.with_defaults(l_T/self.l_T_slack)
287
+ fl_M_pas = curve.fiber_force_length_passive.with_defaults(self.l_M_tilde)
288
+ fl_M_act = curve.fiber_force_length_active.with_defaults(self.l_M_tilde)
289
+ v_M_tilde = curve.fiber_force_velocity_inverse.with_defaults(
290
+ ((((fl_T*self.F_M_max)/((l_MT - l_T)/l_M))/self.F_M_max) - fl_M_pas)
291
+ /(self.a*fl_M_act)
292
+ )
293
+ self.dl_M_tilde_expr = (self.v_M_max/self.l_M_opt)*v_M_tilde
294
+ self.da_expr = (
295
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
296
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
297
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
298
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
299
+ )*(self.e - self.a)
300
+
301
+ def test_state_vars(self):
302
+ assert hasattr(self.instance, 'x')
303
+ assert hasattr(self.instance, 'state_vars')
304
+ assert self.instance.x == self.instance.state_vars
305
+ x_expected = Matrix([self.l_M_tilde, self.a])
306
+ assert self.instance.x == x_expected
307
+ assert self.instance.state_vars == x_expected
308
+ assert isinstance(self.instance.x, Matrix)
309
+ assert isinstance(self.instance.state_vars, Matrix)
310
+ assert self.instance.x.shape == (2, 1)
311
+ assert self.instance.state_vars.shape == (2, 1)
312
+
313
+ def test_input_vars(self):
314
+ assert hasattr(self.instance, 'r')
315
+ assert hasattr(self.instance, 'input_vars')
316
+ assert self.instance.r == self.instance.input_vars
317
+ r_expected = Matrix([self.e])
318
+ assert self.instance.r == r_expected
319
+ assert self.instance.input_vars == r_expected
320
+ assert isinstance(self.instance.r, Matrix)
321
+ assert isinstance(self.instance.input_vars, Matrix)
322
+ assert self.instance.r.shape == (1, 1)
323
+ assert self.instance.input_vars.shape == (1, 1)
324
+
325
+ def test_constants(self):
326
+ assert hasattr(self.instance, 'p')
327
+ assert hasattr(self.instance, 'constants')
328
+ assert self.instance.p == self.instance.constants
329
+ p_expected = Matrix(
330
+ [
331
+ self.l_T_slack,
332
+ self.F_M_max,
333
+ self.l_M_opt,
334
+ self.v_M_max,
335
+ self.alpha_opt,
336
+ self.beta,
337
+ self.tau_a,
338
+ self.tau_d,
339
+ self.b,
340
+ ]
341
+ )
342
+ assert self.instance.p == p_expected
343
+ assert self.instance.constants == p_expected
344
+ assert isinstance(self.instance.p, Matrix)
345
+ assert isinstance(self.instance.constants, Matrix)
346
+ assert self.instance.p.shape == (9, 1)
347
+ assert self.instance.constants.shape == (9, 1)
348
+
349
+ def test_M(self):
350
+ assert hasattr(self.instance, 'M')
351
+ M_expected = eye(2)
352
+ assert self.instance.M == M_expected
353
+ assert isinstance(self.instance.M, Matrix)
354
+ assert self.instance.M.shape == (2, 2)
355
+
356
+ def test_F(self):
357
+ assert hasattr(self.instance, 'F')
358
+ F_expected = Matrix([self.dl_M_tilde_expr, self.da_expr])
359
+ assert self.instance.F == F_expected
360
+ assert isinstance(self.instance.F, Matrix)
361
+ assert self.instance.F.shape == (2, 1)
362
+
363
+ def test_rhs(self):
364
+ assert hasattr(self.instance, 'rhs')
365
+ rhs_expected = Matrix([self.dl_M_tilde_expr, self.da_expr])
366
+ rhs = self.instance.rhs()
367
+ assert isinstance(rhs, Matrix)
368
+ assert rhs.shape == (2, 1)
369
+ assert simplify(rhs - rhs_expected) == zeros(2, 1)
370
+
371
+
372
+ @pytest.mark.parametrize(
373
+ 'musculotendon_concrete, curve',
374
+ [
375
+ (
376
+ MusculotendonDeGroote2016,
377
+ CharacteristicCurveCollection(
378
+ tendon_force_length=TendonForceLengthDeGroote2016,
379
+ tendon_force_length_inverse=TendonForceLengthInverseDeGroote2016,
380
+ fiber_force_length_passive=FiberForceLengthPassiveDeGroote2016,
381
+ fiber_force_length_passive_inverse=FiberForceLengthPassiveInverseDeGroote2016,
382
+ fiber_force_length_active=FiberForceLengthActiveDeGroote2016,
383
+ fiber_force_velocity=FiberForceVelocityDeGroote2016,
384
+ fiber_force_velocity_inverse=FiberForceVelocityInverseDeGroote2016,
385
+ ),
386
+ )
387
+ ],
388
+ )
389
+ class TestTendonForceExplicit:
390
+
391
+ @pytest.fixture(autouse=True)
392
+ def _musculotendon_tendon_force_explicit_fixture(
393
+ self,
394
+ musculotendon_concrete,
395
+ curve,
396
+ ):
397
+ self.name = 'name'
398
+ self.N = ReferenceFrame('N')
399
+ self.q = dynamicsymbols('q')
400
+ self.origin = Point('pO')
401
+ self.insertion = Point('pI')
402
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
403
+ self.pathway = LinearPathway(self.origin, self.insertion)
404
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
405
+ self.e = self.activation.excitation
406
+ self.a = self.activation.activation
407
+ self.tau_a = self.activation.activation_time_constant
408
+ self.tau_d = self.activation.deactivation_time_constant
409
+ self.b = self.activation.smoothing_rate
410
+ self.formulation = MusculotendonFormulation.TENDON_FORCE_EXPLICIT
411
+ self.l_T_slack = Symbol('l_T_slack')
412
+ self.F_M_max = Symbol('F_M_max')
413
+ self.l_M_opt = Symbol('l_M_opt')
414
+ self.v_M_max = Symbol('v_M_max')
415
+ self.alpha_opt = Symbol('alpha_opt')
416
+ self.beta = Symbol('beta')
417
+ self.instance = musculotendon_concrete(
418
+ self.name,
419
+ self.pathway,
420
+ self.activation,
421
+ musculotendon_dynamics=self.formulation,
422
+ tendon_slack_length=self.l_T_slack,
423
+ peak_isometric_force=self.F_M_max,
424
+ optimal_fiber_length=self.l_M_opt,
425
+ maximal_fiber_velocity=self.v_M_max,
426
+ optimal_pennation_angle=self.alpha_opt,
427
+ fiber_damping_coefficient=self.beta,
428
+ with_defaults=True,
429
+ )
430
+ self.F_T_tilde = dynamicsymbols('F_T_tilde_name')
431
+ l_T_tilde = curve.tendon_force_length_inverse.with_defaults(self.F_T_tilde)
432
+ l_MT = self.pathway.length
433
+ v_MT = self.pathway.extension_velocity
434
+ l_T = l_T_tilde*self.l_T_slack
435
+ l_M = sqrt((l_MT - l_T)**2 + (self.l_M_opt*sin(self.alpha_opt))**2)
436
+ l_M_tilde = l_M/self.l_M_opt
437
+ cos_alpha = (l_MT - l_T)/l_M
438
+ F_T = self.F_T_tilde*self.F_M_max
439
+ F_M = F_T/cos_alpha
440
+ F_M_tilde = F_M/self.F_M_max
441
+ fl_M_pas = curve.fiber_force_length_passive.with_defaults(l_M_tilde)
442
+ fl_M_act = curve.fiber_force_length_active.with_defaults(l_M_tilde)
443
+ fv_M = (F_M_tilde - fl_M_pas)/(self.a*fl_M_act)
444
+ v_M_tilde = curve.fiber_force_velocity_inverse.with_defaults(fv_M)
445
+ v_M = v_M_tilde*self.v_M_max
446
+ v_T = v_MT - v_M/cos_alpha
447
+ v_T_tilde = v_T/self.l_T_slack
448
+ self.dF_T_tilde_expr = (
449
+ Float('0.2')*Float('33.93669377311689')*exp(
450
+ Float('33.93669377311689')*UnevaluatedExpr(l_T_tilde - Float('0.995'))
451
+ )*v_T_tilde
452
+ )
453
+ self.da_expr = (
454
+ (1/(self.tau_a*(Rational(1, 2) + Rational(3, 2)*self.a)))
455
+ *(Rational(1, 2) + Rational(1, 2)*tanh(self.b*(self.e - self.a)))
456
+ + ((Rational(1, 2) + Rational(3, 2)*self.a)/self.tau_d)
457
+ *(Rational(1, 2) - Rational(1, 2)*tanh(self.b*(self.e - self.a)))
458
+ )*(self.e - self.a)
459
+
460
+ def test_state_vars(self):
461
+ assert hasattr(self.instance, 'x')
462
+ assert hasattr(self.instance, 'state_vars')
463
+ assert self.instance.x == self.instance.state_vars
464
+ x_expected = Matrix([self.F_T_tilde, self.a])
465
+ assert self.instance.x == x_expected
466
+ assert self.instance.state_vars == x_expected
467
+ assert isinstance(self.instance.x, Matrix)
468
+ assert isinstance(self.instance.state_vars, Matrix)
469
+ assert self.instance.x.shape == (2, 1)
470
+ assert self.instance.state_vars.shape == (2, 1)
471
+
472
+ def test_input_vars(self):
473
+ assert hasattr(self.instance, 'r')
474
+ assert hasattr(self.instance, 'input_vars')
475
+ assert self.instance.r == self.instance.input_vars
476
+ r_expected = Matrix([self.e])
477
+ assert self.instance.r == r_expected
478
+ assert self.instance.input_vars == r_expected
479
+ assert isinstance(self.instance.r, Matrix)
480
+ assert isinstance(self.instance.input_vars, Matrix)
481
+ assert self.instance.r.shape == (1, 1)
482
+ assert self.instance.input_vars.shape == (1, 1)
483
+
484
+ def test_constants(self):
485
+ assert hasattr(self.instance, 'p')
486
+ assert hasattr(self.instance, 'constants')
487
+ assert self.instance.p == self.instance.constants
488
+ p_expected = Matrix(
489
+ [
490
+ self.l_T_slack,
491
+ self.F_M_max,
492
+ self.l_M_opt,
493
+ self.v_M_max,
494
+ self.alpha_opt,
495
+ self.beta,
496
+ self.tau_a,
497
+ self.tau_d,
498
+ self.b,
499
+ ]
500
+ )
501
+ assert self.instance.p == p_expected
502
+ assert self.instance.constants == p_expected
503
+ assert isinstance(self.instance.p, Matrix)
504
+ assert isinstance(self.instance.constants, Matrix)
505
+ assert self.instance.p.shape == (9, 1)
506
+ assert self.instance.constants.shape == (9, 1)
507
+
508
+ def test_M(self):
509
+ assert hasattr(self.instance, 'M')
510
+ M_expected = eye(2)
511
+ assert self.instance.M == M_expected
512
+ assert isinstance(self.instance.M, Matrix)
513
+ assert self.instance.M.shape == (2, 2)
514
+
515
+ def test_F(self):
516
+ assert hasattr(self.instance, 'F')
517
+ F_expected = Matrix([self.dF_T_tilde_expr, self.da_expr])
518
+ assert self.instance.F == F_expected
519
+ assert isinstance(self.instance.F, Matrix)
520
+ assert self.instance.F.shape == (2, 1)
521
+
522
+ def test_rhs(self):
523
+ assert hasattr(self.instance, 'rhs')
524
+ rhs_expected = Matrix([self.dF_T_tilde_expr, self.da_expr])
525
+ rhs = self.instance.rhs()
526
+ assert isinstance(rhs, Matrix)
527
+ assert rhs.shape == (2, 1)
528
+ assert simplify(rhs - rhs_expected) == zeros(2, 1)
529
+
530
+
531
+ class TestMusculotendonDeGroote2016:
532
+
533
+ @staticmethod
534
+ def test_class():
535
+ assert issubclass(MusculotendonDeGroote2016, ForceActuator)
536
+ assert issubclass(MusculotendonDeGroote2016, _NamedMixin)
537
+ assert MusculotendonDeGroote2016.__name__ == 'MusculotendonDeGroote2016'
538
+
539
+ @staticmethod
540
+ def test_instance():
541
+ origin = Point('pO')
542
+ insertion = Point('pI')
543
+ insertion.set_pos(origin, dynamicsymbols('q')*ReferenceFrame('N').x)
544
+ pathway = LinearPathway(origin, insertion)
545
+ activation = FirstOrderActivationDeGroote2016('name')
546
+ l_T_slack = Symbol('l_T_slack')
547
+ F_M_max = Symbol('F_M_max')
548
+ l_M_opt = Symbol('l_M_opt')
549
+ v_M_max = Symbol('v_M_max')
550
+ alpha_opt = Symbol('alpha_opt')
551
+ beta = Symbol('beta')
552
+ instance = MusculotendonDeGroote2016(
553
+ 'name',
554
+ pathway,
555
+ activation,
556
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
557
+ tendon_slack_length=l_T_slack,
558
+ peak_isometric_force=F_M_max,
559
+ optimal_fiber_length=l_M_opt,
560
+ maximal_fiber_velocity=v_M_max,
561
+ optimal_pennation_angle=alpha_opt,
562
+ fiber_damping_coefficient=beta,
563
+ )
564
+ assert isinstance(instance, MusculotendonDeGroote2016)
565
+
566
+ @pytest.fixture(autouse=True)
567
+ def _musculotendon_fixture(self):
568
+ self.name = 'name'
569
+ self.N = ReferenceFrame('N')
570
+ self.q = dynamicsymbols('q')
571
+ self.origin = Point('pO')
572
+ self.insertion = Point('pI')
573
+ self.insertion.set_pos(self.origin, self.q*self.N.x)
574
+ self.pathway = LinearPathway(self.origin, self.insertion)
575
+ self.activation = FirstOrderActivationDeGroote2016(self.name)
576
+ self.l_T_slack = Symbol('l_T_slack')
577
+ self.F_M_max = Symbol('F_M_max')
578
+ self.l_M_opt = Symbol('l_M_opt')
579
+ self.v_M_max = Symbol('v_M_max')
580
+ self.alpha_opt = Symbol('alpha_opt')
581
+ self.beta = Symbol('beta')
582
+
583
+ def test_with_defaults(self):
584
+ origin = Point('pO')
585
+ insertion = Point('pI')
586
+ insertion.set_pos(origin, dynamicsymbols('q')*ReferenceFrame('N').x)
587
+ pathway = LinearPathway(origin, insertion)
588
+ activation = FirstOrderActivationDeGroote2016('name')
589
+ l_T_slack = Symbol('l_T_slack')
590
+ F_M_max = Symbol('F_M_max')
591
+ l_M_opt = Symbol('l_M_opt')
592
+ v_M_max = Float('10.0')
593
+ alpha_opt = Float('0.0')
594
+ beta = Float('0.1')
595
+ instance = MusculotendonDeGroote2016.with_defaults(
596
+ 'name',
597
+ pathway,
598
+ activation,
599
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
600
+ tendon_slack_length=l_T_slack,
601
+ peak_isometric_force=F_M_max,
602
+ optimal_fiber_length=l_M_opt,
603
+ )
604
+ assert instance.tendon_slack_length == l_T_slack
605
+ assert instance.peak_isometric_force == F_M_max
606
+ assert instance.optimal_fiber_length == l_M_opt
607
+ assert instance.maximal_fiber_velocity == v_M_max
608
+ assert instance.optimal_pennation_angle == alpha_opt
609
+ assert instance.fiber_damping_coefficient == beta
610
+
611
+ @pytest.mark.parametrize(
612
+ 'l_T_slack, expected',
613
+ [
614
+ (None, Symbol('l_T_slack_name')),
615
+ (Symbol('l_T_slack'), Symbol('l_T_slack')),
616
+ (Rational(1, 2), Rational(1, 2)),
617
+ (Float('0.5'), Float('0.5')),
618
+ ],
619
+ )
620
+ def test_tendon_slack_length(self, l_T_slack, expected):
621
+ instance = MusculotendonDeGroote2016(
622
+ self.name,
623
+ self.pathway,
624
+ self.activation,
625
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
626
+ tendon_slack_length=l_T_slack,
627
+ peak_isometric_force=self.F_M_max,
628
+ optimal_fiber_length=self.l_M_opt,
629
+ maximal_fiber_velocity=self.v_M_max,
630
+ optimal_pennation_angle=self.alpha_opt,
631
+ fiber_damping_coefficient=self.beta,
632
+ )
633
+ assert instance.l_T_slack == expected
634
+ assert instance.tendon_slack_length == expected
635
+
636
+ @pytest.mark.parametrize(
637
+ 'F_M_max, expected',
638
+ [
639
+ (None, Symbol('F_M_max_name')),
640
+ (Symbol('F_M_max'), Symbol('F_M_max')),
641
+ (Integer(1000), Integer(1000)),
642
+ (Float('1000.0'), Float('1000.0')),
643
+ ],
644
+ )
645
+ def test_peak_isometric_force(self, F_M_max, expected):
646
+ instance = MusculotendonDeGroote2016(
647
+ self.name,
648
+ self.pathway,
649
+ self.activation,
650
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
651
+ tendon_slack_length=self.l_T_slack,
652
+ peak_isometric_force=F_M_max,
653
+ optimal_fiber_length=self.l_M_opt,
654
+ maximal_fiber_velocity=self.v_M_max,
655
+ optimal_pennation_angle=self.alpha_opt,
656
+ fiber_damping_coefficient=self.beta,
657
+ )
658
+ assert instance.F_M_max == expected
659
+ assert instance.peak_isometric_force == expected
660
+
661
+ @pytest.mark.parametrize(
662
+ 'l_M_opt, expected',
663
+ [
664
+ (None, Symbol('l_M_opt_name')),
665
+ (Symbol('l_M_opt'), Symbol('l_M_opt')),
666
+ (Rational(1, 2), Rational(1, 2)),
667
+ (Float('0.5'), Float('0.5')),
668
+ ],
669
+ )
670
+ def test_optimal_fiber_length(self, l_M_opt, expected):
671
+ instance = MusculotendonDeGroote2016(
672
+ self.name,
673
+ self.pathway,
674
+ self.activation,
675
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
676
+ tendon_slack_length=self.l_T_slack,
677
+ peak_isometric_force=self.F_M_max,
678
+ optimal_fiber_length=l_M_opt,
679
+ maximal_fiber_velocity=self.v_M_max,
680
+ optimal_pennation_angle=self.alpha_opt,
681
+ fiber_damping_coefficient=self.beta,
682
+ )
683
+ assert instance.l_M_opt == expected
684
+ assert instance.optimal_fiber_length == expected
685
+
686
+ @pytest.mark.parametrize(
687
+ 'v_M_max, expected',
688
+ [
689
+ (None, Symbol('v_M_max_name')),
690
+ (Symbol('v_M_max'), Symbol('v_M_max')),
691
+ (Integer(10), Integer(10)),
692
+ (Float('10.0'), Float('10.0')),
693
+ ],
694
+ )
695
+ def test_maximal_fiber_velocity(self, v_M_max, expected):
696
+ instance = MusculotendonDeGroote2016(
697
+ self.name,
698
+ self.pathway,
699
+ self.activation,
700
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
701
+ tendon_slack_length=self.l_T_slack,
702
+ peak_isometric_force=self.F_M_max,
703
+ optimal_fiber_length=self.l_M_opt,
704
+ maximal_fiber_velocity=v_M_max,
705
+ optimal_pennation_angle=self.alpha_opt,
706
+ fiber_damping_coefficient=self.beta,
707
+ )
708
+ assert instance.v_M_max == expected
709
+ assert instance.maximal_fiber_velocity == expected
710
+
711
+ @pytest.mark.parametrize(
712
+ 'alpha_opt, expected',
713
+ [
714
+ (None, Symbol('alpha_opt_name')),
715
+ (Symbol('alpha_opt'), Symbol('alpha_opt')),
716
+ (Integer(0), Integer(0)),
717
+ (Float('0.1'), Float('0.1')),
718
+ ],
719
+ )
720
+ def test_optimal_pennation_angle(self, alpha_opt, expected):
721
+ instance = MusculotendonDeGroote2016(
722
+ self.name,
723
+ self.pathway,
724
+ self.activation,
725
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
726
+ tendon_slack_length=self.l_T_slack,
727
+ peak_isometric_force=self.F_M_max,
728
+ optimal_fiber_length=self.l_M_opt,
729
+ maximal_fiber_velocity=self.v_M_max,
730
+ optimal_pennation_angle=alpha_opt,
731
+ fiber_damping_coefficient=self.beta,
732
+ )
733
+ assert instance.alpha_opt == expected
734
+ assert instance.optimal_pennation_angle == expected
735
+
736
+ @pytest.mark.parametrize(
737
+ 'beta, expected',
738
+ [
739
+ (None, Symbol('beta_name')),
740
+ (Symbol('beta'), Symbol('beta')),
741
+ (Integer(0), Integer(0)),
742
+ (Rational(1, 10), Rational(1, 10)),
743
+ (Float('0.1'), Float('0.1')),
744
+ ],
745
+ )
746
+ def test_fiber_damping_coefficient(self, beta, expected):
747
+ instance = MusculotendonDeGroote2016(
748
+ self.name,
749
+ self.pathway,
750
+ self.activation,
751
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
752
+ tendon_slack_length=self.l_T_slack,
753
+ peak_isometric_force=self.F_M_max,
754
+ optimal_fiber_length=self.l_M_opt,
755
+ maximal_fiber_velocity=self.v_M_max,
756
+ optimal_pennation_angle=self.alpha_opt,
757
+ fiber_damping_coefficient=beta,
758
+ )
759
+ assert instance.beta == expected
760
+ assert instance.fiber_damping_coefficient == expected
761
+
762
+ def test_excitation(self):
763
+ instance = MusculotendonDeGroote2016(
764
+ self.name,
765
+ self.pathway,
766
+ self.activation,
767
+ )
768
+ assert hasattr(instance, 'e')
769
+ assert hasattr(instance, 'excitation')
770
+ e_expected = dynamicsymbols('e_name')
771
+ assert instance.e == e_expected
772
+ assert instance.excitation == e_expected
773
+ assert instance.e is instance.excitation
774
+
775
+ def test_excitation_is_immutable(self):
776
+ instance = MusculotendonDeGroote2016(
777
+ self.name,
778
+ self.pathway,
779
+ self.activation,
780
+ )
781
+ with pytest.raises(AttributeError):
782
+ instance.e = None
783
+ with pytest.raises(AttributeError):
784
+ instance.excitation = None
785
+
786
+ def test_activation(self):
787
+ instance = MusculotendonDeGroote2016(
788
+ self.name,
789
+ self.pathway,
790
+ self.activation,
791
+ )
792
+ assert hasattr(instance, 'a')
793
+ assert hasattr(instance, 'activation')
794
+ a_expected = dynamicsymbols('a_name')
795
+ assert instance.a == a_expected
796
+ assert instance.activation == a_expected
797
+
798
+ def test_activation_is_immutable(self):
799
+ instance = MusculotendonDeGroote2016(
800
+ self.name,
801
+ self.pathway,
802
+ self.activation,
803
+ )
804
+ with pytest.raises(AttributeError):
805
+ instance.a = None
806
+ with pytest.raises(AttributeError):
807
+ instance.activation = None
808
+
809
+ def test_repr(self):
810
+ instance = MusculotendonDeGroote2016(
811
+ self.name,
812
+ self.pathway,
813
+ self.activation,
814
+ musculotendon_dynamics=MusculotendonFormulation.RIGID_TENDON,
815
+ tendon_slack_length=self.l_T_slack,
816
+ peak_isometric_force=self.F_M_max,
817
+ optimal_fiber_length=self.l_M_opt,
818
+ maximal_fiber_velocity=self.v_M_max,
819
+ optimal_pennation_angle=self.alpha_opt,
820
+ fiber_damping_coefficient=self.beta,
821
+ )
822
+ expected = (
823
+ 'MusculotendonDeGroote2016(\'name\', '
824
+ 'pathway=LinearPathway(pO, pI), '
825
+ 'activation_dynamics=FirstOrderActivationDeGroote2016(\'name\', '
826
+ 'activation_time_constant=tau_a_name, '
827
+ 'deactivation_time_constant=tau_d_name, '
828
+ 'smoothing_rate=b_name), '
829
+ 'musculotendon_dynamics=0, '
830
+ 'tendon_slack_length=l_T_slack, '
831
+ 'peak_isometric_force=F_M_max, '
832
+ 'optimal_fiber_length=l_M_opt, '
833
+ 'maximal_fiber_velocity=v_M_max, '
834
+ 'optimal_pennation_angle=alpha_opt, '
835
+ 'fiber_damping_coefficient=beta)'
836
+ )
837
+ assert repr(instance) == expected
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['Beam',
2
+ 'Truss',
3
+ 'Cable',
4
+ 'Arch'
5
+ ]
6
+
7
+ from .beam import Beam
8
+ from .truss import Truss
9
+ from .cable import Cable
10
+ from .arch import Arch
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/arch.py ADDED
@@ -0,0 +1,1025 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module can be used to solve probelsm related to 2D parabolic arches
3
+ """
4
+ from sympy.core.sympify import sympify
5
+ from sympy.core.symbol import Symbol,symbols
6
+ from sympy import diff, sqrt, cos , sin, atan, rad, Min
7
+ from sympy.core.relational import Eq
8
+ from sympy.solvers.solvers import solve
9
+ from sympy.functions import Piecewise
10
+ from sympy.plotting import plot
11
+ from sympy import limit
12
+ from sympy.utilities.decorator import doctest_depends_on
13
+ from sympy.external.importtools import import_module
14
+
15
+ numpy = import_module('numpy', import_kwargs={'fromlist':['arange']})
16
+
17
+ class Arch:
18
+ """
19
+ This class is used to solve problems related to a three hinged arch(determinate) structure.\n
20
+ An arch is a curved vertical structure spanning an open space underneath it.\n
21
+ Arches can be used to reduce the bending moments in long-span structures.\n
22
+
23
+ Arches are used in structural engineering(over windows, door and even bridges)\n
24
+ because they can support a very large mass placed on top of them.
25
+
26
+ Example
27
+ ========
28
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
29
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
30
+ >>> a.get_shape_eqn
31
+ 5 - (x - 5)**2/5
32
+
33
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
34
+ >>> a = Arch((0,0),(10,1),crown_x=6)
35
+ >>> a.get_shape_eqn
36
+ 9/5 - (x - 6)**2/20
37
+ """
38
+ def __init__(self,left_support,right_support,**kwargs):
39
+ self._shape_eqn = None
40
+ self._left_support = (sympify(left_support[0]),sympify(left_support[1]))
41
+ self._right_support = (sympify(right_support[0]),sympify(right_support[1]))
42
+ self._crown_x = None
43
+ self._crown_y = None
44
+ if 'crown_x' in kwargs:
45
+ self._crown_x = sympify(kwargs['crown_x'])
46
+ if 'crown_y' in kwargs:
47
+ self._crown_y = sympify(kwargs['crown_y'])
48
+ self._shape_eqn = self.get_shape_eqn
49
+ self._conc_loads = {}
50
+ self._distributed_loads = {}
51
+ self._loads = {'concentrated': self._conc_loads, 'distributed':self._distributed_loads}
52
+ self._loads_applied = {}
53
+ self._supports = {'left':'hinge', 'right':'hinge'}
54
+ self._member = None
55
+ self._member_force = None
56
+ self._reaction_force = {Symbol('R_A_x'):0, Symbol('R_A_y'):0, Symbol('R_B_x'):0, Symbol('R_B_y'):0}
57
+ self._points_disc_x = set()
58
+ self._points_disc_y = set()
59
+ self._moment_x = {}
60
+ self._moment_y = {}
61
+ self._load_x = {}
62
+ self._load_y = {}
63
+ self._moment_x_func = Piecewise((0,True))
64
+ self._moment_y_func = Piecewise((0,True))
65
+ self._load_x_func = Piecewise((0,True))
66
+ self._load_y_func = Piecewise((0,True))
67
+ self._bending_moment = None
68
+ self._shear_force = None
69
+ self._axial_force = None
70
+ # self._crown = (sympify(crown[0]),sympify(crown[1]))
71
+
72
+ @property
73
+ def get_shape_eqn(self):
74
+ "returns the equation of the shape of arch developed"
75
+ if self._shape_eqn:
76
+ return self._shape_eqn
77
+
78
+ x,y,c = symbols('x y c')
79
+ a = Symbol('a',positive=False)
80
+ if self._crown_x and self._crown_y:
81
+ x0 = self._crown_x
82
+ y0 = self._crown_y
83
+ parabola_eqn = a*(x-x0)**2 + y0 - y
84
+ eq1 = parabola_eqn.subs({x:self._left_support[0], y:self._left_support[1]})
85
+ solution = solve((eq1),(a))
86
+ parabola_eqn = solution[0]*(x-x0)**2 + y0
87
+ if(parabola_eqn.subs({x:self._right_support[0]}) != self._right_support[1]):
88
+ raise ValueError("provided coordinates of crown and supports are not consistent with parabolic arch")
89
+
90
+ elif self._crown_x:
91
+ x0 = self._crown_x
92
+ parabola_eqn = a*(x-x0)**2 + c - y
93
+ eq1 = parabola_eqn.subs({x:self._left_support[0], y:self._left_support[1]})
94
+ eq2 = parabola_eqn.subs({x:self._right_support[0], y:self._right_support[1]})
95
+ solution = solve((eq1,eq2),(a,c))
96
+ if len(solution) <2 or solution[a] == 0:
97
+ raise ValueError("parabolic arch cannot be constructed with the provided coordinates, try providing crown_y")
98
+ parabola_eqn = solution[a]*(x-x0)**2+ solution[c]
99
+ self._crown_y = solution[c]
100
+
101
+ else:
102
+ raise KeyError("please provide crown_x to construct arch")
103
+
104
+ return parabola_eqn
105
+
106
+ @property
107
+ def get_loads(self):
108
+ """
109
+ return the position of the applied load and angle (for concentrated loads)
110
+ """
111
+ return self._loads
112
+
113
+ @property
114
+ def supports(self):
115
+ """
116
+ Returns the type of support
117
+ """
118
+ return self._supports
119
+
120
+ @property
121
+ def left_support(self):
122
+ """
123
+ Returns the position of the left support.
124
+ """
125
+ return self._left_support
126
+
127
+ @property
128
+ def right_support(self):
129
+ """
130
+ Returns the position of the right support.
131
+ """
132
+ return self._right_support
133
+
134
+ @property
135
+ def reaction_force(self):
136
+ """
137
+ return the reaction forces generated
138
+ """
139
+ return self._reaction_force
140
+
141
+ def apply_load(self,order,label,start,mag,end=None,angle=None):
142
+ """
143
+ This method adds load to the Arch.
144
+
145
+ Parameters
146
+ ==========
147
+
148
+ order : Integer
149
+ Order of the applied load.
150
+
151
+ - For point/concentrated loads, order = -1
152
+ - For distributed load, order = 0
153
+
154
+ label : String or Symbol
155
+ The label of the load
156
+ - should not use 'A' or 'B' as it is used for supports.
157
+
158
+ start : Float
159
+
160
+ - For concentrated/point loads, start is the x coordinate
161
+ - For distributed loads, start is the starting position of distributed load
162
+
163
+ mag : Sympifyable
164
+ Magnitude of the applied load. Must be positive
165
+
166
+ end : Float
167
+ Required for distributed loads
168
+
169
+ - For concentrated/point load , end is None(may not be given)
170
+ - For distributed loads, end is the end position of distributed load
171
+
172
+ angle: Sympifyable
173
+ The angle in degrees, the load vector makes with the horizontal
174
+ in the counter-clockwise direction.
175
+
176
+ Examples
177
+ ========
178
+ For applying distributed load
179
+
180
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
181
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
182
+ >>> a.apply_load(0,'C',start=3,end=5,mag=-10)
183
+
184
+ For applying point/concentrated_loads
185
+
186
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
187
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
188
+ >>> a.apply_load(-1,'C',start=2,mag=15,angle=45)
189
+
190
+ """
191
+ y = Symbol('y')
192
+ x = Symbol('x')
193
+ x0 = Symbol('x0')
194
+ # y0 = Symbol('y0')
195
+ order= sympify(order)
196
+ mag = sympify(mag)
197
+ angle = sympify(angle)
198
+
199
+ if label in self._loads_applied:
200
+ raise ValueError("load with the given label already exists")
201
+
202
+ if label in ['A','B']:
203
+ raise ValueError("cannot use the given label, reserved for supports")
204
+
205
+ if order == 0:
206
+ if end is None or end<start:
207
+ raise KeyError("provide end greater than start")
208
+
209
+ self._distributed_loads[label] = {'start':start, 'end':end, 'f_y': mag}
210
+ self._points_disc_y.add(start)
211
+
212
+ if start in self._moment_y:
213
+ self._moment_y[start] -= mag*(Min(x,end)-start)*(x0-(start+(Min(x,end)))/2)
214
+ self._load_y[start] += mag*(Min(end,x)-start)
215
+ else:
216
+ self._moment_y[start] = -mag*(Min(x,end)-start)*(x0-(start+(Min(x,end)))/2)
217
+ self._load_y[start] = mag*(Min(end,x)-start)
218
+
219
+ self._loads_applied[label] = 'distributed'
220
+
221
+ if order == -1:
222
+
223
+ if angle is None:
224
+ raise TypeError("please provide direction of force")
225
+ height = self._shape_eqn.subs({'x':start})
226
+
227
+ self._conc_loads[label] = {'x':start, 'y':height, 'f_x':mag*cos(rad(angle)), 'f_y': mag*sin(rad(angle)), 'mag':mag, 'angle':angle}
228
+ self._points_disc_x.add(start)
229
+ self._points_disc_y.add(start)
230
+
231
+ if start in self._moment_x:
232
+ self._moment_x[start] += self._conc_loads[label]['f_x']*(y-self._conc_loads[label]['y'])
233
+ self._load_x[start] += self._conc_loads[label]['f_x']
234
+ else:
235
+ self._moment_x[start] = self._conc_loads[label]['f_x']*(y-self._conc_loads[label]['y'])
236
+ self._load_x[start] = self._conc_loads[label]['f_x']
237
+
238
+ if start in self._moment_y:
239
+ self._moment_y[start] -= self._conc_loads[label]['f_y']*(x0-start)
240
+ self._load_y[start] += self._conc_loads[label]['f_y']
241
+ else:
242
+ self._moment_y[start] = -self._conc_loads[label]['f_y']*(x0-start)
243
+ self._load_y[start] = self._conc_loads[label]['f_y']
244
+
245
+ self._loads_applied[label] = 'concentrated'
246
+
247
+
248
+ def remove_load(self,label):
249
+ """
250
+ This methods removes the load applied to the arch
251
+
252
+ Parameters
253
+ ==========
254
+
255
+ label : String or Symbol
256
+ The label of the applied load
257
+
258
+ Examples
259
+ ========
260
+
261
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
262
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
263
+ >>> a.apply_load(0,'C',start=3,end=5,mag=-10)
264
+ >>> a.remove_load('C')
265
+ removed load C: {'start': 3, 'end': 5, 'f_y': -10}
266
+ """
267
+ y = Symbol('y')
268
+ x = Symbol('x')
269
+ x0 = Symbol('x0')
270
+
271
+ if label in self._distributed_loads :
272
+
273
+ self._loads_applied.pop(label)
274
+ start = self._distributed_loads[label]['start']
275
+ end = self._distributed_loads[label]['end']
276
+ mag = self._distributed_loads[label]['f_y']
277
+ self._points_disc_y.remove(start)
278
+ self._load_y[start] -= mag*(Min(x,end)-start)
279
+ self._moment_y[start] += mag*(Min(x,end)-start)*(x0-(start+(Min(x,end)))/2)
280
+ val = self._distributed_loads.pop(label)
281
+ print(f"removed load {label}: {val}")
282
+
283
+ elif label in self._conc_loads :
284
+
285
+ self._loads_applied.pop(label)
286
+ start = self._conc_loads[label]['x']
287
+ self._points_disc_x.remove(start)
288
+ self._points_disc_y.remove(start)
289
+ self._moment_y[start] += self._conc_loads[label]['f_y']*(x0-start)
290
+ self._moment_x[start] -= self._conc_loads[label]['f_x']*(y-self._conc_loads[label]['y'])
291
+ self._load_x[start] -= self._conc_loads[label]['f_x']
292
+ self._load_y[start] -= self._conc_loads[label]['f_y']
293
+ val = self._conc_loads.pop(label)
294
+ print(f"removed load {label}: {val}")
295
+
296
+ else :
297
+ raise ValueError("label not found")
298
+
299
+ def change_support_position(self, left_support=None, right_support=None):
300
+ """
301
+ Change position of supports.
302
+ If not provided , defaults to the old value.
303
+ Parameters
304
+ ==========
305
+
306
+ left_support: tuple (x, y)
307
+ x: float
308
+ x-coordinate value of the left_support
309
+
310
+ y: float
311
+ y-coordinate value of the left_support
312
+
313
+ right_support: tuple (x, y)
314
+ x: float
315
+ x-coordinate value of the right_support
316
+
317
+ y: float
318
+ y-coordinate value of the right_support
319
+ """
320
+ if left_support is not None:
321
+ self._left_support = (left_support[0],left_support[1])
322
+
323
+ if right_support is not None:
324
+ self._right_support = (right_support[0],right_support[1])
325
+
326
+ self._shape_eqn = None
327
+ self._shape_eqn = self.get_shape_eqn
328
+
329
+ def change_crown_position(self,crown_x=None,crown_y=None):
330
+ """
331
+ Change the position of the crown/hinge of the arch
332
+
333
+ Parameters
334
+ ==========
335
+
336
+ crown_x: Float
337
+ The x coordinate of the position of the hinge
338
+ - if not provided, defaults to old value
339
+
340
+ crown_y: Float
341
+ The y coordinate of the position of the hinge
342
+ - if not provided defaults to None
343
+ """
344
+ self._crown_x = crown_x
345
+ self._crown_y = crown_y
346
+ self._shape_eqn = None
347
+ self._shape_eqn = self.get_shape_eqn
348
+
349
+ def change_support_type(self,left_support=None,right_support=None):
350
+ """
351
+ Add the type for support at each end.
352
+ Can use roller or hinge support at each end.
353
+
354
+ Parameters
355
+ ==========
356
+
357
+ left_support, right_support : string
358
+ Type of support at respective end
359
+
360
+ - For roller support , left_support/right_support = "roller"
361
+ - For hinged support, left_support/right_support = "hinge"
362
+ - defaults to hinge if value not provided
363
+
364
+ Examples
365
+ ========
366
+
367
+ For applying roller support at right end
368
+
369
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
370
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
371
+ >>> a.change_support_type(right_support="roller")
372
+
373
+ """
374
+ support_types = ['roller','hinge']
375
+ if left_support:
376
+ if left_support not in support_types:
377
+ raise ValueError("supports must only be roller or hinge")
378
+
379
+ self._supports['left'] = left_support
380
+
381
+ if right_support:
382
+ if right_support not in support_types:
383
+ raise ValueError("supports must only be roller or hinge")
384
+
385
+ self._supports['right'] = right_support
386
+
387
+ def add_member(self,y):
388
+ """
389
+ This method adds a member/rod at a particular height y.
390
+ A rod is used for stability of the structure in case of a roller support.
391
+ """
392
+ if y>self._crown_y or y<min(self._left_support[1], self._right_support[1]):
393
+ raise ValueError(f"position of support must be between y={min(self._left_support[1], self._right_support[1])} and y={self._crown_y}")
394
+ x = Symbol('x')
395
+ a = diff(self._shape_eqn,x).subs(x,self._crown_x+1)/2
396
+ x_diff = sqrt((y - self._crown_y)/a)
397
+ x1 = self._crown_x + x_diff
398
+ x2 = self._crown_x - x_diff
399
+ self._member = (x1,x2,y)
400
+
401
+ def shear_force_at(self, pos = None, **kwargs):
402
+ """
403
+ return the shear at some x-coordinates
404
+ if no x value provided, returns the formula
405
+ """
406
+ if pos is None:
407
+ return self._shear_force
408
+ else:
409
+ x = Symbol('x')
410
+ if 'dir' in kwargs:
411
+ dir = kwargs['dir']
412
+ return limit(self._shear_force,x,pos,dir=dir)
413
+ return self._shear_force.subs(x,pos)
414
+
415
+ def bending_moment_at(self, pos = None, **kwargs):
416
+ """
417
+ return the bending moment at some x-coordinates
418
+ if no x value provided, returns the formula
419
+ """
420
+ if pos is None:
421
+ return self._bending_moment
422
+ else:
423
+ x0 = Symbol('x0')
424
+ if 'dir' in kwargs:
425
+ dir = kwargs['dir']
426
+ return limit(self._bending_moment,x0,pos,dir=dir)
427
+ return self._bending_moment.subs(x0,pos)
428
+
429
+
430
+ def axial_force_at(self,pos = None, **kwargs):
431
+ """
432
+ return the axial/normal force generated at some x-coordinate
433
+ if no x value provided, returns the formula
434
+ """
435
+ if pos is None:
436
+ return self._axial_force
437
+ else:
438
+ x = Symbol('x')
439
+ if 'dir' in kwargs:
440
+ dir = kwargs['dir']
441
+ return limit(self._axial_force,x,pos,dir=dir)
442
+ return self._axial_force.subs(x,pos)
443
+
444
+ def solve(self):
445
+ """
446
+ This method solves for the reaction forces generated at the supports,\n
447
+ and bending moment and generated in the arch and tension produced in the member if used.
448
+
449
+ Examples
450
+ ========
451
+
452
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
453
+ >>> a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
454
+ >>> a.apply_load(0,'C',start=3,end=5,mag=-10)
455
+ >>> a.solve()
456
+ >>> a.reaction_force
457
+ {R_A_x: 8, R_A_y: 12, R_B_x: -8, R_B_y: 8}
458
+
459
+ >>> from sympy import Symbol
460
+ >>> t = Symbol('t')
461
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
462
+ >>> a = Arch((0,0),(16,0),crown_x=8,crown_y=5)
463
+ >>> a.apply_load(0,'C',start=3,end=5,mag=t)
464
+ >>> a.solve()
465
+ >>> a.reaction_force
466
+ {R_A_x: -4*t/5, R_A_y: -3*t/2, R_B_x: 4*t/5, R_B_y: -t/2}
467
+
468
+ >>> a.bending_moment_at(4)
469
+ -5*t/2
470
+ """
471
+ y = Symbol('y')
472
+ x = Symbol('x')
473
+ x0 = Symbol('x0')
474
+
475
+ discontinuity_points_x = sorted(self._points_disc_x)
476
+ discontinuity_points_y = sorted(self._points_disc_y)
477
+
478
+ self._moment_x_func = Piecewise((0,True))
479
+ self._moment_y_func = Piecewise((0,True))
480
+
481
+ self._load_x_func = Piecewise((0,True))
482
+ self._load_y_func = Piecewise((0,True))
483
+
484
+ accumulated_x_moment = 0
485
+ accumulated_y_moment = 0
486
+
487
+ accumulated_x_load = 0
488
+ accumulated_y_load = 0
489
+
490
+ for point in discontinuity_points_x:
491
+ cond = (x >= point)
492
+ accumulated_x_load += self._load_x[point]
493
+ accumulated_x_moment += self._moment_x[point]
494
+ self._load_x_func = Piecewise((accumulated_x_load,cond),(self._load_x_func,True))
495
+ self._moment_x_func = Piecewise((accumulated_x_moment,cond),(self._moment_x_func,True))
496
+
497
+ for point in discontinuity_points_y:
498
+ cond = (x >= point)
499
+ accumulated_y_moment += self._moment_y[point]
500
+ accumulated_y_load += self._load_y[point]
501
+ self._load_y_func = Piecewise((accumulated_y_load,cond),(self._load_y_func,True))
502
+ self._moment_y_func = Piecewise((accumulated_y_moment,cond),(self._moment_y_func,True))
503
+
504
+ moment_A = self._moment_y_func.subs(x,self._right_support[0]).subs(x0,self._left_support[0]) +\
505
+ self._moment_x_func.subs(x,self._right_support[0]).subs(y,self._left_support[1])
506
+
507
+ moment_hinge_left = self._moment_y_func.subs(x,self._crown_x).subs(x0,self._crown_x) +\
508
+ self._moment_x_func.subs(x,self._crown_x).subs(y,self._crown_y)
509
+
510
+ moment_hinge_right = self._moment_y_func.subs(x,self._right_support[0]).subs(x0,self._crown_x)- \
511
+ self._moment_y_func.subs(x,self._crown_x).subs(x0,self._crown_x) +\
512
+ self._moment_x_func.subs(x,self._right_support[0]).subs(y,self._crown_y) -\
513
+ self._moment_x_func.subs(x,self._crown_x).subs(y,self._crown_y)
514
+
515
+ net_x = self._load_x_func.subs(x,self._right_support[0])
516
+ net_y = self._load_y_func.subs(x,self._right_support[0])
517
+
518
+ if (self._supports['left']=='roller' or self._supports['right']=='roller') and not self._member:
519
+ print("member must be added if any of the supports is roller")
520
+ return
521
+
522
+ R_A_x, R_A_y, R_B_x, R_B_y, T = symbols('R_A_x R_A_y R_B_x R_B_y T')
523
+
524
+ if self._supports['left'] == 'roller' and self._supports['right'] == 'roller':
525
+
526
+ if self._member[2]>=max(self._left_support[1],self._right_support[1]):
527
+
528
+ if net_x!=0:
529
+ raise ValueError("net force in x direction not possible under the specified conditions")
530
+
531
+ else:
532
+ eq1 = Eq(R_A_x ,0)
533
+ eq2 = Eq(R_B_x, 0)
534
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
535
+
536
+ eq4 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])-\
537
+ R_B_x*(self._right_support[1]-self._left_support[1])+moment_A,0)
538
+
539
+ eq5 = Eq(moment_hinge_right + R_B_y*(self._right_support[0]-self._crown_x) +\
540
+ T*(self._member[2]-self._crown_y),0)
541
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
542
+
543
+ elif self._member[2]>=self._left_support[1]:
544
+ eq1 = Eq(R_A_x ,0)
545
+ eq2 = Eq(R_B_x, 0)
546
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
547
+ eq4 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])-\
548
+ T*(self._member[2]-self._left_support[1])+moment_A,0)
549
+ eq5 = Eq(T+net_x,0)
550
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
551
+
552
+ elif self._member[2]>=self._right_support[1]:
553
+ eq1 = Eq(R_A_x ,0)
554
+ eq2 = Eq(R_B_x, 0)
555
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
556
+ eq4 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])+\
557
+ T*(self._member[2]-self._left_support[1])+moment_A,0)
558
+ eq5 = Eq(T-net_x,0)
559
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
560
+
561
+ elif self._supports['left'] == 'roller':
562
+ if self._member[2]>=max(self._left_support[1], self._right_support[1]):
563
+ eq1 = Eq(R_A_x ,0)
564
+ eq2 = Eq(R_B_x+net_x,0)
565
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
566
+ eq4 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])-\
567
+ R_B_x*(self._right_support[1]-self._left_support[1])+moment_A,0)
568
+ eq5 = Eq(moment_hinge_left + R_A_y*(self._left_support[0]-self._crown_x) -\
569
+ T*(self._member[2]-self._crown_y),0)
570
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
571
+
572
+ elif self._member[2]>=self._left_support[1]:
573
+ eq1 = Eq(R_A_x ,0)
574
+ eq2 = Eq(R_B_x+ T +net_x,0)
575
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
576
+ eq4 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])-\
577
+ R_B_x*(self._right_support[1]-self._left_support[1])-\
578
+ T*(self._member[2]-self._left_support[0])+moment_A,0)
579
+ eq5 = Eq(moment_hinge_left + R_A_y*(self._left_support[0]-self._crown_x)-\
580
+ T*(self._member[2]-self._crown_y),0)
581
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
582
+
583
+ elif self._member[2]>=self._right_support[0]:
584
+ eq1 = Eq(R_A_x,0)
585
+ eq2 = Eq(R_B_x- T +net_x,0)
586
+ eq3 = Eq(R_A_y + R_B_y + net_y,0)
587
+ eq4 = Eq(moment_hinge_left+R_A_y*(self._left_support[0]-self._crown_x),0)
588
+ eq5 = Eq(moment_A+R_B_y*(self._right_support[0]-self._left_support[0])-\
589
+ R_B_x*(self._right_support[1]-self._left_support[1])+\
590
+ T*(self._member[2]-self._left_support[1]),0)
591
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
592
+
593
+ elif self._supports['right'] == 'roller':
594
+ if self._member[2]>=max(self._left_support[1], self._right_support[1]):
595
+ eq1 = Eq(R_B_x,0)
596
+ eq2 = Eq(R_A_x+net_x,0)
597
+ eq3 = Eq(R_A_y+R_B_y+net_y,0)
598
+ eq4 = Eq(moment_hinge_right+R_B_y*(self._right_support[0]-self._crown_x)+\
599
+ T*(self._member[2]-self._crown_y),0)
600
+ eq5 = Eq(moment_A+R_B_y*(self._right_support[0]-self._left_support[0]),0)
601
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
602
+
603
+ elif self._member[2]>=self._left_support[1]:
604
+ eq1 = Eq(R_B_x,0)
605
+ eq2 = Eq(R_A_x+T+net_x,0)
606
+ eq3 = Eq(R_A_y+R_B_y+net_y,0)
607
+ eq4 = Eq(moment_hinge_right+R_B_y*(self._right_support[0]-self._crown_x),0)
608
+ eq5 = Eq(moment_A-T*(self._member[2]-self._left_support[1])+\
609
+ R_B_y*(self._right_support[0]-self._left_support[0]),0)
610
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
611
+
612
+ elif self._member[2]>=self._right_support[1]:
613
+ eq1 = Eq(R_B_x,0)
614
+ eq2 = Eq(R_A_x-T+net_x,0)
615
+ eq3 = Eq(R_A_y+R_B_y+net_y,0)
616
+ eq4 = Eq(moment_hinge_right+R_B_y*(self._right_support[0]-self._crown_x)+\
617
+ T*(self._member[2]-self._crown_y),0)
618
+ eq5 = Eq(moment_A+T*(self._member[2]-self._left_support[1])+\
619
+ R_B_y*(self._right_support[0]-self._left_support[0]))
620
+ solution = solve((eq1,eq2,eq3,eq4,eq5),(R_A_x,R_A_y,R_B_x,R_B_y,T))
621
+ else:
622
+ eq1 = Eq(R_A_x + R_B_x + net_x,0)
623
+ eq2 = Eq(R_A_y + R_B_y + net_y,0)
624
+ eq3 = Eq(R_B_y*(self._right_support[0]-self._left_support[0])-\
625
+ R_B_x*(self._right_support[1]-self._left_support[1])+moment_A,0)
626
+ eq4 = Eq(moment_hinge_right + R_B_y*(self._right_support[0]-self._crown_x) -\
627
+ R_B_x*(self._right_support[1]-self._crown_y),0)
628
+ solution = solve((eq1,eq2,eq3,eq4),(R_A_x,R_A_y,R_B_x,R_B_y))
629
+
630
+ for symb in self._reaction_force:
631
+ self._reaction_force[symb] = solution[symb]
632
+
633
+ self._bending_moment = - (self._moment_x_func.subs(x,x0) + self._moment_y_func.subs(x,x0) -\
634
+ solution[R_A_y]*(x0-self._left_support[0]) +\
635
+ solution[R_A_x]*(self._shape_eqn.subs({x:x0})-self._left_support[1]))
636
+
637
+ angle = atan(diff(self._shape_eqn,x))
638
+
639
+ fx = (self._load_x_func+solution[R_A_x])
640
+ fy = (self._load_y_func+solution[R_A_y])
641
+
642
+ axial_force = fx*cos(angle) + fy*sin(angle)
643
+ shear_force = -fx*sin(angle) + fy*cos(angle)
644
+
645
+ self._axial_force = axial_force
646
+ self._shear_force = shear_force
647
+
648
+ @doctest_depends_on(modules=('numpy',))
649
+ def draw(self):
650
+ """
651
+ This method returns a plot object containing the diagram of the specified arch along with the supports
652
+ and forces applied to the structure.
653
+
654
+ Examples
655
+ ========
656
+
657
+ >>> from sympy import Symbol
658
+ >>> t = Symbol('t')
659
+ >>> from sympy.physics.continuum_mechanics.arch import Arch
660
+ >>> a = Arch((0,0),(40,0),crown_x=20,crown_y=12)
661
+ >>> a.apply_load(-1,'C',8,150,angle=270)
662
+ >>> a.apply_load(0,'D',start=20,end=40,mag=-4)
663
+ >>> a.apply_load(-1,'E',10,t,angle=300)
664
+ >>> p = a.draw()
665
+ >>> p # doctest: +ELLIPSIS
666
+ Plot object containing:
667
+ [0]: cartesian line: 11.325 - 3*(x - 20)**2/100 for x over (0.0, 40.0)
668
+ [1]: cartesian line: 12 - 3*(x - 20)**2/100 for x over (0.0, 40.0)
669
+ ...
670
+ >>> p.show()
671
+
672
+ """
673
+ x = Symbol('x')
674
+ markers = []
675
+ annotations = self._draw_loads()
676
+ rectangles = []
677
+ supports = self._draw_supports()
678
+ markers+=supports
679
+
680
+ xmax = self._right_support[0]
681
+ xmin = self._left_support[0]
682
+ ymin = min(self._left_support[1],self._right_support[1])
683
+ ymax = self._crown_y
684
+
685
+ lim = max(xmax*1.1-xmin*0.8+1, ymax*1.1-ymin*0.8+1)
686
+
687
+ rectangles = self._draw_rectangles()
688
+
689
+ filler = self._draw_filler()
690
+ rectangles+=filler
691
+
692
+ if self._member is not None:
693
+ if(self._member[2]>=self._right_support[1]):
694
+ markers.append(
695
+ {
696
+ 'args':[[self._member[1]+0.005*lim],[self._member[2]]],
697
+ 'marker':'o',
698
+ 'markersize': 4,
699
+ 'color': 'white',
700
+ 'markerfacecolor':'none'
701
+ }
702
+ )
703
+
704
+ if(self._member[2]>=self._left_support[1]):
705
+ markers.append(
706
+ {
707
+ 'args':[[self._member[0]-0.005*lim],[self._member[2]]],
708
+ 'marker':'o',
709
+ 'markersize': 4,
710
+ 'color': 'white',
711
+ 'markerfacecolor':'none'
712
+ }
713
+ )
714
+
715
+
716
+
717
+ markers.append({
718
+ 'args':[[self._crown_x],[self._crown_y-0.005*lim]],
719
+ 'marker':'o',
720
+ 'markersize': 5,
721
+ 'color':'white',
722
+ 'markerfacecolor':'none',
723
+ })
724
+
725
+ if lim==xmax*1.1-xmin*0.8+1:
726
+
727
+ sing_plot = plot(self._shape_eqn-0.015*lim,
728
+ self._shape_eqn,
729
+ (x, self._left_support[0], self._right_support[0]),
730
+ markers=markers,
731
+ show=False,
732
+ annotations=annotations,
733
+ rectangles = rectangles,
734
+ xlim=(xmin-0.05*lim, xmax*1.1),
735
+ ylim=(xmin-0.05*lim, xmax*1.1),
736
+ axis=False,
737
+ line_color='brown')
738
+
739
+ else:
740
+ sing_plot = plot(self._shape_eqn-0.015*lim,
741
+ self._shape_eqn,
742
+ (x, self._left_support[0], self._right_support[0]),
743
+ markers=markers,
744
+ show=False,
745
+ annotations=annotations,
746
+ rectangles = rectangles,
747
+ xlim=(ymin-0.05*lim, ymax*1.1),
748
+ ylim=(ymin-0.05*lim, ymax*1.1),
749
+ axis=False,
750
+ line_color='brown')
751
+
752
+ return sing_plot
753
+
754
+
755
+ def _draw_supports(self):
756
+ support_markers = []
757
+
758
+ xmax = self._right_support[0]
759
+ xmin = self._left_support[0]
760
+ ymin = min(self._left_support[1],self._right_support[1])
761
+ ymax = self._crown_y
762
+
763
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
764
+ max_diff = 1.1*xmax-0.8*xmin
765
+ else:
766
+ max_diff = 1.1*ymax-0.8*ymin
767
+
768
+ if self._supports['left']=='roller':
769
+ support_markers.append(
770
+ {
771
+ 'args':[
772
+ [self._left_support[0]],
773
+ [self._left_support[1]-0.02*max_diff]
774
+ ],
775
+ 'marker':'o',
776
+ 'markersize':11,
777
+ 'color':'black',
778
+ 'markerfacecolor':'none'
779
+ }
780
+ )
781
+ else:
782
+ support_markers.append(
783
+ {
784
+ 'args':[
785
+ [self._left_support[0]],
786
+ [self._left_support[1]-0.007*max_diff]
787
+ ],
788
+ 'marker':6,
789
+ 'markersize':15,
790
+ 'color':'black',
791
+ 'markerfacecolor':'none'
792
+ }
793
+ )
794
+
795
+ if self._supports['right']=='roller':
796
+ support_markers.append(
797
+ {
798
+ 'args':[
799
+ [self._right_support[0]],
800
+ [self._right_support[1]-0.02*max_diff]
801
+ ],
802
+ 'marker':'o',
803
+ 'markersize':11,
804
+ 'color':'black',
805
+ 'markerfacecolor':'none'
806
+ }
807
+ )
808
+ else:
809
+ support_markers.append(
810
+ {
811
+ 'args':[
812
+ [self._right_support[0]],
813
+ [self._right_support[1]-0.007*max_diff]
814
+ ],
815
+ 'marker':6,
816
+ 'markersize':15,
817
+ 'color':'black',
818
+ 'markerfacecolor':'none'
819
+ }
820
+ )
821
+
822
+ support_markers.append(
823
+ {
824
+ 'args':[
825
+ [self._right_support[0]],
826
+ [self._right_support[1]-0.036*max_diff]
827
+ ],
828
+ 'marker':'_',
829
+ 'markersize':15,
830
+ 'color':'black',
831
+ 'markerfacecolor':'none'
832
+ }
833
+ )
834
+
835
+ support_markers.append(
836
+ {
837
+ 'args':[
838
+ [self._left_support[0]],
839
+ [self._left_support[1]-0.036*max_diff]
840
+ ],
841
+ 'marker':'_',
842
+ 'markersize':15,
843
+ 'color':'black',
844
+ 'markerfacecolor':'none'
845
+ }
846
+ )
847
+
848
+ return support_markers
849
+
850
+ def _draw_rectangles(self):
851
+ member = []
852
+
853
+ xmax = self._right_support[0]
854
+ xmin = self._left_support[0]
855
+ ymin = min(self._left_support[1],self._right_support[1])
856
+ ymax = self._crown_y
857
+
858
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
859
+ max_diff = 1.1*xmax-0.8*xmin
860
+ else:
861
+ max_diff = 1.1*ymax-0.8*ymin
862
+
863
+ if self._member is not None:
864
+ if self._member[2]>= max(self._left_support[1],self._right_support[1]):
865
+ member.append(
866
+ {
867
+ 'xy':(self._member[0],self._member[2]-0.005*max_diff),
868
+ 'width':self._member[1]-self._member[0],
869
+ 'height': 0.01*max_diff,
870
+ 'angle': 0,
871
+ 'color':'brown',
872
+ }
873
+ )
874
+
875
+ elif self._member[2]>=self._left_support[1]:
876
+ member.append(
877
+ {
878
+ 'xy':(self._member[0],self._member[2]-0.005*max_diff),
879
+ 'width':self._right_support[0]-self._member[0],
880
+ 'height': 0.01*max_diff,
881
+ 'angle': 0,
882
+ 'color':'brown',
883
+ }
884
+ )
885
+
886
+ else:
887
+ member.append(
888
+ {
889
+ 'xy':(self._member[1],self._member[2]-0.005*max_diff),
890
+ 'width':abs(self._left_support[0]-self._member[1]),
891
+ 'height': 0.01*max_diff,
892
+ 'angle': 180,
893
+ 'color':'brown',
894
+ }
895
+ )
896
+
897
+ if self._distributed_loads:
898
+ for loads in self._distributed_loads:
899
+
900
+ start = self._distributed_loads[loads]['start']
901
+ end = self._distributed_loads[loads]['end']
902
+
903
+ member.append(
904
+ {
905
+ 'xy':(start,self._crown_y+max_diff*0.15),
906
+ 'width': (end-start),
907
+ 'height': max_diff*0.01,
908
+ 'color': 'orange'
909
+ }
910
+ )
911
+
912
+
913
+ return member
914
+
915
+ def _draw_loads(self):
916
+ load_annotations = []
917
+
918
+ xmax = self._right_support[0]
919
+ xmin = self._left_support[0]
920
+ ymin = min(self._left_support[1],self._right_support[1])
921
+ ymax = self._crown_y
922
+
923
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
924
+ max_diff = 1.1*xmax-0.8*xmin
925
+ else:
926
+ max_diff = 1.1*ymax-0.8*ymin
927
+
928
+ for load in self._conc_loads:
929
+ x = self._conc_loads[load]['x']
930
+ y = self._conc_loads[load]['y']
931
+ angle = self._conc_loads[load]['angle']
932
+ mag = self._conc_loads[load]['mag']
933
+ load_annotations.append(
934
+ {
935
+ 'text':'',
936
+ 'xy':(
937
+ x+cos(rad(angle))*max_diff*0.08,
938
+ y+sin(rad(angle))*max_diff*0.08
939
+ ),
940
+ 'xytext':(x,y),
941
+ 'fontsize':10,
942
+ 'fontweight': 'bold',
943
+ 'arrowprops':{'width':1.5, 'headlength':5, 'headwidth':5, 'facecolor':'blue','edgecolor':'blue'}
944
+ }
945
+ )
946
+ load_annotations.append(
947
+ {
948
+ 'text':f'{load}: {mag} N',
949
+ 'fontsize':10,
950
+ 'fontweight': 'bold',
951
+ 'xy': (x+cos(rad(angle))*max_diff*0.12,y+sin(rad(angle))*max_diff*0.12)
952
+ }
953
+ )
954
+
955
+ for load in self._distributed_loads:
956
+ start = self._distributed_loads[load]['start']
957
+ end = self._distributed_loads[load]['end']
958
+ mag = self._distributed_loads[load]['f_y']
959
+ x_points = numpy.arange(start,end,(end-start)/(max_diff*0.25))
960
+ x_points = numpy.append(x_points,end)
961
+ for point in x_points:
962
+ if(mag<0):
963
+ load_annotations.append(
964
+ {
965
+ 'text':'',
966
+ 'xy':(point,self._crown_y+max_diff*0.05),
967
+ 'xytext': (point,self._crown_y+max_diff*0.15),
968
+ 'arrowprops':{'width':1.5, 'headlength':5, 'headwidth':5, 'facecolor':'orange','edgecolor':'orange'}
969
+ }
970
+ )
971
+ else:
972
+ load_annotations.append(
973
+ {
974
+ 'text':'',
975
+ 'xy':(point,self._crown_y+max_diff*0.2),
976
+ 'xytext': (point,self._crown_y+max_diff*0.15),
977
+ 'arrowprops':{'width':1.5, 'headlength':5, 'headwidth':5, 'facecolor':'orange','edgecolor':'orange'}
978
+ }
979
+ )
980
+ if(mag<0):
981
+ load_annotations.append(
982
+ {
983
+ 'text':f'{load}: {abs(mag)} N/m',
984
+ 'fontsize':10,
985
+ 'fontweight': 'bold',
986
+ 'xy':((start+end)/2,self._crown_y+max_diff*0.175)
987
+ }
988
+ )
989
+ else:
990
+ load_annotations.append(
991
+ {
992
+ 'text':f'{load}: {abs(mag)} N/m',
993
+ 'fontsize':10,
994
+ 'fontweight': 'bold',
995
+ 'xy':((start+end)/2,self._crown_y+max_diff*0.125)
996
+ }
997
+ )
998
+ return load_annotations
999
+
1000
+ def _draw_filler(self):
1001
+ x = Symbol('x')
1002
+ filler = []
1003
+ xmax = self._right_support[0]
1004
+ xmin = self._left_support[0]
1005
+ ymin = min(self._left_support[1],self._right_support[1])
1006
+ ymax = self._crown_y
1007
+
1008
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
1009
+ max_diff = 1.1*xmax-0.8*xmin
1010
+ else:
1011
+ max_diff = 1.1*ymax-0.8*ymin
1012
+
1013
+ x_points = numpy.arange(self._left_support[0],self._right_support[0],(self._right_support[0]-self._left_support[0])/(max_diff*max_diff))
1014
+
1015
+ for point in x_points:
1016
+ filler.append(
1017
+ {
1018
+ 'xy':(point,self._shape_eqn.subs(x,point)-max_diff*0.015),
1019
+ 'width': (self._right_support[0]-self._left_support[0])/(max_diff*max_diff),
1020
+ 'height': max_diff*0.015,
1021
+ 'color': 'brown'
1022
+ }
1023
+ )
1024
+
1025
+ return filler
miniconda3/envs/ladir/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
 
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/cable.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module can be used to solve problems related
3
+ to 2D Cables.
4
+ """
5
+
6
+ from sympy.core.sympify import sympify
7
+ from sympy.core.symbol import Symbol,symbols
8
+ from sympy import sin, cos, pi, atan, diff, Piecewise, solve, rad
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.solvers.solveset import linsolve
11
+ from sympy.matrices import Matrix
12
+ from sympy.plotting import plot
13
+
14
+ class Cable:
15
+ """
16
+ Cables are structures in engineering that support
17
+ the applied transverse loads through the tensile
18
+ resistance developed in its members.
19
+
20
+ Cables are widely used in suspension bridges, tension
21
+ leg offshore platforms, transmission lines, and find
22
+ use in several other engineering applications.
23
+
24
+ Examples
25
+ ========
26
+ A cable is supported at (0, 10) and (10, 10). Two point loads
27
+ acting vertically downwards act on the cable, one with magnitude 3 kN
28
+ and acting 2 meters from the left support and 3 meters below it, while
29
+ the other with magnitude 2 kN is 6 meters from the left support and
30
+ 6 meters below it.
31
+
32
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
33
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
34
+ >>> c.apply_load(-1, ('P', 2, 7, 3, 270))
35
+ >>> c.apply_load(-1, ('Q', 6, 4, 2, 270))
36
+ >>> c.loads
37
+ {'distributed': {}, 'point_load': {'P': [3, 270], 'Q': [2, 270]}}
38
+ >>> c.loads_position
39
+ {'P': [2, 7], 'Q': [6, 4]}
40
+ """
41
+ def __init__(self, support_1, support_2):
42
+ """
43
+ Initializes the class.
44
+
45
+ Parameters
46
+ ==========
47
+
48
+ support_1 and support_2 are tuples of the form
49
+ (label, x, y), where
50
+
51
+ label : String or symbol
52
+ The label of the support
53
+
54
+ x : Sympifyable
55
+ The x coordinate of the position of the support
56
+
57
+ y : Sympifyable
58
+ The y coordinate of the position of the support
59
+ """
60
+ self._left_support = []
61
+ self._right_support = []
62
+ self._supports = {}
63
+ self._support_labels = []
64
+ self._loads = {"distributed": {}, "point_load": {}}
65
+ self._loads_position = {}
66
+ self._length = 0
67
+ self._reaction_loads = {}
68
+ self._tension = {}
69
+ self._lowest_x_global = sympify(0)
70
+ self._lowest_y_global = sympify(0)
71
+ self._cable_eqn = None
72
+ self._tension_func = None
73
+ if support_1[0] == support_2[0]:
74
+ raise ValueError("Supports can not have the same label")
75
+
76
+ elif support_1[1] == support_2[1]:
77
+ raise ValueError("Supports can not be at the same location")
78
+
79
+ x1 = sympify(support_1[1])
80
+ y1 = sympify(support_1[2])
81
+ self._supports[support_1[0]] = [x1, y1]
82
+
83
+ x2 = sympify(support_2[1])
84
+ y2 = sympify(support_2[2])
85
+ self._supports[support_2[0]] = [x2, y2]
86
+
87
+ if support_1[1] < support_2[1]:
88
+ self._left_support.append(x1)
89
+ self._left_support.append(y1)
90
+ self._right_support.append(x2)
91
+ self._right_support.append(y2)
92
+ self._support_labels.append(support_1[0])
93
+ self._support_labels.append(support_2[0])
94
+
95
+ else:
96
+ self._left_support.append(x2)
97
+ self._left_support.append(y2)
98
+ self._right_support.append(x1)
99
+ self._right_support.append(y1)
100
+ self._support_labels.append(support_2[0])
101
+ self._support_labels.append(support_1[0])
102
+
103
+ for i in self._support_labels:
104
+ self._reaction_loads[Symbol("R_"+ i +"_x")] = 0
105
+ self._reaction_loads[Symbol("R_"+ i +"_y")] = 0
106
+
107
+ @property
108
+ def supports(self):
109
+ """
110
+ Returns the supports of the cable along with their
111
+ positions.
112
+ """
113
+ return self._supports
114
+
115
+ @property
116
+ def left_support(self):
117
+ """
118
+ Returns the position of the left support.
119
+ """
120
+ return self._left_support
121
+
122
+ @property
123
+ def right_support(self):
124
+ """
125
+ Returns the position of the right support.
126
+ """
127
+ return self._right_support
128
+
129
+ @property
130
+ def loads(self):
131
+ """
132
+ Returns the magnitude and direction of the loads
133
+ acting on the cable.
134
+ """
135
+ return self._loads
136
+
137
+ @property
138
+ def loads_position(self):
139
+ """
140
+ Returns the position of the point loads acting on the
141
+ cable.
142
+ """
143
+ return self._loads_position
144
+
145
+ @property
146
+ def length(self):
147
+ """
148
+ Returns the length of the cable.
149
+ """
150
+ return self._length
151
+
152
+ @property
153
+ def reaction_loads(self):
154
+ """
155
+ Returns the reaction forces at the supports, which are
156
+ initialized to 0.
157
+ """
158
+ return self._reaction_loads
159
+
160
+ @property
161
+ def tension(self):
162
+ """
163
+ Returns the tension developed in the cable due to the loads
164
+ applied.
165
+ """
166
+ return self._tension
167
+
168
+ def tension_at(self, x):
169
+ """
170
+ Returns the tension at a given value of x developed due to
171
+ distributed load.
172
+ """
173
+ if 'distributed' not in self._tension.keys():
174
+ raise ValueError("No distributed load added or solve method not called")
175
+
176
+ if x > self._right_support[0] or x < self._left_support[0]:
177
+ raise ValueError("The value of x should be between the two supports")
178
+
179
+ A = self._tension['distributed']
180
+ X = Symbol('X')
181
+
182
+ return A.subs({X:(x-self._lowest_x_global)})
183
+
184
+ def apply_length(self, length):
185
+ """
186
+ This method specifies the length of the cable
187
+
188
+ Parameters
189
+ ==========
190
+
191
+ length : Sympifyable
192
+ The length of the cable
193
+
194
+ Examples
195
+ ========
196
+
197
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
198
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
199
+ >>> c.apply_length(20)
200
+ >>> c.length
201
+ 20
202
+ """
203
+ dist = ((self._left_support[0] - self._right_support[0])**2
204
+ - (self._left_support[1] - self._right_support[1])**2)**(1/2)
205
+
206
+ if length < dist:
207
+ raise ValueError("length should not be less than the distance between the supports")
208
+
209
+ self._length = length
210
+
211
+ def change_support(self, label, new_support):
212
+ """
213
+ This method changes the mentioned support with a new support.
214
+
215
+ Parameters
216
+ ==========
217
+ label: String or symbol
218
+ The label of the support to be changed
219
+
220
+ new_support: Tuple of the form (new_label, x, y)
221
+ new_label: String or symbol
222
+ The label of the new support
223
+
224
+ x: Sympifyable
225
+ The x-coordinate of the position of the new support.
226
+
227
+ y: Sympifyable
228
+ The y-coordinate of the position of the new support.
229
+
230
+ Examples
231
+ ========
232
+
233
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
234
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
235
+ >>> c.supports
236
+ {'A': [0, 10], 'B': [10, 10]}
237
+ >>> c.change_support('B', ('C', 5, 6))
238
+ >>> c.supports
239
+ {'A': [0, 10], 'C': [5, 6]}
240
+ """
241
+ if label not in self._supports:
242
+ raise ValueError("No support exists with the given label")
243
+
244
+ i = self._support_labels.index(label)
245
+ rem_label = self._support_labels[(i+1)%2]
246
+ x1 = self._supports[rem_label][0]
247
+ y1 = self._supports[rem_label][1]
248
+
249
+ x = sympify(new_support[1])
250
+ y = sympify(new_support[2])
251
+
252
+ for l in self._loads_position:
253
+ if l[0] >= max(x, x1) or l[0] <= min(x, x1):
254
+ raise ValueError("The change in support will throw an existing load out of range")
255
+
256
+ self._supports.pop(label)
257
+ self._left_support.clear()
258
+ self._right_support.clear()
259
+ self._reaction_loads.clear()
260
+ self._support_labels.remove(label)
261
+
262
+ self._supports[new_support[0]] = [x, y]
263
+
264
+ if x1 < x:
265
+ self._left_support.append(x1)
266
+ self._left_support.append(y1)
267
+ self._right_support.append(x)
268
+ self._right_support.append(y)
269
+ self._support_labels.append(new_support[0])
270
+
271
+ else:
272
+ self._left_support.append(x)
273
+ self._left_support.append(y)
274
+ self._right_support.append(x1)
275
+ self._right_support.append(y1)
276
+ self._support_labels.insert(0, new_support[0])
277
+
278
+ for i in self._support_labels:
279
+ self._reaction_loads[Symbol("R_"+ i +"_x")] = 0
280
+ self._reaction_loads[Symbol("R_"+ i +"_y")] = 0
281
+
282
+ def apply_load(self, order, load):
283
+ """
284
+ This method adds load to the cable.
285
+
286
+ Parameters
287
+ ==========
288
+
289
+ order : Integer
290
+ The order of the applied load.
291
+
292
+ - For point loads, order = -1
293
+ - For distributed load, order = 0
294
+
295
+ load : tuple
296
+
297
+ * For point loads, load is of the form (label, x, y, magnitude, direction), where:
298
+
299
+ label : String or symbol
300
+ The label of the load
301
+
302
+ x : Sympifyable
303
+ The x coordinate of the position of the load
304
+
305
+ y : Sympifyable
306
+ The y coordinate of the position of the load
307
+
308
+ magnitude : Sympifyable
309
+ The magnitude of the load. It must always be positive
310
+
311
+ direction : Sympifyable
312
+ The angle, in degrees, that the load vector makes with the horizontal
313
+ in the counter-clockwise direction. It takes the values 0 to 360,
314
+ inclusive.
315
+
316
+
317
+ * For uniformly distributed load, load is of the form (label, magnitude)
318
+
319
+ label : String or symbol
320
+ The label of the load
321
+
322
+ magnitude : Sympifyable
323
+ The magnitude of the load. It must always be positive
324
+
325
+ Examples
326
+ ========
327
+
328
+ For a point load of magnitude 12 units inclined at 30 degrees with the horizontal:
329
+
330
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
331
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
332
+ >>> c.apply_load(-1, ('Z', 5, 5, 12, 30))
333
+ >>> c.loads
334
+ {'distributed': {}, 'point_load': {'Z': [12, 30]}}
335
+ >>> c.loads_position
336
+ {'Z': [5, 5]}
337
+
338
+
339
+ For a uniformly distributed load of magnitude 9 units:
340
+
341
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
342
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
343
+ >>> c.apply_load(0, ('X', 9))
344
+ >>> c.loads
345
+ {'distributed': {'X': 9}, 'point_load': {}}
346
+ """
347
+ if order == -1:
348
+ if len(self._loads["distributed"]) != 0:
349
+ raise ValueError("Distributed load already exists")
350
+
351
+ label = load[0]
352
+ if label in self._loads["point_load"]:
353
+ raise ValueError("Label already exists")
354
+
355
+ x = sympify(load[1])
356
+ y = sympify(load[2])
357
+
358
+ if x > self._right_support[0] or x < self._left_support[0]:
359
+ raise ValueError("The load should be positioned between the supports")
360
+
361
+ magnitude = sympify(load[3])
362
+ direction = sympify(load[4])
363
+
364
+ self._loads["point_load"][label] = [magnitude, direction]
365
+ self._loads_position[label] = [x, y]
366
+
367
+ elif order == 0:
368
+ if len(self._loads_position) != 0:
369
+ raise ValueError("Point load(s) already exist")
370
+
371
+ label = load[0]
372
+ if label in self._loads["distributed"]:
373
+ raise ValueError("Label already exists")
374
+
375
+ magnitude = sympify(load[1])
376
+
377
+ self._loads["distributed"][label] = magnitude
378
+
379
+ else:
380
+ raise ValueError("Order should be either -1 or 0")
381
+
382
+ def remove_loads(self, *args):
383
+ """
384
+ This methods removes the specified loads.
385
+
386
+ Parameters
387
+ ==========
388
+ This input takes multiple label(s) as input
389
+ label(s): String or symbol
390
+ The label(s) of the loads to be removed.
391
+
392
+ Examples
393
+ ========
394
+
395
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
396
+ >>> c = Cable(('A', 0, 10), ('B', 10, 10))
397
+ >>> c.apply_load(-1, ('Z', 5, 5, 12, 30))
398
+ >>> c.loads
399
+ {'distributed': {}, 'point_load': {'Z': [12, 30]}}
400
+ >>> c.remove_loads('Z')
401
+ >>> c.loads
402
+ {'distributed': {}, 'point_load': {}}
403
+ """
404
+ for i in args:
405
+ if len(self._loads_position) == 0:
406
+ if i not in self._loads['distributed']:
407
+ raise ValueError("Error removing load " + i + ": no such load exists")
408
+
409
+ else:
410
+ self._loads['disrtibuted'].pop(i)
411
+
412
+ else:
413
+ if i not in self._loads['point_load']:
414
+ raise ValueError("Error removing load " + i + ": no such load exists")
415
+
416
+ else:
417
+ self._loads['point_load'].pop(i)
418
+ self._loads_position.pop(i)
419
+
420
+ def solve(self, *args):
421
+ """
422
+ This method solves for the reaction forces at the supports, the tension developed in
423
+ the cable, and updates the length of the cable.
424
+
425
+ Parameters
426
+ ==========
427
+ This method requires no input when solving for point loads
428
+ For distributed load, the x and y coordinates of the lowest point of the cable are
429
+ required as
430
+
431
+ x: Sympifyable
432
+ The x coordinate of the lowest point
433
+
434
+ y: Sympifyable
435
+ The y coordinate of the lowest point
436
+
437
+ Examples
438
+ ========
439
+ For point loads,
440
+
441
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
442
+ >>> c = Cable(("A", 0, 10), ("B", 10, 10))
443
+ >>> c.apply_load(-1, ('Z', 2, 7.26, 3, 270))
444
+ >>> c.apply_load(-1, ('X', 4, 6, 8, 270))
445
+ >>> c.solve()
446
+ >>> c.tension
447
+ {A_Z: 8.91403453669861, X_B: 19*sqrt(13)/10, Z_X: 4.79150773600774}
448
+ >>> c.reaction_loads
449
+ {R_A_x: -5.25547445255474, R_A_y: 7.2, R_B_x: 5.25547445255474, R_B_y: 3.8}
450
+ >>> c.length
451
+ 5.7560958484519 + 2*sqrt(13)
452
+
453
+ For distributed load,
454
+
455
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
456
+ >>> c=Cable(("A", 0, 40),("B", 100, 20))
457
+ >>> c.apply_load(0, ("X", 850))
458
+ >>> c.solve(58.58)
459
+ >>> c.tension
460
+ {'distributed': 36465.0*sqrt(0.00054335718671383*X**2 + 1)}
461
+ >>> c.tension_at(0)
462
+ 61717.4130533677
463
+ >>> c.reaction_loads
464
+ {R_A_x: 36465.0, R_A_y: -49793.0, R_B_x: 44399.9537590861, R_B_y: 42868.2071025955}
465
+ """
466
+
467
+ if len(self._loads_position) != 0:
468
+ sorted_position = sorted(self._loads_position.items(), key = lambda item : item[1][0])
469
+
470
+ sorted_position.append(self._support_labels[1])
471
+ sorted_position.insert(0, self._support_labels[0])
472
+
473
+ self._tension.clear()
474
+ moment_sum_from_left_support = 0
475
+ moment_sum_from_right_support = 0
476
+ F_x = 0
477
+ F_y = 0
478
+ self._length = 0
479
+ tension_func = []
480
+ x = symbols('x')
481
+ for i in range(1, len(sorted_position)-1):
482
+ if i == 1:
483
+ self._length+=sqrt((self._left_support[0] - self._loads_position[sorted_position[i][0]][0])**2 + (self._left_support[1] - self._loads_position[sorted_position[i][0]][1])**2)
484
+
485
+ else:
486
+ self._length+=sqrt((self._loads_position[sorted_position[i-1][0]][0] - self._loads_position[sorted_position[i][0]][0])**2 + (self._loads_position[sorted_position[i-1][0]][1] - self._loads_position[sorted_position[i][0]][1])**2)
487
+
488
+ if i == len(sorted_position)-2:
489
+ self._length+=sqrt((self._right_support[0] - self._loads_position[sorted_position[i][0]][0])**2 + (self._right_support[1] - self._loads_position[sorted_position[i][0]][1])**2)
490
+
491
+ moment_sum_from_left_support += self._loads['point_load'][sorted_position[i][0]][0] * cos(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180) * abs(self._left_support[1] - self._loads_position[sorted_position[i][0]][1])
492
+ moment_sum_from_left_support += self._loads['point_load'][sorted_position[i][0]][0] * sin(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180) * abs(self._left_support[0] - self._loads_position[sorted_position[i][0]][0])
493
+
494
+ F_x += self._loads['point_load'][sorted_position[i][0]][0] * cos(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180)
495
+ F_y += self._loads['point_load'][sorted_position[i][0]][0] * sin(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180)
496
+
497
+ label = Symbol(sorted_position[i][0]+"_"+sorted_position[i+1][0])
498
+ y2 = self._loads_position[sorted_position[i][0]][1]
499
+ x2 = self._loads_position[sorted_position[i][0]][0]
500
+ y1 = 0
501
+ x1 = 0
502
+
503
+ if i == len(sorted_position)-2:
504
+ x1 = self._right_support[0]
505
+ y1 = self._right_support[1]
506
+
507
+ else:
508
+ x1 = self._loads_position[sorted_position[i+1][0]][0]
509
+ y1 = self._loads_position[sorted_position[i+1][0]][1]
510
+
511
+ angle_with_horizontal = atan((y1 - y2)/(x1 - x2))
512
+
513
+ tension = -(moment_sum_from_left_support)/(abs(self._left_support[1] - self._loads_position[sorted_position[i][0]][1])*cos(angle_with_horizontal) + abs(self._left_support[0] - self._loads_position[sorted_position[i][0]][0])*sin(angle_with_horizontal))
514
+ self._tension[label] = tension
515
+ tension_func.append((tension, x<=x1))
516
+ moment_sum_from_right_support += self._loads['point_load'][sorted_position[i][0]][0] * cos(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180) * abs(self._right_support[1] - self._loads_position[sorted_position[i][0]][1])
517
+ moment_sum_from_right_support += self._loads['point_load'][sorted_position[i][0]][0] * sin(pi * self._loads['point_load'][sorted_position[i][0]][1] / 180) * abs(self._right_support[0] - self._loads_position[sorted_position[i][0]][0])
518
+
519
+ label = Symbol(sorted_position[0][0]+"_"+sorted_position[1][0])
520
+ y2 = self._loads_position[sorted_position[1][0]][1]
521
+ x2 = self._loads_position[sorted_position[1][0]][0]
522
+ x1 = self._left_support[0]
523
+ y1 = self._left_support[1]
524
+
525
+ angle_with_horizontal = -atan((y2 - y1)/(x2 - x1))
526
+ tension = -(moment_sum_from_right_support)/(abs(self._right_support[1] - self._loads_position[sorted_position[1][0]][1])*cos(angle_with_horizontal) + abs(self._right_support[0] - self._loads_position[sorted_position[1][0]][0])*sin(angle_with_horizontal))
527
+ self._tension[label] = tension
528
+
529
+ tension_func.insert(0,(tension, x<=x2))
530
+ self._tension_func = Piecewise(*tension_func)
531
+ angle_with_horizontal = pi/2 - angle_with_horizontal
532
+ label = self._support_labels[0]
533
+ self._reaction_loads[Symbol("R_"+label+"_x")] = -sin(angle_with_horizontal) * tension
534
+ F_x += -sin(angle_with_horizontal) * tension
535
+ self._reaction_loads[Symbol("R_"+label+"_y")] = cos(angle_with_horizontal) * tension
536
+ F_y += cos(angle_with_horizontal) * tension
537
+
538
+ label = self._support_labels[1]
539
+ self._reaction_loads[Symbol("R_"+label+"_x")] = -F_x
540
+ self._reaction_loads[Symbol("R_"+label+"_y")] = -F_y
541
+
542
+ elif len(self._loads['distributed']) != 0 :
543
+
544
+ if len(args) == 0:
545
+ raise ValueError("Provide the lowest point of the cable")
546
+
547
+ lowest_x = sympify(args[0])
548
+ self._lowest_x_global = lowest_x
549
+
550
+ a = Symbol('a', positive=True)
551
+ c = Symbol('c')
552
+ # augmented matrix form of linsolve
553
+
554
+ M = Matrix(
555
+ [[(self._left_support[0]-lowest_x)**2, 1, self._left_support[1]],
556
+ [(self._right_support[0]-lowest_x)**2, 1, self._right_support[1]],
557
+ ])
558
+
559
+ coefficient_solution = list(linsolve(M, (a, c)))
560
+ if len(coefficient_solution) ==0 or coefficient_solution[0][0]== 0:
561
+ raise ValueError("The lowest point is inconsistent with the supports")
562
+
563
+ A = coefficient_solution[0][0]
564
+ C = coefficient_solution[0][1] + coefficient_solution[0][0]*lowest_x**2
565
+ B = -2*coefficient_solution[0][0]*lowest_x
566
+ self._lowest_y_global = coefficient_solution[0][1]
567
+ lowest_y = self._lowest_y_global
568
+
569
+ # y = A*x**2 + B*x + C
570
+ # shifting origin to lowest point
571
+ X = Symbol('X')
572
+ Y = Symbol('Y')
573
+ Y = A*(X + lowest_x)**2 + B*(X + lowest_x) + C - lowest_y
574
+
575
+ temp_list = list(self._loads['distributed'].values())
576
+ applied_force = temp_list[0]
577
+
578
+ horizontal_force_constant = (applied_force * (self._right_support[0] - lowest_x)**2) / (2 * (self._right_support[1] - lowest_y))
579
+
580
+ self._tension.clear()
581
+ tangent_slope_to_curve = diff(Y, X)
582
+ self._tension['distributed'] = horizontal_force_constant / (cos(atan(tangent_slope_to_curve)))
583
+
584
+ label = self._support_labels[0]
585
+ self._reaction_loads[Symbol("R_"+label+"_x")] = self.tension_at(self._left_support[0]) * cos(atan(tangent_slope_to_curve.subs(X, self._left_support[0] - lowest_x)))
586
+ self._reaction_loads[Symbol("R_"+label+"_y")] = self.tension_at(self._left_support[0]) * sin(atan(tangent_slope_to_curve.subs(X, self._left_support[0] - lowest_x)))
587
+
588
+ label = self._support_labels[1]
589
+ self._reaction_loads[Symbol("R_"+label+"_x")] = self.tension_at(self._left_support[0]) * cos(atan(tangent_slope_to_curve.subs(X, self._right_support[0] - lowest_x)))
590
+ self._reaction_loads[Symbol("R_"+label+"_y")] = self.tension_at(self._left_support[0]) * sin(atan(tangent_slope_to_curve.subs(X, self._right_support[0] - lowest_x)))
591
+
592
+ def draw(self):
593
+ """
594
+ This method is used to obtain a plot for the specified cable with its supports,
595
+ shape and loads.
596
+
597
+ Examples
598
+ ========
599
+
600
+ For point loads,
601
+
602
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
603
+ >>> c = Cable(("A", 0, 10), ("B", 10, 10))
604
+ >>> c.apply_load(-1, ('Z', 2, 7.26, 3, 270))
605
+ >>> c.apply_load(-1, ('X', 4, 6, 8, 270))
606
+ >>> c.solve()
607
+ >>> p = c.draw()
608
+ >>> p # doctest: +ELLIPSIS
609
+ Plot object containing:
610
+ [0]: cartesian line: Piecewise((10 - 1.37*x, x <= 2), (8.52 - 0.63*x, x <= 4), (2*x/3 + 10/3, x <= 10)) for x over (0.0, 10.0)
611
+ ...
612
+ >>> p.show()
613
+
614
+ For uniformly distributed loads,
615
+
616
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
617
+ >>> c=Cable(("A", 0, 40),("B", 100, 20))
618
+ >>> c.apply_load(0, ("X", 850))
619
+ >>> c.solve(58.58)
620
+ >>> p = c.draw()
621
+ >>> p # doctest: +ELLIPSIS
622
+ Plot object containing:
623
+ [0]: cartesian line: 0.0116550116550117*(x - 58.58)**2 + 0.00447086247086247 for x over (0.0, 100.0)
624
+ [1]: cartesian line: -7.49552913752915 for x over (0.0, 100.0)
625
+ ...
626
+ >>> p.show()
627
+ """
628
+ x = Symbol("x")
629
+ annotations = []
630
+ support_rectangles = self._draw_supports()
631
+
632
+ xy_min = min(self._left_support[0],self._lowest_y_global)
633
+ xy_max = max(self._right_support[0], max(self._right_support[1],self._left_support[1]))
634
+ max_diff = xy_max - xy_min
635
+ if len(self._loads_position) != 0:
636
+ self._cable_eqn = self._draw_cable(-1)
637
+ annotations += self._draw_loads(-1)
638
+
639
+ elif len(self._loads['distributed']) != 0 :
640
+ self._cable_eqn = self._draw_cable(0)
641
+ annotations += self._draw_loads(0)
642
+
643
+ if not self._cable_eqn:
644
+ raise ValueError("solve method not called and/or values provided for loads and supports not adequate")
645
+
646
+ cab_plot = plot(*self._cable_eqn,(x,self._left_support[0],self._right_support[0]),
647
+ xlim=(xy_min-0.5*max_diff,xy_max+0.5*max_diff),
648
+ ylim=(xy_min-0.5*max_diff,xy_max+0.5*max_diff),
649
+ rectangles=support_rectangles,show= False,annotations=annotations, axis=False)
650
+
651
+ return cab_plot
652
+
653
+ def _draw_supports(self):
654
+ member_rectangles = []
655
+ xy_min = min(self._left_support[0],self._lowest_y_global)
656
+ xy_max = max(self._right_support[0], max(self._right_support[1],self._left_support[1]))
657
+ max_diff = xy_max - xy_min
658
+
659
+ supp_width = 0.075*max_diff
660
+
661
+ member_rectangles.append(
662
+ {
663
+ 'xy': (self._left_support[0]-supp_width,self._left_support[1]),
664
+ 'width': supp_width,
665
+ 'height':supp_width,
666
+ 'color':'brown',
667
+ 'fill': False
668
+ }
669
+ )
670
+
671
+ member_rectangles.append(
672
+ {
673
+ 'xy': (self._right_support[0],self._right_support[1]),
674
+ 'width': supp_width,
675
+ 'height':supp_width,
676
+ 'color':'brown',
677
+ 'fill': False
678
+ }
679
+ )
680
+
681
+ return member_rectangles
682
+
683
+ def _draw_cable(self,order):
684
+ xy_min = min(self._left_support[0],self._lowest_y_global)
685
+ xy_max = max(self._right_support[0], max(self._right_support[1],self._left_support[1]))
686
+ max_diff = xy_max - xy_min
687
+ if order == -1 :
688
+ x,y = symbols('x y')
689
+ line_func = []
690
+ sorted_position = sorted(self._loads_position.items(), key = lambda item : item[1][0])
691
+
692
+ for i in range(len(sorted_position)):
693
+ if(i==0):
694
+ y = ((sorted_position[i][1][1] - self._left_support[1])*(x-self._left_support[0]))/(sorted_position[i][1][0]- self._left_support[0]) + self._left_support[1]
695
+ else:
696
+ y = ((sorted_position[i][1][1] - sorted_position[i-1][1][1] )*(x-sorted_position[i-1][1][0]))/(sorted_position[i][1][0]- sorted_position[i-1][1][0]) + sorted_position[i-1][1][1]
697
+ line_func.append((y,x<=sorted_position[i][1][0]))
698
+
699
+ y = ((sorted_position[len(sorted_position)-1][1][1] - self._right_support[1])*(x-self._right_support[0]))/(sorted_position[i][1][0]- self._right_support[0]) + self._right_support[1]
700
+ line_func.append((y,x<=self._right_support[0]))
701
+ return [Piecewise(*line_func)]
702
+
703
+ elif order == 0:
704
+ x0 = self._lowest_x_global
705
+ diff_force_height = max_diff*0.075
706
+
707
+ a,c,x,y = symbols('a c x y')
708
+ parabola_eqn = a*(x-x0)**2 + c - y
709
+
710
+ points = [(self._left_support[0],self._left_support[1]),(self._right_support[0],self._right_support[1])]
711
+ equations = []
712
+ for px, py in points:
713
+ equations.append(parabola_eqn.subs({x: px, y: py}))
714
+ solution = solve(equations, (a, c))
715
+ parabola_eqn = solution[a]*(x-x0)**2 + solution[c]
716
+ return [parabola_eqn, self._lowest_y_global - diff_force_height]
717
+
718
+ def _draw_loads(self,order):
719
+ xy_min = min(self._left_support[0],self._lowest_y_global)
720
+ xy_max = max(self._right_support[0], max(self._right_support[1],self._left_support[1]))
721
+ max_diff = xy_max - xy_min
722
+ if(order==-1):
723
+ arrow_length = max_diff*0.1
724
+ force_arrows = []
725
+ for key in self._loads['point_load']:
726
+ force_arrows.append(
727
+ {
728
+ 'text': '',
729
+ 'xy':(self._loads_position[key][0]+arrow_length*cos(rad(self._loads['point_load'][key][1])),\
730
+ self._loads_position[key][1] + arrow_length*sin(rad(self._loads['point_load'][key][1]))),
731
+ 'xytext': (self._loads_position[key][0],self._loads_position[key][1]),
732
+ 'arrowprops': {'width': 1, 'headlength':3, 'headwidth':3 , 'facecolor': 'black', }
733
+ }
734
+ )
735
+ mag = self._loads['point_load'][key][0]
736
+ force_arrows.append(
737
+ {
738
+ 'text':f'{mag}N',
739
+ 'xy': (self._loads_position[key][0]+arrow_length*1.6*cos(rad(self._loads['point_load'][key][1])),\
740
+ self._loads_position[key][1] + arrow_length*1.6*sin(rad(self._loads['point_load'][key][1]))),
741
+ }
742
+ )
743
+ return force_arrows
744
+
745
+ elif (order == 0):
746
+ x = symbols('x')
747
+ force_arrows = []
748
+ x_val = [self._left_support[0] + ((self._right_support[0]-self._left_support[0])/10)*i for i in range(1,10)]
749
+ for i in x_val:
750
+ force_arrows.append(
751
+ {
752
+ 'text':'',
753
+ 'xytext':(
754
+ i,
755
+ self._cable_eqn[0].subs(x,i)
756
+ ),
757
+ 'xy':(
758
+ i,
759
+ self._cable_eqn[1].subs(x,i)
760
+ ),
761
+ 'arrowprops':{'width':1, 'headlength':3.5, 'headwidth':3.5, 'facecolor':'black'}
762
+ }
763
+ )
764
+ mag = 0
765
+ for key in self._loads['distributed']:
766
+ mag += self._loads['distributed'][key]
767
+
768
+ force_arrows.append(
769
+ {
770
+ 'text':f'{mag} N/m',
771
+ 'xy':((self._left_support[0]+self._right_support[0])/2,self._lowest_y_global - max_diff*0.15)
772
+ }
773
+ )
774
+ return force_arrows
775
+
776
+ def plot_tension(self):
777
+ """
778
+ Returns the diagram/plot of the tension generated in the cable at various points.
779
+
780
+ Examples
781
+ ========
782
+
783
+ For point loads,
784
+
785
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
786
+ >>> c = Cable(("A", 0, 10), ("B", 10, 10))
787
+ >>> c.apply_load(-1, ('Z', 2, 7.26, 3, 270))
788
+ >>> c.apply_load(-1, ('X', 4, 6, 8, 270))
789
+ >>> c.solve()
790
+ >>> p = c.plot_tension()
791
+ >>> p
792
+ Plot object containing:
793
+ [0]: cartesian line: Piecewise((8.91403453669861, x <= 2), (4.79150773600774, x <= 4), (19*sqrt(13)/10, x <= 10)) for x over (0.0, 10.0)
794
+ >>> p.show()
795
+
796
+ For uniformly distributed loads,
797
+
798
+ >>> from sympy.physics.continuum_mechanics.cable import Cable
799
+ >>> c=Cable(("A", 0, 40),("B", 100, 20))
800
+ >>> c.apply_load(0, ("X", 850))
801
+ >>> c.solve(58.58)
802
+ >>> p = c.plot_tension()
803
+ >>> p
804
+ Plot object containing:
805
+ [0]: cartesian line: 36465.0*sqrt(0.00054335718671383*X**2 + 1) for X over (0.0, 100.0)
806
+ >>> p.show()
807
+
808
+ """
809
+ if len(self._loads_position) != 0:
810
+ x = symbols('x')
811
+ tension_plot = plot(self._tension_func, (x,self._left_support[0],self._right_support[0]), show=False)
812
+ else:
813
+ X = symbols('X')
814
+ tension_plot = plot(self._tension['distributed'], (X,self._left_support[0],self._right_support[0]), show=False)
815
+ return tension_plot
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_arch.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.continuum_mechanics.arch import Arch
2
+ from sympy import Symbol, simplify
3
+
4
+ x = Symbol('x')
5
+ t = Symbol('t')
6
+
7
+ def test_arch_init():
8
+ a = Arch((0,0),(10,0),crown_x=5,crown_y=5)
9
+ assert a.get_loads == {'distributed': {}, 'concentrated': {}}
10
+ assert a.reaction_force == {Symbol('R_A_x'):0, Symbol('R_A_y'):0, Symbol('R_B_x'):0, Symbol('R_B_y'):0}
11
+ assert a.supports == {'left':'hinge', 'right':'hinge'}
12
+ assert a.left_support == (0,0)
13
+ assert a.right_support == (10,0)
14
+ assert a.get_shape_eqn == 5 - ((x-5)**2)/5
15
+
16
+ a = Arch((0,0),(10,1),crown_x=6)
17
+ a.change_support_type(left_support='roller')
18
+ a.add_member(0.5)
19
+ assert a.supports == {'left':'roller', 'right':'hinge'}
20
+ assert simplify(a.get_shape_eqn) == simplify(9/5 - (x - 6)**2/20)
21
+
22
+ def test_arch_support():
23
+ a = Arch((0,0),(40,0),crown_x=20,crown_y=12)
24
+ a.apply_load(-1,'C',8,150,angle=270)
25
+ a.apply_load(0,'D',start=20,end=40,mag=-4)
26
+ a.solve()
27
+ assert abs(a.reaction_force[Symbol("R_A_x")] - 83.33333333333333) < 10e-12
28
+ assert abs(a.reaction_force[Symbol("R_B_y")] - 90.00000000000000) < 10e-12
29
+ assert abs(a.reaction_force[Symbol("R_B_x")] + 83.33333333333333) < 10e-12
30
+ assert abs(a.reaction_force[Symbol("R_A_y")] - 140.00000000000000) < 10e-12
31
+
32
+ def test_arch_member():
33
+ a = Arch((0,0),(40,0),crown_x=20,crown_y=15)
34
+ a.change_support_type(right_support='roller')
35
+ a.add_member(0)
36
+ a.apply_load(-1,'D',start=12,mag=3,angle=270)
37
+ a.apply_load(-1,'E',start=6,mag=4,angle=270)
38
+ a.apply_load(-1,'C',start=30,mag=5,angle=270)
39
+ a.solve()
40
+ assert a.reaction_force[Symbol("R_A_x")] == 0
41
+ assert abs(a.reaction_force[Symbol("R_A_y")] - 6.750000000000000) < 10e-12
42
+ assert a.reaction_force[Symbol("R_B_x")] == 0
43
+ assert abs(a.reaction_force[Symbol("R_B_y")] - 5.250000000000000) < 10e-12
44
+
45
+ def test_symbol_magnitude():
46
+ a = Arch((0,0),(16,0),crown_x=8,crown_y=5)
47
+ a.apply_load(0,'C',start=3,end=5,mag=t)
48
+ a.solve()
49
+ assert a.reaction_force[Symbol("R_A_x")] == -(4*t)/5
50
+ assert a.reaction_force[Symbol("R_A_y")] == -(3*t)/2
51
+ assert a.reaction_force[Symbol("R_B_x")] == (4*t)/5
52
+ assert a.reaction_force[Symbol("R_B_y")] == -t/2
53
+ assert a.bending_moment_at(4) == -5*t/2
54
+
55
+ def test_forces():
56
+ a = Arch((0,0),(40,0),crown_x=20,crown_y=12)
57
+ a.apply_load(-1,'C',8,150,angle=270)
58
+ a.apply_load(0,'D',start=20,end=40,mag=-4)
59
+ a.solve()
60
+ assert abs(a.axial_force_at(7.999999999999999)-149.430523405935) < 1e-12
61
+ assert abs(a.shear_force_at(7.999999999999999)-64.9227473161196) < 1e-12
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py ADDED
@@ -0,0 +1,1118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ b.bc_bending_moment = [(0, 5)]
53
+ b.bc_shear_force = [(2, 1)]
54
+ assert b.boundary_conditions == {'deflection': [(0, 2)], 'slope': [(0, 1)],
55
+ 'bending_moment': [(0, 5)], 'shear_force': [(2, 1)]}
56
+
57
+ # Test for shear force boundary condition method
58
+ b.bc_shear_force.extend([(1, 1), (2, 3)])
59
+ sf_bcs = b.bc_shear_force
60
+ assert sf_bcs == [(2, 1), (1, 1), (2, 3)]
61
+
62
+ # Test for slope boundary condition method
63
+ b.bc_bending_moment.extend([(1, 3), (5, 3)])
64
+ bm_bcs = b.bc_bending_moment
65
+ assert bm_bcs == [(0, 5), (1, 3), (5, 3)]
66
+
67
+ # Test for slope boundary condition method
68
+ b.bc_slope.extend([(4, 3), (5, 0)])
69
+ s_bcs = b.bc_slope
70
+ assert s_bcs == [(0, 1), (4, 3), (5, 0)]
71
+
72
+ # Test for deflection boundary condition method
73
+ b.bc_deflection.extend([(4, 3), (5, 0)])
74
+ d_bcs = b.bc_deflection
75
+ assert d_bcs == [(0, 2), (4, 3), (5, 0)]
76
+
77
+ # Test for updated boundary conditions
78
+ bcs_new = b.boundary_conditions
79
+ assert bcs_new == {
80
+ 'deflection': [(0, 2), (4, 3), (5, 0)],
81
+ 'slope': [(0, 1), (4, 3), (5, 0)],
82
+ 'bending_moment': [(0, 5), (1, 3), (5, 3)],
83
+ 'shear_force': [(2, 1), (1, 1), (2, 3)]}
84
+
85
+ b1 = Beam(30, E, I)
86
+ b1.apply_load(-8, 0, -1)
87
+ b1.apply_load(R1, 10, -1)
88
+ b1.apply_load(R2, 30, -1)
89
+ b1.apply_load(120, 30, -2)
90
+ b1.bc_deflection = [(10, 0), (30, 0)]
91
+ b1.solve_for_reaction_loads(R1, R2)
92
+
93
+ # Test for finding reaction forces
94
+ p = b1.reaction_loads
95
+ q = {R1: 6, R2: 2}
96
+ assert p == q
97
+
98
+ # Test for load distribution function.
99
+ p = b1.load
100
+ q = -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) \
101
+ + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
102
+ assert p == q
103
+
104
+ # Test for shear force distribution function
105
+ p = b1.shear_force()
106
+ q = 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
107
+ - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
108
+ assert p == q
109
+
110
+ # Test for shear stress distribution function
111
+ p = b1.shear_stress()
112
+ q = (8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
113
+ - 120*SingularityFunction(x, 30, -1) \
114
+ - 2*SingularityFunction(x, 30, 0))/A
115
+ assert p==q
116
+
117
+ # Test for bending moment distribution function
118
+ p = b1.bending_moment()
119
+ q = 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) \
120
+ - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
121
+ assert p == q
122
+
123
+ # Test for slope distribution function
124
+ p = b1.slope()
125
+ q = -4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) \
126
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) \
127
+ + Rational(4000, 3)
128
+ assert p == q/(E*I)
129
+
130
+ # Test for deflection distribution function
131
+ p = b1.deflection()
132
+ q = x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 \
133
+ + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) \
134
+ + SingularityFunction(x, 30, 3)/3 - 12000
135
+ assert p == q/(E*I)
136
+
137
+ # Test using symbols
138
+ l = Symbol('l')
139
+ w0 = Symbol('w0')
140
+ w2 = Symbol('w2')
141
+ a1 = Symbol('a1')
142
+ c = Symbol('c')
143
+ c1 = Symbol('c1')
144
+ d = Symbol('d')
145
+ e = Symbol('e')
146
+ f = Symbol('f')
147
+
148
+ b2 = Beam(l, E, I)
149
+
150
+ b2.apply_load(w0, a1, 1)
151
+ b2.apply_load(w2, c1, -1)
152
+
153
+ b2.bc_deflection = [(c, d)]
154
+ b2.bc_slope = [(e, f)]
155
+
156
+ # Test for load distribution function.
157
+ p = b2.load
158
+ q = w0*SingularityFunction(x, a1, 1) + w2*SingularityFunction(x, c1, -1)
159
+ assert p == q
160
+
161
+ # Test for shear force distribution function
162
+ p = b2.shear_force()
163
+ q = -w0*SingularityFunction(x, a1, 2)/2 \
164
+ - w2*SingularityFunction(x, c1, 0)
165
+ assert p == q
166
+
167
+ # Test for shear stress distribution function
168
+ p = b2.shear_stress()
169
+ q = (-w0*SingularityFunction(x, a1, 2)/2 \
170
+ - w2*SingularityFunction(x, c1, 0))/A
171
+ assert p == q
172
+
173
+ # Test for bending moment distribution function
174
+ p = b2.bending_moment()
175
+ q = -w0*SingularityFunction(x, a1, 3)/6 - w2*SingularityFunction(x, c1, 1)
176
+ assert p == q
177
+
178
+ # Test for slope distribution function
179
+ p = b2.slope()
180
+ 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)
181
+ assert expand(p) == expand(q)
182
+
183
+ # Test for deflection distribution function
184
+ p = b2.deflection()
185
+ q = x*(E*I*f - w0*SingularityFunction(e, a1, 4)/24 \
186
+ - w2*SingularityFunction(e, c1, 2)/2)/(E*I) \
187
+ + (w0*SingularityFunction(x, a1, 5)/120 \
188
+ + w2*SingularityFunction(x, c1, 3)/6)/(E*I) \
189
+ + (E*I*(-c*f + d) + c*w0*SingularityFunction(e, a1, 4)/24 \
190
+ + c*w2*SingularityFunction(e, c1, 2)/2 \
191
+ - w0*SingularityFunction(c, a1, 5)/120 \
192
+ - w2*SingularityFunction(c, c1, 3)/6)/(E*I)
193
+ assert simplify(p - q) == 0
194
+
195
+ b3 = Beam(9, E, I, 2)
196
+ b3.apply_load(value=-2, start=2, order=2, end=3)
197
+ b3.bc_slope.append((0, 2))
198
+ C3 = symbols('C3')
199
+ C4 = symbols('C4')
200
+
201
+ p = b3.load
202
+ q = -2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) \
203
+ + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
204
+ assert p == q
205
+
206
+ p = b3.shear_force()
207
+ q = 2*SingularityFunction(x, 2, 3)/3 - 2*SingularityFunction(x, 3, 1) \
208
+ - 2*SingularityFunction(x, 3, 2) - 2*SingularityFunction(x, 3, 3)/3
209
+ assert p == q
210
+
211
+ p = b3.shear_stress()
212
+ q = SingularityFunction(x, 2, 3)/3 - 1*SingularityFunction(x, 3, 1) \
213
+ - 1*SingularityFunction(x, 3, 2) - 1*SingularityFunction(x, 3, 3)/3
214
+ assert p == q
215
+
216
+ p = b3.slope()
217
+ q = 2 - (SingularityFunction(x, 2, 5)/30 - SingularityFunction(x, 3, 3)/3 \
218
+ - SingularityFunction(x, 3, 4)/6 - SingularityFunction(x, 3, 5)/30)/(E*I)
219
+ assert p == q
220
+
221
+ p = b3.deflection()
222
+ q = 2*x - (SingularityFunction(x, 2, 6)/180 \
223
+ - SingularityFunction(x, 3, 4)/12 - SingularityFunction(x, 3, 5)/30 \
224
+ - SingularityFunction(x, 3, 6)/180)/(E*I)
225
+ assert p == q + C4
226
+
227
+ b4 = Beam(4, E, I, 3)
228
+ b4.apply_load(-3, 0, 0, end=3)
229
+
230
+ p = b4.load
231
+ q = -3*SingularityFunction(x, 0, 0) + 3*SingularityFunction(x, 3, 0)
232
+ assert p == q
233
+
234
+ p = b4.shear_force()
235
+ q = 3*SingularityFunction(x, 0, 1) \
236
+ - 3*SingularityFunction(x, 3, 1)
237
+ assert p == q
238
+
239
+ p = b4.shear_stress()
240
+ q = SingularityFunction(x, 0, 1) - SingularityFunction(x, 3, 1)
241
+ assert p == q
242
+
243
+ p = b4.slope()
244
+ q = -3*SingularityFunction(x, 0, 3)/6 + 3*SingularityFunction(x, 3, 3)/6
245
+ assert p == q/(E*I) + C3
246
+
247
+ p = b4.deflection()
248
+ q = -3*SingularityFunction(x, 0, 4)/24 + 3*SingularityFunction(x, 3, 4)/24
249
+ assert p == q/(E*I) + C3*x + C4
250
+
251
+ # can't use end with point loads
252
+ raises(ValueError, lambda: b4.apply_load(-3, 0, -1, end=3))
253
+ with raises(TypeError):
254
+ b4.variable = 1
255
+
256
+
257
+ def test_insufficient_bconditions():
258
+ # Test cases when required number of boundary conditions
259
+ # are not provided to solve the integration constants.
260
+ L = symbols('L', positive=True)
261
+ E, I, P, a3, a4 = symbols('E I P a3 a4')
262
+
263
+ b = Beam(L, E, I, base_char='a')
264
+ b.apply_load(R2, L, -1)
265
+ b.apply_load(R1, 0, -1)
266
+ b.apply_load(-P, L/2, -1)
267
+ b.solve_for_reaction_loads(R1, R2)
268
+
269
+ p = b.slope()
270
+ q = P*SingularityFunction(x, 0, 2)/4 - P*SingularityFunction(x, L/2, 2)/2 + P*SingularityFunction(x, L, 2)/4
271
+ assert p == q/(E*I) + a3
272
+
273
+ p = b.deflection()
274
+ q = P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
275
+ assert p == q/(E*I) + a3*x + a4
276
+
277
+ b.bc_deflection = [(0, 0)]
278
+ p = b.deflection()
279
+ q = a3*x + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
280
+ assert p == q/(E*I)
281
+
282
+ b.bc_deflection = [(0, 0), (L, 0)]
283
+ p = b.deflection()
284
+ 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
285
+ assert p == q/(E*I)
286
+
287
+
288
+ def test_statically_indeterminate():
289
+ E = Symbol('E')
290
+ I = Symbol('I')
291
+ M1, M2 = symbols('M1, M2')
292
+ F = Symbol('F')
293
+ l = Symbol('l', positive=True)
294
+
295
+ b5 = Beam(l, E, I)
296
+ b5.bc_deflection = [(0, 0),(l, 0)]
297
+ b5.bc_slope = [(0, 0),(l, 0)]
298
+
299
+ b5.apply_load(R1, 0, -1)
300
+ b5.apply_load(M1, 0, -2)
301
+ b5.apply_load(R2, l, -1)
302
+ b5.apply_load(M2, l, -2)
303
+ b5.apply_load(-F, l/2, -1)
304
+
305
+ b5.solve_for_reaction_loads(R1, R2, M1, M2)
306
+ p = b5.reaction_loads
307
+ q = {R1: F/2, R2: F/2, M1: -F*l/8, M2: F*l/8}
308
+ assert p == q
309
+
310
+
311
+ def test_beam_units():
312
+ E = Symbol('E')
313
+ I = Symbol('I')
314
+ R1, R2 = symbols('R1, R2')
315
+
316
+ kN = kilo*newton
317
+ gN = giga*newton
318
+
319
+ b = Beam(8*meter, 200*gN/meter**2, 400*1000000*(milli*meter)**4)
320
+ b.apply_load(5*kN, 2*meter, -1)
321
+ b.apply_load(R1, 0*meter, -1)
322
+ b.apply_load(R2, 8*meter, -1)
323
+ b.apply_load(10*kN/meter, 4*meter, 0, end=8*meter)
324
+ b.bc_deflection = [(0*meter, 0*meter), (8*meter, 0*meter)]
325
+ b.solve_for_reaction_loads(R1, R2)
326
+ assert b.reaction_loads == {R1: -13750*newton, R2: -31250*newton}
327
+
328
+ b = Beam(3*meter, E*newton/meter**2, I*meter**4)
329
+ b.apply_load(8*kN, 1*meter, -1)
330
+ b.apply_load(R1, 0*meter, -1)
331
+ b.apply_load(R2, 3*meter, -1)
332
+ b.apply_load(12*kN*meter, 2*meter, -2)
333
+ b.bc_deflection = [(0*meter, 0*meter), (3*meter, 0*meter)]
334
+ b.solve_for_reaction_loads(R1, R2)
335
+ assert b.reaction_loads == {R1: newton*Rational(-28000, 3), R2: newton*Rational(4000, 3)}
336
+ assert b.deflection().subs(x, 1*meter) == 62000*meter/(9*E*I)
337
+
338
+
339
+ def test_variable_moment():
340
+ E = Symbol('E')
341
+ I = Symbol('I')
342
+
343
+ b = Beam(4, E, 2*(4 - x))
344
+ b.apply_load(20, 4, -1)
345
+ R, M = symbols('R, M')
346
+ b.apply_load(R, 0, -1)
347
+ b.apply_load(M, 0, -2)
348
+ b.bc_deflection = [(0, 0)]
349
+ b.bc_slope = [(0, 0)]
350
+ b.solve_for_reaction_loads(R, M)
351
+ assert b.slope().expand() == ((10*x*SingularityFunction(x, 0, 0)
352
+ - 10*(x - 4)*SingularityFunction(x, 4, 0))/E).expand()
353
+ assert b.deflection().expand() == ((5*x**2*SingularityFunction(x, 0, 0)
354
+ - 10*Piecewise((0, Abs(x)/4 < 1), (x**2*meijerg(((-1, 1), ()), ((), (-2, 0)), x/4), True))
355
+ + 40*SingularityFunction(x, 4, 1))/E).expand()
356
+
357
+ b = Beam(4, E - x, I)
358
+ b.apply_load(20, 4, -1)
359
+ R, M = symbols('R, M')
360
+ b.apply_load(R, 0, -1)
361
+ b.apply_load(M, 0, -2)
362
+ b.bc_deflection = [(0, 0)]
363
+ b.bc_slope = [(0, 0)]
364
+ b.solve_for_reaction_loads(R, M)
365
+ assert b.slope().expand() == ((-80*(-log(-E) + log(-E + x))*SingularityFunction(x, 0, 0)
366
+ + 80*(-log(-E + 4) + log(-E + x))*SingularityFunction(x, 4, 0) + 20*(-E*log(-E)
367
+ + E*log(-E + x) + x)*SingularityFunction(x, 0, 0) - 20*(-E*log(-E + 4) + E*log(-E + x)
368
+ + x - 4)*SingularityFunction(x, 4, 0))/I).expand()
369
+
370
+
371
+ def test_composite_beam():
372
+ E = Symbol('E')
373
+ I = Symbol('I')
374
+ b1 = Beam(2, E, 1.5*I)
375
+ b2 = Beam(2, E, I)
376
+ b = b1.join(b2, "fixed")
377
+ b.apply_load(-20, 0, -1)
378
+ b.apply_load(80, 0, -2)
379
+ b.apply_load(20, 4, -1)
380
+ b.bc_slope = [(0, 0)]
381
+ b.bc_deflection = [(0, 0)]
382
+ assert b.length == 4
383
+ assert b.second_moment == Piecewise((1.5*I, x <= 2), (I, x <= 4))
384
+ assert b.slope().subs(x, 4) == 120.0/(E*I)
385
+ assert b.slope().subs(x, 2) == 80.0/(E*I)
386
+ assert int(b.deflection().subs(x, 4).args[0]) == -302 # Coefficient of 1/(E*I)
387
+
388
+ l = symbols('l', positive=True)
389
+ R1, M1, R2, R3, P = symbols('R1 M1 R2 R3 P')
390
+ b1 = Beam(2*l, E, I)
391
+ b2 = Beam(2*l, E, I)
392
+ b = b1.join(b2,"hinge")
393
+ b.apply_load(M1, 0, -2)
394
+ b.apply_load(R1, 0, -1)
395
+ b.apply_load(R2, l, -1)
396
+ b.apply_load(R3, 4*l, -1)
397
+ b.apply_load(P, 3*l, -1)
398
+ b.bc_slope = [(0, 0)]
399
+ b.bc_deflection = [(0, 0), (l, 0), (4*l, 0)]
400
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
401
+ assert b.reaction_loads == {R3: -P/2, R2: P*Rational(-5, 4), M1: -P*l/4, R1: P*Rational(3, 4)}
402
+ assert b.slope().subs(x, 3*l) == -7*P*l**2/(48*E*I)
403
+ assert b.deflection().subs(x, 2*l) == 7*P*l**3/(24*E*I)
404
+ assert b.deflection().subs(x, 3*l) == 5*P*l**3/(16*E*I)
405
+
406
+ # When beams having same second moment are joined.
407
+ b1 = Beam(2, 500, 10)
408
+ b2 = Beam(2, 500, 10)
409
+ b = b1.join(b2, "fixed")
410
+ b.apply_load(M1, 0, -2)
411
+ b.apply_load(R1, 0, -1)
412
+ b.apply_load(R2, 1, -1)
413
+ b.apply_load(R3, 4, -1)
414
+ b.apply_load(10, 3, -1)
415
+ b.bc_slope = [(0, 0)]
416
+ b.bc_deflection = [(0, 0), (1, 0), (4, 0)]
417
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
418
+ assert b.slope() == -2*SingularityFunction(x, 0, 1)/5625 + SingularityFunction(x, 0, 2)/1875\
419
+ - 133*SingularityFunction(x, 1, 2)/135000 + SingularityFunction(x, 3, 2)/1000\
420
+ - 37*SingularityFunction(x, 4, 2)/67500
421
+ assert b.deflection() == -SingularityFunction(x, 0, 2)/5625 + SingularityFunction(x, 0, 3)/5625\
422
+ - 133*SingularityFunction(x, 1, 3)/405000 + SingularityFunction(x, 3, 3)/3000\
423
+ - 37*SingularityFunction(x, 4, 3)/202500
424
+
425
+
426
+ def test_point_cflexure():
427
+ E = Symbol('E')
428
+ I = Symbol('I')
429
+ b = Beam(10, E, I)
430
+ b.apply_load(-4, 0, -1)
431
+ b.apply_load(-46, 6, -1)
432
+ b.apply_load(10, 2, -1)
433
+ b.apply_load(20, 4, -1)
434
+ b.apply_load(3, 6, 0)
435
+ assert b.point_cflexure() == [Rational(10, 3)]
436
+
437
+ E = Symbol('E')
438
+ I = Symbol('I')
439
+ b = Beam(15, E, I)
440
+ r0 = b.apply_support(0, type='pin')
441
+ r10 = b.apply_support(10, type='pin')
442
+ r15, m15 = b.apply_support(15, type='fixed')
443
+ b.apply_rotation_hinge(12)
444
+ b.apply_load(-10, 5, -1)
445
+ b.apply_load(-5, 10, 0, 15)
446
+ b.solve_for_reaction_loads(r0, r10, r15, m15)
447
+ assert b.point_cflexure() == [Rational(1200, 163), 12, Rational(163, 12)]
448
+
449
+ E = Symbol('E')
450
+ I = Symbol('I')
451
+ b = Beam(15, E, I)
452
+ r0 = b.apply_support(0, type='pin')
453
+ r10 = b.apply_support(10, type='pin')
454
+ r15, m15 = b.apply_support(15, type='fixed')
455
+ b.apply_rotation_hinge(5)
456
+ b.apply_rotation_hinge(12)
457
+ b.apply_load(-10, 5, -1)
458
+ b.apply_load(-5, 10, 0, 15)
459
+ b.solve_for_reaction_loads(r0, r10, r15, m15)
460
+ with raises(NotImplementedError):
461
+ b.point_cflexure()
462
+
463
+ def test_remove_load():
464
+ E = Symbol('E')
465
+ I = Symbol('I')
466
+ b = Beam(4, E, I)
467
+
468
+ try:
469
+ b.remove_load(2, 1, -1)
470
+ # As no load is applied on beam, ValueError should be returned.
471
+ except ValueError:
472
+ assert True
473
+ else:
474
+ assert False
475
+
476
+ b.apply_load(-3, 0, -2)
477
+ b.apply_load(4, 2, -1)
478
+ b.apply_load(-2, 2, 2, end = 3)
479
+ b.remove_load(-2, 2, 2, end = 3)
480
+ assert b.load == -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
481
+ assert b.applied_loads == [(-3, 0, -2, None), (4, 2, -1, None)]
482
+
483
+ try:
484
+ b.remove_load(1, 2, -1)
485
+ # As load of this magnitude was never applied at
486
+ # this position, method should return a ValueError.
487
+ except ValueError:
488
+ assert True
489
+ else:
490
+ assert False
491
+
492
+ b.remove_load(-3, 0, -2)
493
+ b.remove_load(4, 2, -1)
494
+ assert b.load == 0
495
+ assert b.applied_loads == []
496
+
497
+
498
+ def test_apply_support():
499
+ E = Symbol('E')
500
+ I = Symbol('I')
501
+
502
+ b = Beam(4, E, I)
503
+ b.apply_support(0, "cantilever")
504
+ b.apply_load(20, 4, -1)
505
+ M_0, R_0 = symbols('M_0, R_0')
506
+ b.solve_for_reaction_loads(R_0, M_0)
507
+ assert simplify(b.slope()) == simplify((80*SingularityFunction(x, 0, 1) - 10*SingularityFunction(x, 0, 2)
508
+ + 10*SingularityFunction(x, 4, 2))/(E*I))
509
+ assert simplify(b.deflection()) == simplify((40*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 0, 3)/3
510
+ + 10*SingularityFunction(x, 4, 3)/3)/(E*I))
511
+
512
+ b = Beam(30, E, I)
513
+ p0 = b.apply_support(10, "pin")
514
+ p1 = b.apply_support(30, "roller")
515
+ b.apply_load(-8, 0, -1)
516
+ b.apply_load(120, 30, -2)
517
+ b.solve_for_reaction_loads(p0, p1)
518
+ assert b.slope() == (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
519
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3))/(E*I)
520
+ assert b.deflection() == (x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
521
+ + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
522
+ R_10 = Symbol('R_10')
523
+ R_30 = Symbol('R_30')
524
+ assert p0 == R_10
525
+ assert b.reaction_loads == {R_10: 6, R_30: 2}
526
+ assert b.reaction_loads[p0] == 6
527
+
528
+ b = Beam(8, E, I)
529
+ p0, m0 = b.apply_support(0, "fixed")
530
+ p1 = b.apply_support(8, "roller")
531
+ b.apply_load(-5, 0, 0, 8)
532
+ b.solve_for_reaction_loads(p0, m0, p1)
533
+ R_0 = Symbol('R_0')
534
+ M_0 = Symbol('M_0')
535
+ R_8 = Symbol('R_8')
536
+ assert p0 == R_0
537
+ assert m0 == M_0
538
+ assert p1 == R_8
539
+ assert b.reaction_loads == {R_0: 25, M_0: -40, R_8: 15}
540
+ assert b.reaction_loads[m0] == -40
541
+
542
+ P = Symbol('P', positive=True)
543
+ L = Symbol('L', positive=True)
544
+ b = Beam(L, E, I)
545
+ b.apply_support(0, type='fixed')
546
+ b.apply_support(L, type='fixed')
547
+ b.apply_load(-P, L/2, -1)
548
+ R_0, R_L, M_0, M_L = symbols('R_0, R_L, M_0, M_L')
549
+ b.solve_for_reaction_loads(R_0, R_L, M_0, M_L)
550
+ assert b.reaction_loads == {R_0: P/2, R_L: P/2, M_0: -L*P/8, M_L: L*P/8}
551
+
552
+ def test_apply_rotation_hinge():
553
+ b = Beam(15, 20, 20)
554
+ r0, m0 = b.apply_support(0, type='fixed')
555
+ r10 = b.apply_support(10, type='pin')
556
+ r15 = b.apply_support(15, type='pin')
557
+ p7 = b.apply_rotation_hinge(7)
558
+ p12 = b.apply_rotation_hinge(12)
559
+ b.apply_load(-10, 7, -1)
560
+ b.apply_load(-2, 10, 0, 15)
561
+ b.solve_for_reaction_loads(r0, m0, r10, r15)
562
+ R_0, M_0, R_10, R_15, P_7, P_12 = symbols('R_0, M_0, R_10, R_15, P_7, P_12')
563
+ expected_reactions = {R_0: 20/3, M_0: -140/3, R_10: 31/3, R_15: 3}
564
+ expected_rotations = {P_7: 2281/2160, P_12: -5137/5184}
565
+ reaction_symbols = [r0, m0, r10, r15]
566
+ rotation_symbols = [p7, p12]
567
+ tolerance = 1e-6
568
+ assert all(abs(b.reaction_loads[r] - expected_reactions[r]) < tolerance for r in reaction_symbols)
569
+ assert all(abs(b.rotation_jumps[r] - expected_rotations[r]) < tolerance for r in rotation_symbols)
570
+ expected_bending_moment = (140 * SingularityFunction(x, 0, 0) / 3 - 20 * SingularityFunction(x, 0, 1) / 3
571
+ - 11405 * SingularityFunction(x, 7, -1) / 27 + 10 * SingularityFunction(x, 7, 1)
572
+ - 31 * SingularityFunction(x, 10, 1) / 3 + SingularityFunction(x, 10, 2)
573
+ + 128425 * SingularityFunction(x, 12, -1) / 324 - 3 * SingularityFunction(x, 15, 1)
574
+ - SingularityFunction(x, 15, 2))
575
+ assert b.bending_moment().expand() == expected_bending_moment.expand()
576
+ expected_slope = (-7*SingularityFunction(x, 0, 1)/60 + SingularityFunction(x, 0, 2)/120
577
+ + 2281*SingularityFunction(x, 7, 0)/2160 - SingularityFunction(x, 7, 2)/80
578
+ + 31*SingularityFunction(x, 10, 2)/2400 - SingularityFunction(x, 10, 3)/1200
579
+ - 5137*SingularityFunction(x, 12, 0)/5184 + 3*SingularityFunction(x, 15, 2)/800
580
+ + SingularityFunction(x, 15, 3)/1200)
581
+ assert b.slope().expand() == expected_slope.expand()
582
+ expected_deflection = (-7 * SingularityFunction(x, 0, 2) / 120 + SingularityFunction(x, 0, 3) / 360
583
+ + 2281 * SingularityFunction(x, 7, 1) / 2160 - SingularityFunction(x, 7, 3) / 240
584
+ + 31 * SingularityFunction(x, 10, 3) / 7200 - SingularityFunction(x, 10, 4) / 4800
585
+ - 5137 * SingularityFunction(x, 12, 1) / 5184 + SingularityFunction(x, 15, 3) / 800
586
+ + SingularityFunction(x, 15, 4) / 4800)
587
+ assert b.deflection().expand() == expected_deflection.expand()
588
+
589
+ E = Symbol('E')
590
+ I = Symbol('I')
591
+ F = Symbol('F')
592
+ b = Beam(10, E, I)
593
+ r0, m0 = b.apply_support(0, type="fixed")
594
+ r10 = b.apply_support(10, type="pin")
595
+ b.apply_rotation_hinge(6)
596
+ b.apply_load(F, 8, -1)
597
+ b.solve_for_reaction_loads(r0, m0, r10)
598
+ assert b.reaction_loads == {R_0: -F/2, M_0: 3*F, R_10: -F/2}
599
+ assert (b.bending_moment() == -3*F*SingularityFunction(x, 0, 0) + F*SingularityFunction(x, 0, 1)/2
600
+ + 17*F*SingularityFunction(x, 6, -1) - F*SingularityFunction(x, 8, 1)
601
+ + F*SingularityFunction(x, 10, 1)/2)
602
+ expected_deflection = -(-3*F*SingularityFunction(x, 0, 2)/2 + F*SingularityFunction(x, 0, 3)/12
603
+ + 17*F*SingularityFunction(x, 6, 1) - F*SingularityFunction(x, 8, 3)/6
604
+ + F*SingularityFunction(x, 10, 3)/12)/(E*I)
605
+ assert b.deflection().expand() == expected_deflection.expand()
606
+
607
+ E = Symbol('E')
608
+ I = Symbol('I')
609
+ F = Symbol('F')
610
+ l1 = Symbol('l1', positive=True)
611
+ l2 = Symbol('l2', positive=True)
612
+ l3 = Symbol('l3', positive=True)
613
+ L = l1 + l2 + l3
614
+ b = Beam(L, E, I)
615
+ r0, m0 = b.apply_support(0, type="fixed")
616
+ r1 = b.apply_support(L, type="pin")
617
+ b.apply_rotation_hinge(l1)
618
+ b.apply_load(F, l1+l2, -1)
619
+ b.solve_for_reaction_loads(r0, m0, r1)
620
+ assert b.reaction_loads[r0] == -F*l3/(l2 + l3)
621
+ assert b.reaction_loads[m0] == F*l1*l3/(l2 + l3)
622
+ assert b.reaction_loads[r1] == -F*l2/(l2 + l3)
623
+ expected_bending_moment = (-F*l1*l3*SingularityFunction(x, 0, 0)/(l2 + l3)
624
+ + F*l2*SingularityFunction(x, l1 + l2 + l3, 1)/(l2 + l3)
625
+ + F*l3*SingularityFunction(x, 0, 1)/(l2 + l3) - F*SingularityFunction(x, l1 + l2, 1)
626
+ - (-2*F*l1**3*l3 - 3*F*l1**2*l2*l3 - 3*F*l1**2*l3**2 + F*l2**3*l3 + 3*F*l2**2*l3**2 + 2*F*l2*l3**3)
627
+ *SingularityFunction(x, l1, -1)/(6*l2**2 + 12*l2*l3 + 6*l3**2))
628
+ assert simplify(b.bending_moment().expand()) == simplify(expected_bending_moment.expand())
629
+
630
+ def test_apply_sliding_hinge():
631
+ b = Beam(13, 20, 20)
632
+ r0, m0 = b.apply_support(0, type="fixed")
633
+ w8 = b.apply_sliding_hinge(8)
634
+ r13 = b.apply_support(13, type="pin")
635
+ b.apply_load(-10, 5, -1)
636
+ b.solve_for_reaction_loads(r0, m0, r13)
637
+ R_0, M_0, R_13, W_8 = symbols('R_0, M_0, R_13 W_8')
638
+ assert b.reaction_loads == {R_0: 10, M_0: -50, R_13: 0}
639
+ tolerance = 1e-6
640
+ assert abs(b.deflection_jumps[w8] - 85/24) < tolerance
641
+ assert (b.bending_moment() == 50*SingularityFunction(x, 0, 0) - 10*SingularityFunction(x, 0, 1)
642
+ + 10*SingularityFunction(x, 5, 1) - 4250*SingularityFunction(x, 8, -2)/3)
643
+ assert (b.deflection() == -SingularityFunction(x, 0, 2)/16 + SingularityFunction(x, 0, 3)/240
644
+ - SingularityFunction(x, 5, 3)/240 + 85*SingularityFunction(x, 8, 0)/24)
645
+
646
+ E = Symbol('E')
647
+ I = Symbol('I')
648
+ I2 = Symbol('I2')
649
+ b1 = Beam(5, E, I)
650
+ b2 = Beam(8, E, I2)
651
+ b = b1.join(b2)
652
+ r0, m0 = b.apply_support(0, type="fixed")
653
+ b.apply_sliding_hinge(8)
654
+ r13 = b.apply_support(13, type="pin")
655
+ b.apply_load(-10, 5, -1)
656
+ b.solve_for_reaction_loads(r0, m0, r13)
657
+ W_8 = Symbol('W_8')
658
+ assert b.deflection_jumps == {W_8: 4250/(3*E*I2)}
659
+
660
+ E = Symbol('E')
661
+ I = Symbol('I')
662
+ q = Symbol('q')
663
+ l1 = Symbol('l1', positive=True)
664
+ l2 = Symbol('l2', positive=True)
665
+ l3 = Symbol('l3', positive=True)
666
+ L = l1 + l2 + l3
667
+ b = Beam(L, E, I)
668
+ r0 = b.apply_support(0, type="pin")
669
+ r3 = b.apply_support(l1, type="pin")
670
+ b.apply_sliding_hinge(l1 + l2)
671
+ r10 = b.apply_support(L, type="pin")
672
+ b.apply_load(q, 0, 0, l1)
673
+ b.solve_for_reaction_loads(r0, r3, r10)
674
+ assert (b.bending_moment() == l1*q*SingularityFunction(x, 0, 1)/2 + l1*q*SingularityFunction(x, l1, 1)/2
675
+ - q*SingularityFunction(x, 0, 2)/2 + q*SingularityFunction(x, l1, 2)/2
676
+ + (-l1**3*l2*q/24 - l1**3*l3*q/24)*SingularityFunction(x, l1 + l2, -2))
677
+ assert b.deflection() ==(l1**3*q*x/24 - l1*q*SingularityFunction(x, 0, 3)/12
678
+ - l1*q*SingularityFunction(x, l1, 3)/12 + q*SingularityFunction(x, 0, 4)/24
679
+ - q*SingularityFunction(x, l1, 4)/24
680
+ + (l1**3*l2*q/24 + l1**3*l3*q/24)*SingularityFunction(x, l1 + l2, 0))/(E*I)
681
+
682
+ def test_max_shear_force():
683
+ E = Symbol('E')
684
+ I = Symbol('I')
685
+
686
+ b = Beam(3, E, I)
687
+ R, M = symbols('R, M')
688
+ b.apply_load(R, 0, -1)
689
+ b.apply_load(M, 0, -2)
690
+ b.apply_load(2, 3, -1)
691
+ b.apply_load(4, 2, -1)
692
+ b.apply_load(2, 2, 0, end=3)
693
+ b.solve_for_reaction_loads(R, M)
694
+ assert b.max_shear_force() == (Interval(0, 2), 8)
695
+
696
+ l = symbols('l', positive=True)
697
+ P = Symbol('P')
698
+ b = Beam(l, E, I)
699
+ R1, R2 = symbols('R1, R2')
700
+ b.apply_load(R1, 0, -1)
701
+ b.apply_load(R2, l, -1)
702
+ b.apply_load(P, 0, 0, end=l)
703
+ b.solve_for_reaction_loads(R1, R2)
704
+ max_shear = b.max_shear_force()
705
+ assert max_shear[0] == 0
706
+ assert simplify(max_shear[1] - (l*Abs(P)/2)) == 0
707
+
708
+
709
+ def test_max_bmoment():
710
+ E = Symbol('E')
711
+ I = Symbol('I')
712
+ l, P = symbols('l, P', positive=True)
713
+
714
+ b = Beam(l, E, I)
715
+ R1, R2 = symbols('R1, R2')
716
+ b.apply_load(R1, 0, -1)
717
+ b.apply_load(R2, l, -1)
718
+ b.apply_load(P, l/2, -1)
719
+ b.solve_for_reaction_loads(R1, R2)
720
+ b.reaction_loads
721
+ assert b.max_bmoment() == (l/2, P*l/4)
722
+
723
+ b = Beam(l, E, I)
724
+ R1, R2 = symbols('R1, R2')
725
+ b.apply_load(R1, 0, -1)
726
+ b.apply_load(R2, l, -1)
727
+ b.apply_load(P, 0, 0, end=l)
728
+ b.solve_for_reaction_loads(R1, R2)
729
+ assert b.max_bmoment() == (l/2, P*l**2/8)
730
+
731
+
732
+ def test_max_deflection():
733
+ E, I, l, F = symbols('E, I, l, F', positive=True)
734
+ b = Beam(l, E, I)
735
+ b.bc_deflection = [(0, 0),(l, 0)]
736
+ b.bc_slope = [(0, 0),(l, 0)]
737
+ b.apply_load(F/2, 0, -1)
738
+ b.apply_load(-F*l/8, 0, -2)
739
+ b.apply_load(F/2, l, -1)
740
+ b.apply_load(F*l/8, l, -2)
741
+ b.apply_load(-F, l/2, -1)
742
+ assert b.max_deflection() == (l/2, F*l**3/(192*E*I))
743
+
744
+ def test_solve_for_ild_reactions():
745
+ E = Symbol('E')
746
+ I = Symbol('I')
747
+ b = Beam(10, E, I)
748
+ b.apply_support(0, type="pin")
749
+ b.apply_support(10, type="pin")
750
+ R_0, R_10 = symbols('R_0, R_10')
751
+ b.solve_for_ild_reactions(1, R_0, R_10)
752
+ a = b.ild_variable
753
+ assert b.ild_reactions == {R_0: -SingularityFunction(a, 0, 0) + SingularityFunction(a, 0, 1)/10
754
+ - SingularityFunction(a, 10, 1)/10,
755
+ R_10: -SingularityFunction(a, 0, 1)/10 + SingularityFunction(a, 10, 0)
756
+ + SingularityFunction(a, 10, 1)/10}
757
+
758
+ E = Symbol('E')
759
+ I = Symbol('I')
760
+ F = Symbol('F')
761
+ L = Symbol('L', positive=True)
762
+ b = Beam(L, E, I)
763
+ b.apply_support(L, type="fixed")
764
+ b.apply_load(F, 0, -1)
765
+ R_L, M_L = symbols('R_L, M_L')
766
+ b.solve_for_ild_reactions(F, R_L, M_L)
767
+ a = b.ild_variable
768
+ assert b.ild_reactions == {R_L: -F*SingularityFunction(a, 0, 0) + F*SingularityFunction(a, L, 0) - F,
769
+ M_L: -F*L*SingularityFunction(a, 0, 0) - F*L + F*SingularityFunction(a, 0, 1)
770
+ - F*SingularityFunction(a, L, 1)}
771
+
772
+ E = Symbol('E')
773
+ I = Symbol('I')
774
+ b = Beam(20, E, I)
775
+ r0 = b.apply_support(0, type="pin")
776
+ r5 = b.apply_support(5, type="pin")
777
+ r10 = b.apply_support(10, type="pin")
778
+ r20, m20 = b.apply_support(20, type="fixed")
779
+ b.solve_for_ild_reactions(1, r0, r5, r10, r20, m20)
780
+ a = b.ild_variable
781
+ assert b.ild_reactions[r0].subs(a, 4) == -Rational(59, 475)
782
+ assert b.ild_reactions[r5].subs(a, 4) == -Rational(2296, 2375)
783
+ assert b.ild_reactions[r10].subs(a, 4) == Rational(243, 2375)
784
+ assert b.ild_reactions[r20].subs(a, 12) == -Rational(83, 475)
785
+ assert b.ild_reactions[m20].subs(a, 12) == -Rational(264, 475)
786
+
787
+ def test_solve_for_ild_shear():
788
+ E = Symbol('E')
789
+ I = Symbol('I')
790
+ F = Symbol('F')
791
+ L1 = Symbol('L1', positive=True)
792
+ L2 = Symbol('L2', positive=True)
793
+ b = Beam(L1 + L2, E, I)
794
+ r0 = b.apply_support(0, type="pin")
795
+ rL = b.apply_support(L1 + L2, type="pin")
796
+ b.solve_for_ild_reactions(F, r0, rL)
797
+ b.solve_for_ild_shear(L1, F, r0, rL)
798
+ a = b.ild_variable
799
+ expected_shear = (-F*L1*SingularityFunction(a, 0, 0)/(L1 + L2) - F*L2*SingularityFunction(a, 0, 0)/(L1 + L2)
800
+ - F*SingularityFunction(-a, 0, 0) + F*SingularityFunction(a, L1 + L2, 0) + F
801
+ + F*SingularityFunction(a, 0, 1)/(L1 + L2) - F*SingularityFunction(a, L1 + L2, 1)/(L1 + L2)
802
+ - (-F*L1*SingularityFunction(a, 0, 0)/(L1 + L2) + F*L1*SingularityFunction(a, L1 + L2, 0)/(L1 + L2)
803
+ - F*L2*SingularityFunction(a, 0, 0)/(L1 + L2) + F*L2*SingularityFunction(a, L1 + L2, 0)/(L1 + L2)
804
+ + 2*F)*SingularityFunction(a, L1, 0))
805
+ assert b.ild_shear.expand() == expected_shear.expand()
806
+
807
+ E = Symbol('E')
808
+ I = Symbol('I')
809
+ b = Beam(20, E, I)
810
+ r0 = b.apply_support(0, type="pin")
811
+ r5 = b.apply_support(5, type="pin")
812
+ r10 = b.apply_support(10, type="pin")
813
+ r20, m20 = b.apply_support(20, type="fixed")
814
+ b.solve_for_ild_reactions(1, r0, r5, r10, r20, m20)
815
+ b.solve_for_ild_shear(6, 1, r0, r5, r10, r20, m20)
816
+ a = b.ild_variable
817
+ assert b.ild_shear.subs(a, 12) == Rational(96, 475)
818
+ assert b.ild_shear.subs(a, 4) == -Rational(216, 2375)
819
+
820
+ def test_solve_for_ild_moment():
821
+ E = Symbol('E')
822
+ I = Symbol('I')
823
+ F = Symbol('F')
824
+ L1 = Symbol('L1', positive=True)
825
+ L2 = Symbol('L2', positive=True)
826
+ b = Beam(L1 + L2, E, I)
827
+ r0 = b.apply_support(0, type="pin")
828
+ rL = b.apply_support(L1 + L2, type="pin")
829
+ a = b.ild_variable
830
+ b.solve_for_ild_reactions(F, r0, rL)
831
+ b.solve_for_ild_moment(L1, F, r0, rL)
832
+ assert b.ild_moment.subs(a, 3).subs(L1, 5).subs(L2, 5) == -3*F/2
833
+
834
+ E = Symbol('E')
835
+ I = Symbol('I')
836
+ b = Beam(20, E, I)
837
+ r0 = b.apply_support(0, type="pin")
838
+ r5 = b.apply_support(5, type="pin")
839
+ r10 = b.apply_support(10, type="pin")
840
+ r20, m20 = b.apply_support(20, type="fixed")
841
+ b.solve_for_ild_reactions(1, r0, r5, r10, r20, m20)
842
+ b.solve_for_ild_moment(5, 1, r0, r5, r10, r20, m20)
843
+ assert b.ild_moment.subs(a, 12) == -Rational(96, 475)
844
+ assert b.ild_moment.subs(a, 4) == Rational(36, 95)
845
+
846
+ def test_ild_with_rotation_hinge():
847
+ E = Symbol('E')
848
+ I = Symbol('I')
849
+ F = Symbol('F')
850
+ L1 = Symbol('L1', positive=True)
851
+ L2 = Symbol('L2', positive=True)
852
+ L3 = Symbol('L3', positive=True)
853
+ b = Beam(L1 + L2 + L3, E, I)
854
+ r0 = b.apply_support(0, type="pin")
855
+ r1 = b.apply_support(L1 + L2, type="pin")
856
+ r2 = b.apply_support(L1 + L2 + L3, type="pin")
857
+ b.apply_rotation_hinge(L1 + L2)
858
+ b.solve_for_ild_reactions(F, r0, r1, r2)
859
+ a = b.ild_variable
860
+ assert b.ild_reactions[r0].subs(a, 4).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -3*F/5
861
+ assert b.ild_reactions[r0].subs(a, -10).subs(L1, 5).subs(L2, 5).subs(L3, 10) == 0
862
+ assert b.ild_reactions[r0].subs(a, 25).subs(L1, 5).subs(L2, 5).subs(L3, 10) == 0
863
+ assert b.ild_reactions[r1].subs(a, 4).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -2*F/5
864
+ assert b.ild_reactions[r2].subs(a, 18).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -4*F/5
865
+ b.solve_for_ild_shear(L1, F, r0, r1, r2)
866
+ assert b.ild_shear.subs(a, 7).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -3*F/10
867
+ assert b.ild_shear.subs(a, 70).subs(L1, 5).subs(L2, 5).subs(L3, 10) == 0
868
+ b.solve_for_ild_moment(L1, F, r0, r1, r2)
869
+ assert b.ild_moment.subs(a, 1).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -F/2
870
+ assert b.ild_moment.subs(a, 8).subs(L1, 5).subs(L2, 5).subs(L3, 10) == -F
871
+
872
+ def test_ild_with_sliding_hinge():
873
+ b = Beam(13, 200, 200)
874
+ r0 = b.apply_support(0, type="pin")
875
+ r6 = b.apply_support(6, type="pin")
876
+ r13, m13 = b.apply_support(13, type="fixed")
877
+ w3 = b.apply_sliding_hinge(3)
878
+ b.solve_for_ild_reactions(1, r0, r6, r13, m13)
879
+ a = b.ild_variable
880
+ assert b.ild_reactions[r0].subs(a, 3) == -1
881
+ assert b.ild_reactions[r6].subs(a, 3) == Rational(9, 14)
882
+ assert b.ild_reactions[r13].subs(a, 9) == -Rational(207, 343)
883
+ assert b.ild_reactions[m13].subs(a, 9) == -Rational(60, 49)
884
+ assert b.ild_reactions[m13].subs(a, 15) == 0
885
+ assert b.ild_reactions[m13].subs(a, -3) == 0
886
+ assert b.ild_deflection_jumps[w3].subs(a, 9) == -Rational(9, 35000)
887
+ b.solve_for_ild_shear(7, 1, r0, r6, r13, m13)
888
+ assert b.ild_shear.subs(a, 8) == -Rational(200, 343)
889
+ b.solve_for_ild_moment(8, 1, r0, r6, r13, m13)
890
+ assert b.ild_moment.subs(a, 3) == -Rational(12, 7)
891
+
892
+ def test_Beam3D():
893
+ l, E, G, I, A = symbols('l, E, G, I, A')
894
+ R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
895
+
896
+ b = Beam3D(l, E, G, I, A)
897
+ m, q = symbols('m, q')
898
+ b.apply_load(q, 0, 0, dir="y")
899
+ b.apply_moment_load(m, 0, 0, dir="z")
900
+ b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
901
+ b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
902
+ b.solve_slope_deflection()
903
+
904
+ assert b.polar_moment() == 2*I
905
+ assert b.shear_force() == [0, -q*x, 0]
906
+ assert b.shear_stress() == [0, -q*x/A, 0]
907
+ assert b.axial_stress() == 0
908
+ assert b.bending_moment() == [0, 0, -m*x + q*x**2/2]
909
+ expected_deflection = (x*(A*G*q*x**3/4 + A*G*x**2*(-l*(A*G*l*(l*q - 2*m) +
910
+ 12*E*I*q)/(A*G*l**2 + 12*E*I)/2 - m) + 3*E*I*l*(A*G*l*(l*q - 2*m) +
911
+ 12*E*I*q)/(A*G*l**2 + 12*E*I) + x*(-A*G*l**2*q/2 +
912
+ 3*A*G*l**2*(A*G*l*(l*q - 2*m) + 12*E*I*q)/(A*G*l**2 + 12*E*I)/4 +
913
+ A*G*l*m*Rational(3, 2) - 3*E*I*q))/(6*A*E*G*I))
914
+ dx, dy, dz = b.deflection()
915
+ assert dx == dz == 0
916
+ assert simplify(dy - expected_deflection) == 0
917
+
918
+ b2 = Beam3D(30, E, G, I, A, x)
919
+ b2.apply_load(50, start=0, order=0, dir="y")
920
+ b2.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
921
+ b2.apply_load(R1, start=0, order=-1, dir="y")
922
+ b2.apply_load(R2, start=30, order=-1, dir="y")
923
+ b2.solve_for_reaction_loads(R1, R2)
924
+ assert b2.reaction_loads == {R1: -750, R2: -750}
925
+
926
+ b2.solve_slope_deflection()
927
+ assert b2.slope() == [0, 0, 25*x**3/(3*E*I) - 375*x**2/(E*I) + 3750*x/(E*I)]
928
+ expected_deflection = 25*x**4/(12*E*I) - 125*x**3/(E*I) + 1875*x**2/(E*I) - \
929
+ 25*x**2/(A*G) + 750*x/(A*G)
930
+ dx, dy, dz = b2.deflection()
931
+ assert dx == dz == 0
932
+ assert dy == expected_deflection
933
+
934
+ # Test for solve_for_reaction_loads
935
+ b3 = Beam3D(30, E, G, I, A, x)
936
+ b3.apply_load(8, start=0, order=0, dir="y")
937
+ b3.apply_load(9*x, start=0, order=0, dir="z")
938
+ b3.apply_load(R1, start=0, order=-1, dir="y")
939
+ b3.apply_load(R2, start=30, order=-1, dir="y")
940
+ b3.apply_load(R3, start=0, order=-1, dir="z")
941
+ b3.apply_load(R4, start=30, order=-1, dir="z")
942
+ b3.solve_for_reaction_loads(R1, R2, R3, R4)
943
+ assert b3.reaction_loads == {R1: -120, R2: -120, R3: -1350, R4: -2700}
944
+
945
+
946
+ def test_polar_moment_Beam3D():
947
+ l, E, G, A, I1, I2 = symbols('l, E, G, A, I1, I2')
948
+ I = [I1, I2]
949
+
950
+ b = Beam3D(l, E, G, I, A)
951
+ assert b.polar_moment() == I1 + I2
952
+
953
+
954
+ def test_parabolic_loads():
955
+
956
+ E, I, L = symbols('E, I, L', positive=True, real=True)
957
+ R, M, P = symbols('R, M, P', real=True)
958
+
959
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
960
+ # length of beam
961
+ beam = Beam(L, E, I)
962
+
963
+ beam.bc_deflection.append((0, 0))
964
+ beam.bc_slope.append((0, 0))
965
+ beam.apply_load(R, 0, -1)
966
+ beam.apply_load(M, 0, -2)
967
+
968
+ # parabolic load
969
+ beam.apply_load(1, 0, 2)
970
+
971
+ beam.solve_for_reaction_loads(R, M)
972
+
973
+ assert beam.reaction_loads[R] == -L**3/3
974
+
975
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
976
+ # first half of beam
977
+ beam = Beam(2*L, E, I)
978
+
979
+ beam.bc_deflection.append((0, 0))
980
+ beam.bc_slope.append((0, 0))
981
+ beam.apply_load(R, 0, -1)
982
+ beam.apply_load(M, 0, -2)
983
+
984
+ # parabolic load from x=0 to x=L
985
+ beam.apply_load(1, 0, 2, end=L)
986
+
987
+ beam.solve_for_reaction_loads(R, M)
988
+
989
+ # result should be the same as the prior example
990
+ assert beam.reaction_loads[R] == -L**3/3
991
+
992
+ # check constant load
993
+ beam = Beam(2*L, E, I)
994
+ beam.apply_load(P, 0, 0, end=L)
995
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
996
+ assert loading.xreplace({x: 5}) == 40
997
+ assert loading.xreplace({x: 15}) == 0
998
+
999
+ # check ramp load
1000
+ beam = Beam(2*L, E, I)
1001
+ beam.apply_load(P, 0, 1, end=L)
1002
+ assert beam.load == (P*SingularityFunction(x, 0, 1) -
1003
+ P*SingularityFunction(x, L, 1) -
1004
+ P*L*SingularityFunction(x, L, 0))
1005
+
1006
+ # check higher order load: x**8 load from x=0 to x=L
1007
+ beam = Beam(2*L, E, I)
1008
+ beam.apply_load(P, 0, 8, end=L)
1009
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
1010
+ assert loading.xreplace({x: 5}) == 40*5**8
1011
+ assert loading.xreplace({x: 15}) == 0
1012
+
1013
+
1014
+ def test_cross_section():
1015
+ I = Symbol('I')
1016
+ l = Symbol('l')
1017
+ E = Symbol('E')
1018
+ C3, C4 = symbols('C3, C4')
1019
+ a, c, g, h, r, n = symbols('a, c, g, h, r, n')
1020
+
1021
+ # test for second_moment and cross_section setter
1022
+ b0 = Beam(l, E, I)
1023
+ assert b0.second_moment == I
1024
+ assert b0.cross_section == None
1025
+ b0.cross_section = Circle((0, 0), 5)
1026
+ assert b0.second_moment == pi*Rational(625, 4)
1027
+ assert b0.cross_section == Circle((0, 0), 5)
1028
+ b0.second_moment = 2*n - 6
1029
+ assert b0.second_moment == 2*n-6
1030
+ assert b0.cross_section == None
1031
+ with raises(ValueError):
1032
+ b0.second_moment = Circle((0, 0), 5)
1033
+
1034
+ # beam with a circular cross-section
1035
+ b1 = Beam(50, E, Circle((0, 0), r))
1036
+ assert b1.cross_section == Circle((0, 0), r)
1037
+ assert b1.second_moment == pi*r*Abs(r)**3/4
1038
+
1039
+ b1.apply_load(-10, 0, -1)
1040
+ b1.apply_load(R1, 5, -1)
1041
+ b1.apply_load(R2, 50, -1)
1042
+ b1.apply_load(90, 45, -2)
1043
+ b1.solve_for_reaction_loads(R1, R2)
1044
+ assert b1.load == (-10*SingularityFunction(x, 0, -1) + 82*SingularityFunction(x, 5, -1)/S(9)
1045
+ + 90*SingularityFunction(x, 45, -2) + 8*SingularityFunction(x, 50, -1)/9)
1046
+ assert b1.bending_moment() == (10*SingularityFunction(x, 0, 1) - 82*SingularityFunction(x, 5, 1)/9
1047
+ - 90*SingularityFunction(x, 45, 0) - 8*SingularityFunction(x, 50, 1)/9)
1048
+ q = (-5*SingularityFunction(x, 0, 2) + 41*SingularityFunction(x, 5, 2)/S(9)
1049
+ + 90*SingularityFunction(x, 45, 1) + 4*SingularityFunction(x, 50, 2)/S(9))/(pi*E*r*Abs(r)**3)
1050
+ assert b1.slope() == C3 + 4*q
1051
+ q = (-5*SingularityFunction(x, 0, 3)/3 + 41*SingularityFunction(x, 5, 3)/27 + 45*SingularityFunction(x, 45, 2)
1052
+ + 4*SingularityFunction(x, 50, 3)/27)/(pi*E*r*Abs(r)**3)
1053
+ assert b1.deflection() == C3*x + C4 + 4*q
1054
+
1055
+ # beam with a recatangular cross-section
1056
+ b2 = Beam(20, E, Polygon((0, 0), (a, 0), (a, c), (0, c)))
1057
+ assert b2.cross_section == Polygon((0, 0), (a, 0), (a, c), (0, c))
1058
+ assert b2.second_moment == a*c**3/12
1059
+ # beam with a triangular cross-section
1060
+ b3 = Beam(15, E, Triangle((0, 0), (g, 0), (g/2, h)))
1061
+ assert b3.cross_section == Triangle(Point2D(0, 0), Point2D(g, 0), Point2D(g/2, h))
1062
+ assert b3.second_moment == g*h**3/36
1063
+
1064
+ # composite beam
1065
+ b = b2.join(b3, "fixed")
1066
+ b.apply_load(-30, 0, -1)
1067
+ b.apply_load(65, 0, -2)
1068
+ b.apply_load(40, 0, -1)
1069
+ b.bc_slope = [(0, 0)]
1070
+ b.bc_deflection = [(0, 0)]
1071
+
1072
+ assert b.second_moment == Piecewise((a*c**3/12, x <= 20), (g*h**3/36, x <= 35))
1073
+ assert b.cross_section == None
1074
+ assert b.length == 35
1075
+ assert b.slope().subs(x, 7) == 8400/(E*a*c**3)
1076
+ assert b.slope().subs(x, 25) == 52200/(E*g*h**3) + 39600/(E*a*c**3)
1077
+ assert b.deflection().subs(x, 30) == -537000/(E*g*h**3) - 712000/(E*a*c**3)
1078
+
1079
+ def test_max_shear_force_Beam3D():
1080
+ x = symbols('x')
1081
+ b = Beam3D(20, 40, 21, 100, 25)
1082
+ b.apply_load(15, start=0, order=0, dir="z")
1083
+ b.apply_load(12*x, start=0, order=0, dir="y")
1084
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
1085
+ assert b.max_shear_force() == [(0, 0), (20, 2400), (20, 300)]
1086
+
1087
+ def test_max_bending_moment_Beam3D():
1088
+ x = symbols('x')
1089
+ b = Beam3D(20, 40, 21, 100, 25)
1090
+ b.apply_load(15, start=0, order=0, dir="z")
1091
+ b.apply_load(12*x, start=0, order=0, dir="y")
1092
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
1093
+ assert b.max_bmoment() == [(0, 0), (20, 3000), (20, 16000)]
1094
+
1095
+ def test_max_deflection_Beam3D():
1096
+ x = symbols('x')
1097
+ b = Beam3D(20, 40, 21, 100, 25)
1098
+ b.apply_load(15, start=0, order=0, dir="z")
1099
+ b.apply_load(12*x, start=0, order=0, dir="y")
1100
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
1101
+ b.solve_slope_deflection()
1102
+ c = sympify("495/14")
1103
+ p = sympify("-10 + 10*sqrt(10793)/43")
1104
+ 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")
1105
+ assert b.max_deflection() == [(0, 0), (10, c), (p, q)]
1106
+
1107
+ def test_torsion_Beam3D():
1108
+ x = symbols('x')
1109
+ b = Beam3D(20, 40, 21, 100, 25)
1110
+ b.apply_moment_load(15, 5, -2, dir='x')
1111
+ b.apply_moment_load(25, 10, -2, dir='x')
1112
+ b.apply_moment_load(-5, 20, -2, dir='x')
1113
+ b.solve_for_torsion()
1114
+ assert b.angular_deflection().subs(x, 3) == sympify("1/40")
1115
+ assert b.angular_deflection().subs(x, 9) == sympify("17/280")
1116
+ assert b.angular_deflection().subs(x, 12) == sympify("53/840")
1117
+ assert b.angular_deflection().subs(x, 17) == sympify("2/35")
1118
+ assert b.angular_deflection().subs(x, 20) == sympify("3/56")
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_cable.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.continuum_mechanics.cable import Cable
2
+ from sympy.core.symbol import Symbol
3
+
4
+
5
+ def test_cable():
6
+ c = Cable(('A', 0, 10), ('B', 10, 10))
7
+ assert c.supports == {'A': [0, 10], 'B': [10, 10]}
8
+ assert c.left_support == [0, 10]
9
+ assert c.right_support == [10, 10]
10
+ assert c.loads == {'distributed': {}, 'point_load': {}}
11
+ assert c.loads_position == {}
12
+ assert c.length == 0
13
+ assert c.reaction_loads == {Symbol("R_A_x"): 0, Symbol("R_A_y"): 0, Symbol("R_B_x"): 0, Symbol("R_B_y"): 0}
14
+
15
+ # tests for change_support method
16
+ c.change_support('A', ('C', 12, 3))
17
+ assert c.supports == {'B': [10, 10], 'C': [12, 3]}
18
+ assert c.left_support == [10, 10]
19
+ assert c.right_support == [12, 3]
20
+ assert c.reaction_loads == {Symbol("R_B_x"): 0, Symbol("R_B_y"): 0, Symbol("R_C_x"): 0, Symbol("R_C_y"): 0}
21
+
22
+ c.change_support('C', ('A', 0, 10))
23
+
24
+ # tests for apply_load method for point loads
25
+ c.apply_load(-1, ('X', 2, 5, 3, 30))
26
+ c.apply_load(-1, ('Y', 5, 8, 5, 60))
27
+ assert c.loads == {'distributed': {}, 'point_load': {'X': [3, 30], 'Y': [5, 60]}}
28
+ assert c.loads_position == {'X': [2, 5], 'Y': [5, 8]}
29
+ assert c.length == 0
30
+ assert c.reaction_loads == {Symbol("R_A_x"): 0, Symbol("R_A_y"): 0, Symbol("R_B_x"): 0, Symbol("R_B_y"): 0}
31
+
32
+ # tests for remove_loads method
33
+ c.remove_loads('X')
34
+ assert c.loads == {'distributed': {}, 'point_load': {'Y': [5, 60]}}
35
+ assert c.loads_position == {'Y': [5, 8]}
36
+ assert c.length == 0
37
+ assert c.reaction_loads == {Symbol("R_A_x"): 0, Symbol("R_A_y"): 0, Symbol("R_B_x"): 0, Symbol("R_B_y"): 0}
38
+
39
+ c.remove_loads('Y')
40
+
41
+ #tests for apply_load method for distributed load
42
+ c.apply_load(0, ('Z', 9))
43
+ assert c.loads == {'distributed': {'Z': 9}, 'point_load': {}}
44
+ assert c.loads_position == {}
45
+ assert c.length == 0
46
+ assert c.reaction_loads == {Symbol("R_A_x"): 0, Symbol("R_A_y"): 0, Symbol("R_B_x"): 0, Symbol("R_B_y"): 0}
47
+
48
+ # tests for apply_length method
49
+ c.apply_length(20)
50
+ assert c.length == 20
51
+
52
+ del c
53
+ # tests for solve method
54
+ # for point loads
55
+ c = Cable(("A", 0, 10), ("B", 5.5, 8))
56
+ c.apply_load(-1, ('Z', 2, 7.26, 3, 270))
57
+ c.apply_load(-1, ('X', 4, 6, 8, 270))
58
+ c.solve()
59
+ #assert c.tension == {Symbol("Z_X"): 4.79150773600774, Symbol("X_B"): 6.78571428571429, Symbol("A_Z"): 6.89488895397307}
60
+ assert abs(c.tension[Symbol("A_Z")] - 6.89488895397307) < 10e-12
61
+ assert abs(c.tension[Symbol("Z_X")] - 4.79150773600774) < 10e-12
62
+ assert abs(c.tension[Symbol("X_B")] - 6.78571428571429) < 10e-12
63
+ #assert c.reaction_loads == {Symbol("R_A_x"): -4.06504065040650, Symbol("R_A_y"): 5.56910569105691, Symbol("R_B_x"): 4.06504065040650, Symbol("R_B_y"): 5.43089430894309}
64
+ assert abs(c.reaction_loads[Symbol("R_A_x")] + 4.06504065040650) < 10e-12
65
+ assert abs(c.reaction_loads[Symbol("R_A_y")] - 5.56910569105691) < 10e-12
66
+ assert abs(c.reaction_loads[Symbol("R_B_x")] - 4.06504065040650) < 10e-12
67
+ assert abs(c.reaction_loads[Symbol("R_B_y")] - 5.43089430894309) < 10e-12
68
+ assert abs(c.length - 8.25609584845190) < 10e-12
69
+
70
+ del c
71
+ # tests for solve method
72
+ # for distributed loads
73
+ c=Cable(("A", 0, 40),("B", 100, 20))
74
+ c.apply_load(0, ("X", 850))
75
+ c.solve(58.58, 0)
76
+
77
+ # assert c.tension['distributed'] == 36456.8485*sqrt(0.000543529004799705*(X + 0.00135624381275735)**2 + 1)
78
+ assert abs(c.tension_at(0) - 61717.4130533677) < 10e-11
79
+ assert abs(c.tension_at(40) - 39738.0809048449) < 10e-11
80
+ assert abs(c.reaction_loads[Symbol("R_A_x")] - 36465.0000000000) < 10e-11
81
+ assert abs(c.reaction_loads[Symbol("R_A_y")] + 49793.0000000000) < 10e-11
82
+ assert abs(c.reaction_loads[Symbol("R_B_x")] - 44399.9537590861) < 10e-11
83
+ assert abs(c.reaction_loads[Symbol("R_B_y")] - 42868.2071025955 ) < 10e-11
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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), (B, 2, 2), (C, 3, 0))
25
+ assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)]
26
+ assert t.node_labels == [A, B, C]
27
+ assert t.node_positions == [(0, 0), (2, 2), (3, 0)]
28
+ assert t.loads == {}
29
+ assert t.supports == {}
30
+ assert t.reaction_loads == {}
31
+
32
+ # testing the remove_node method
33
+ t.remove_node(C)
34
+ assert t.nodes == [(A, 0, 0), (B, 2, 2)]
35
+ assert t.node_labels == [A, B]
36
+ assert t.node_positions == [(0, 0), (2, 2)]
37
+ assert t.loads == {}
38
+ assert t.supports == {}
39
+
40
+ t.add_node((C, 3, 0))
41
+
42
+ # testing the add_member method
43
+ t.add_member((AB, A, B), (BC, B, C), (AC, A, C))
44
+ assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]}
45
+ assert t.internal_forces == {AB: 0, BC: 0, AC: 0}
46
+
47
+ # testing the remove_member method
48
+ t.remove_member(BC)
49
+ assert t.members == {AB: [A, B], AC: [A, C]}
50
+ assert t.internal_forces == {AB: 0, AC: 0}
51
+
52
+ t.add_member((BC, B, C))
53
+
54
+ D, CD = symbols('D, CD')
55
+
56
+ # testing the change_label methods
57
+ t.change_node_label((B, D))
58
+ assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)]
59
+ assert t.node_labels == [A, D, C]
60
+ assert t.loads == {}
61
+ assert t.supports == {}
62
+ assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]}
63
+
64
+ t.change_member_label((BC, CD))
65
+ assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]}
66
+ assert t.internal_forces == {AB: 0, CD: 0, AC: 0}
67
+
68
+
69
+ # testing the apply_load method
70
+ t.apply_load((A, P, 90), (A, P/4, 90), (A, 2*P,45), (D, P/2, 90))
71
+ assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]}
72
+ assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]]
73
+
74
+ # testing the remove_load method
75
+ t.remove_load((A, P/4, 90))
76
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]}
77
+ assert t.loads[A] == [[P, 90], [2*P, 45]]
78
+
79
+ # testing the apply_support method
80
+ t.apply_support((A, "pinned"), (D, "roller"))
81
+ assert t.supports == {A: 'pinned', D: 'roller'}
82
+ assert t.reaction_loads == {}
83
+ 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]]}
84
+
85
+ # testing the remove_support method
86
+ t.remove_support(A)
87
+ assert t.supports == {D: 'roller'}
88
+ assert t.reaction_loads == {}
89
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
90
+
91
+ t.apply_support((A, "pinned"))
92
+
93
+ # testing the solve method
94
+ t.solve()
95
+ assert t.reaction_loads['R_A_x'] == -sqrt(2)*P
96
+ assert t.reaction_loads['R_A_y'] == -sqrt(2)*P - P
97
+ assert t.reaction_loads['R_D_y'] == -P/2
98
+ assert t.internal_forces[AB]/P == 0
99
+ assert t.internal_forces[CD] == 0
100
+ assert t.internal_forces[AC] == 0
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py ADDED
@@ -0,0 +1,1108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module can be used to solve problems related
3
+ to 2D Trusses.
4
+ """
5
+
6
+
7
+ from cmath import atan, inf
8
+ from sympy.core.add import Add
9
+ from sympy.core.evalf import INF
10
+ from sympy.core.mul import Mul
11
+ from sympy.core.symbol import Symbol
12
+ from sympy.core.sympify import sympify
13
+ from sympy import Matrix, pi
14
+ from sympy.external.importtools import import_module
15
+ from sympy.functions.elementary.miscellaneous import sqrt
16
+ from sympy.matrices.dense import zeros
17
+ import math
18
+ from sympy.physics.units.quantities import Quantity
19
+ from sympy.plotting import plot
20
+ from sympy.utilities.decorator import doctest_depends_on
21
+ from sympy import sin, cos
22
+
23
+
24
+ __doctest_requires__ = {('Truss.draw'): ['matplotlib']}
25
+
26
+
27
+ numpy = import_module('numpy', import_kwargs={'fromlist':['arange']})
28
+
29
+
30
+ class Truss:
31
+ """
32
+ A Truss is an assembly of members such as beams,
33
+ connected by nodes, that create a rigid structure.
34
+ In engineering, a truss is a structure that
35
+ consists of two-force members only.
36
+
37
+ Trusses are extremely important in engineering applications
38
+ and can be seen in numerous real-world applications like bridges.
39
+
40
+ Examples
41
+ ========
42
+
43
+ There is a Truss consisting of four nodes and five
44
+ members connecting the nodes. A force P acts
45
+ downward on the node D and there also exist pinned
46
+ and roller joints on the nodes A and B respectively.
47
+
48
+ .. image:: truss_example.png
49
+
50
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
51
+ >>> t = Truss()
52
+ >>> t.add_node(("node_1", 0, 0), ("node_2", 6, 0), ("node_3", 2, 2), ("node_4", 2, 0))
53
+ >>> t.add_member(("member_1", "node_1", "node_4"), ("member_2", "node_2", "node_4"), ("member_3", "node_1", "node_3"))
54
+ >>> t.add_member(("member_4", "node_2", "node_3"), ("member_5", "node_3", "node_4"))
55
+ >>> t.apply_load(("node_4", 10, 270))
56
+ >>> t.apply_support(("node_1", "pinned"), ("node_2", "roller"))
57
+ """
58
+
59
+ def __init__(self):
60
+ """
61
+ Initializes the class
62
+ """
63
+ self._nodes = []
64
+ self._members = {}
65
+ self._loads = {}
66
+ self._supports = {}
67
+ self._node_labels = []
68
+ self._node_positions = []
69
+ self._node_position_x = []
70
+ self._node_position_y = []
71
+ self._nodes_occupied = {}
72
+ self._member_lengths = {}
73
+ self._reaction_loads = {}
74
+ self._internal_forces = {}
75
+ self._node_coordinates = {}
76
+
77
+ @property
78
+ def nodes(self):
79
+ """
80
+ Returns the nodes of the truss along with their positions.
81
+ """
82
+ return self._nodes
83
+
84
+ @property
85
+ def node_labels(self):
86
+ """
87
+ Returns the node labels of the truss.
88
+ """
89
+ return self._node_labels
90
+
91
+ @property
92
+ def node_positions(self):
93
+ """
94
+ Returns the positions of the nodes of the truss.
95
+ """
96
+ return self._node_positions
97
+
98
+ @property
99
+ def members(self):
100
+ """
101
+ Returns the members of the truss along with the start and end points.
102
+ """
103
+ return self._members
104
+
105
+ @property
106
+ def member_lengths(self):
107
+ """
108
+ Returns the length of each member of the truss.
109
+ """
110
+ return self._member_lengths
111
+
112
+ @property
113
+ def supports(self):
114
+ """
115
+ Returns the nodes with provided supports along with the kind of support provided i.e.
116
+ pinned or roller.
117
+ """
118
+ return self._supports
119
+
120
+ @property
121
+ def loads(self):
122
+ """
123
+ Returns the loads acting on the truss.
124
+ """
125
+ return self._loads
126
+
127
+ @property
128
+ def reaction_loads(self):
129
+ """
130
+ Returns the reaction forces for all supports which are all initialized to 0.
131
+ """
132
+ return self._reaction_loads
133
+
134
+ @property
135
+ def internal_forces(self):
136
+ """
137
+ Returns the internal forces for all members which are all initialized to 0.
138
+ """
139
+ return self._internal_forces
140
+
141
+ def add_node(self, *args):
142
+ """
143
+ This method adds a node to the truss along with its name/label and its location.
144
+ Multiple nodes can be added at the same time.
145
+
146
+ Parameters
147
+ ==========
148
+ The input(s) for this method are tuples of the form (label, x, y).
149
+
150
+ label: String or a Symbol
151
+ The label for a node. It is the only way to identify a particular node.
152
+
153
+ x: Sympifyable
154
+ The x-coordinate of the position of the node.
155
+
156
+ y: Sympifyable
157
+ The y-coordinate of the position of the node.
158
+
159
+ Examples
160
+ ========
161
+
162
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
163
+ >>> t = Truss()
164
+ >>> t.add_node(('A', 0, 0))
165
+ >>> t.nodes
166
+ [('A', 0, 0)]
167
+ >>> t.add_node(('B', 3, 0), ('C', 4, 1))
168
+ >>> t.nodes
169
+ [('A', 0, 0), ('B', 3, 0), ('C', 4, 1)]
170
+ """
171
+
172
+ for i in args:
173
+ label = i[0]
174
+ x = i[1]
175
+ x = sympify(x)
176
+ y=i[2]
177
+ y = sympify(y)
178
+ if label in self._node_coordinates:
179
+ raise ValueError("Node needs to have a unique label")
180
+
181
+ elif [x, y] in self._node_coordinates.values():
182
+ raise ValueError("A node already exists at the given position")
183
+
184
+ else :
185
+ self._nodes.append((label, x, y))
186
+ self._node_labels.append(label)
187
+ self._node_positions.append((x, y))
188
+ self._node_position_x.append(x)
189
+ self._node_position_y.append(y)
190
+ self._node_coordinates[label] = [x, y]
191
+
192
+
193
+
194
+ def remove_node(self, *args):
195
+ """
196
+ This method removes a node from the truss.
197
+ Multiple nodes can be removed at the same time.
198
+
199
+ Parameters
200
+ ==========
201
+ The input(s) for this method are the labels of the nodes to be removed.
202
+
203
+ label: String or Symbol
204
+ The label of the node to be removed.
205
+
206
+ Examples
207
+ ========
208
+
209
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
210
+ >>> t = Truss()
211
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0), ('C', 5, 0))
212
+ >>> t.nodes
213
+ [('A', 0, 0), ('B', 3, 0), ('C', 5, 0)]
214
+ >>> t.remove_node('A', 'C')
215
+ >>> t.nodes
216
+ [('B', 3, 0)]
217
+ """
218
+ for label in args:
219
+ for i in range(len(self.nodes)):
220
+ if self._node_labels[i] == label:
221
+ x = self._node_position_x[i]
222
+ y = self._node_position_y[i]
223
+
224
+ if label not in self._node_coordinates:
225
+ raise ValueError("No such node exists in the truss")
226
+
227
+ else:
228
+ members_duplicate = self._members.copy()
229
+ for member in members_duplicate:
230
+ if label == self._members[member][0] or label == self._members[member][1]:
231
+ raise ValueError("The given node already has member attached to it")
232
+ self._nodes.remove((label, x, y))
233
+ self._node_labels.remove(label)
234
+ self._node_positions.remove((x, y))
235
+ self._node_position_x.remove(x)
236
+ self._node_position_y.remove(y)
237
+ if label in self._loads:
238
+ self._loads.pop(label)
239
+ if label in self._supports:
240
+ self._supports.pop(label)
241
+ self._node_coordinates.pop(label)
242
+
243
+
244
+
245
+ def add_member(self, *args):
246
+ """
247
+ This method adds a member between any two nodes in the given truss.
248
+
249
+ Parameters
250
+ ==========
251
+ The input(s) of the method are tuple(s) of the form (label, start, end).
252
+
253
+ label: String or Symbol
254
+ The label for a member. It is the only way to identify a particular member.
255
+
256
+ start: String or Symbol
257
+ The label of the starting point/node of the member.
258
+
259
+ end: String or Symbol
260
+ The label of the ending point/node of the member.
261
+
262
+ Examples
263
+ ========
264
+
265
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
266
+ >>> t = Truss()
267
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0), ('C', 2, 2))
268
+ >>> t.add_member(('AB', 'A', 'B'), ('BC', 'B', 'C'))
269
+ >>> t.members
270
+ {'AB': ['A', 'B'], 'BC': ['B', 'C']}
271
+ """
272
+ for i in args:
273
+ label = i[0]
274
+ start = i[1]
275
+ end = i[2]
276
+
277
+ if start not in self._node_coordinates or end not in self._node_coordinates or start==end:
278
+ raise ValueError("The start and end points of the member must be unique nodes")
279
+
280
+ elif label in self._members:
281
+ raise ValueError("A member with the same label already exists for the truss")
282
+
283
+ elif self._nodes_occupied.get((start, end)):
284
+ raise ValueError("A member already exists between the two nodes")
285
+
286
+ else:
287
+ self._members[label] = [start, end]
288
+ self._member_lengths[label] = sqrt((self._node_coordinates[end][0]-self._node_coordinates[start][0])**2 + (self._node_coordinates[end][1]-self._node_coordinates[start][1])**2)
289
+ self._nodes_occupied[start, end] = True
290
+ self._nodes_occupied[end, start] = True
291
+ self._internal_forces[label] = 0
292
+
293
+ def remove_member(self, *args):
294
+ """
295
+ This method removes members from the given truss.
296
+
297
+ Parameters
298
+ ==========
299
+ labels: String or Symbol
300
+ The label for the member to be removed.
301
+
302
+ Examples
303
+ ========
304
+
305
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
306
+ >>> t = Truss()
307
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0), ('C', 2, 2))
308
+ >>> t.add_member(('AB', 'A', 'B'), ('AC', 'A', 'C'), ('BC', 'B', 'C'))
309
+ >>> t.members
310
+ {'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']}
311
+ >>> t.remove_member('AC', 'BC')
312
+ >>> t.members
313
+ {'AB': ['A', 'B']}
314
+ """
315
+ for label in args:
316
+ if label not in self._members:
317
+ raise ValueError("No such member exists in the Truss")
318
+
319
+ else:
320
+ self._nodes_occupied.pop((self._members[label][0], self._members[label][1]))
321
+ self._nodes_occupied.pop((self._members[label][1], self._members[label][0]))
322
+ self._members.pop(label)
323
+ self._member_lengths.pop(label)
324
+ self._internal_forces.pop(label)
325
+
326
+ def change_node_label(self, *args):
327
+ """
328
+ This method changes the label(s) of the specified node(s).
329
+
330
+ Parameters
331
+ ==========
332
+ The input(s) of this method are tuple(s) of the form (label, new_label).
333
+
334
+ label: String or Symbol
335
+ The label of the node for which the label has
336
+ to be changed.
337
+
338
+ new_label: String or Symbol
339
+ The new label of the node.
340
+
341
+ Examples
342
+ ========
343
+
344
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
345
+ >>> t = Truss()
346
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0))
347
+ >>> t.nodes
348
+ [('A', 0, 0), ('B', 3, 0)]
349
+ >>> t.change_node_label(('A', 'C'), ('B', 'D'))
350
+ >>> t.nodes
351
+ [('C', 0, 0), ('D', 3, 0)]
352
+ """
353
+ for i in args:
354
+ label = i[0]
355
+ new_label = i[1]
356
+ if label not in self._node_coordinates:
357
+ raise ValueError("No such node exists for the Truss")
358
+ elif new_label in self._node_coordinates:
359
+ raise ValueError("A node with the given label already exists")
360
+ else:
361
+ for node in self._nodes:
362
+ if node[0] == label:
363
+ self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2])
364
+ self._node_labels[self._node_labels.index(node[0])] = new_label
365
+ self._node_coordinates[new_label] = self._node_coordinates[label]
366
+ self._node_coordinates.pop(label)
367
+ if node[0] in self._supports:
368
+ self._supports[new_label] = self._supports[node[0]]
369
+ self._supports.pop(node[0])
370
+ if new_label in self._supports:
371
+ if self._supports[new_label] == 'pinned':
372
+ if 'R_'+str(label)+'_x' in self._reaction_loads and 'R_'+str(label)+'_y' in self._reaction_loads:
373
+ self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x']
374
+ self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y']
375
+ self._reaction_loads.pop('R_'+str(label)+'_x')
376
+ self._reaction_loads.pop('R_'+str(label)+'_y')
377
+ self._loads[new_label] = self._loads[label]
378
+ for load in self._loads[new_label]:
379
+ if load[1] == 90:
380
+ load[0] -= Symbol('R_'+str(label)+'_y')
381
+ if load[0] == 0:
382
+ self._loads[label].remove(load)
383
+ break
384
+ for load in self._loads[new_label]:
385
+ if load[1] == 0:
386
+ load[0] -= Symbol('R_'+str(label)+'_x')
387
+ if load[0] == 0:
388
+ self._loads[label].remove(load)
389
+ break
390
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0)
391
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
392
+ self._loads.pop(label)
393
+ elif self._supports[new_label] == 'roller':
394
+ self._loads[new_label] = self._loads[label]
395
+ for load in self._loads[label]:
396
+ if load[1] == 90:
397
+ load[0] -= Symbol('R_'+str(label)+'_y')
398
+ if load[0] == 0:
399
+ self._loads[label].remove(load)
400
+ break
401
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
402
+ self._loads.pop(label)
403
+ else:
404
+ if label in self._loads:
405
+ self._loads[new_label] = self._loads[label]
406
+ self._loads.pop(label)
407
+ for member in self._members:
408
+ if self._members[member][0] == node[0]:
409
+ self._members[member][0] = new_label
410
+ self._nodes_occupied[(new_label, self._members[member][1])] = True
411
+ self._nodes_occupied[(self._members[member][1], new_label)] = True
412
+ self._nodes_occupied.pop((label, self._members[member][1]))
413
+ self._nodes_occupied.pop((self._members[member][1], label))
414
+ elif self._members[member][1] == node[0]:
415
+ self._members[member][1] = new_label
416
+ self._nodes_occupied[(self._members[member][0], new_label)] = True
417
+ self._nodes_occupied[(new_label, self._members[member][0])] = True
418
+ self._nodes_occupied.pop((self._members[member][0], label))
419
+ self._nodes_occupied.pop((label, self._members[member][0]))
420
+
421
+ def change_member_label(self, *args):
422
+ """
423
+ This method changes the label(s) of the specified member(s).
424
+
425
+ Parameters
426
+ ==========
427
+ The input(s) of this method are tuple(s) of the form (label, new_label)
428
+
429
+ label: String or Symbol
430
+ The label of the member for which the label has
431
+ to be changed.
432
+
433
+ new_label: String or Symbol
434
+ The new label of the member.
435
+
436
+ Examples
437
+ ========
438
+
439
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
440
+ >>> t = Truss()
441
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0), ('D', 5, 0))
442
+ >>> t.nodes
443
+ [('A', 0, 0), ('B', 3, 0), ('D', 5, 0)]
444
+ >>> t.change_node_label(('A', 'C'))
445
+ >>> t.nodes
446
+ [('C', 0, 0), ('B', 3, 0), ('D', 5, 0)]
447
+ >>> t.add_member(('BC', 'B', 'C'), ('BD', 'B', 'D'))
448
+ >>> t.members
449
+ {'BC': ['B', 'C'], 'BD': ['B', 'D']}
450
+ >>> t.change_member_label(('BC', 'BC_new'), ('BD', 'BD_new'))
451
+ >>> t.members
452
+ {'BC_new': ['B', 'C'], 'BD_new': ['B', 'D']}
453
+ """
454
+ for i in args:
455
+ label = i[0]
456
+ new_label = i[1]
457
+ if label not in self._members:
458
+ raise ValueError("No such member exists for the Truss")
459
+ else:
460
+ members_duplicate = list(self._members).copy()
461
+ for member in members_duplicate:
462
+ if member == label:
463
+ self._members[new_label] = [self._members[member][0], self._members[member][1]]
464
+ self._members.pop(label)
465
+ self._member_lengths[new_label] = self._member_lengths[label]
466
+ self._member_lengths.pop(label)
467
+ self._internal_forces[new_label] = self._internal_forces[label]
468
+ self._internal_forces.pop(label)
469
+
470
+ def apply_load(self, *args):
471
+ """
472
+ This method applies external load(s) at the specified node(s).
473
+
474
+ Parameters
475
+ ==========
476
+ The input(s) of the method are tuple(s) of the form (location, magnitude, direction).
477
+
478
+ location: String or Symbol
479
+ Label of the Node at which load is applied.
480
+
481
+ magnitude: Sympifyable
482
+ Magnitude of the load applied. It must always be positive and any changes in
483
+ the direction of the load are not reflected here.
484
+
485
+ direction: Sympifyable
486
+ The angle, in degrees, that the load vector makes with the horizontal
487
+ in the counter-clockwise direction. It takes the values 0 to 360,
488
+ inclusive.
489
+
490
+ Examples
491
+ ========
492
+
493
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
494
+ >>> from sympy import symbols
495
+ >>> t = Truss()
496
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0))
497
+ >>> P = symbols('P')
498
+ >>> t.apply_load(('A', P, 90), ('A', P/2, 45), ('A', P/4, 90))
499
+ >>> t.loads
500
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
501
+ """
502
+ for i in args:
503
+ location = i[0]
504
+ magnitude = i[1]
505
+ direction = i[2]
506
+ magnitude = sympify(magnitude)
507
+ direction = sympify(direction)
508
+
509
+ if location not in self._node_coordinates:
510
+ raise ValueError("Load must be applied at a known node")
511
+
512
+ else:
513
+ if location in self._loads:
514
+ self._loads[location].append([magnitude, direction])
515
+ else:
516
+ self._loads[location] = [[magnitude, direction]]
517
+
518
+ def remove_load(self, *args):
519
+ """
520
+ This method removes already
521
+ present external load(s) at specified node(s).
522
+
523
+ Parameters
524
+ ==========
525
+ The input(s) of this method are tuple(s) of the form (location, magnitude, direction).
526
+
527
+ location: String or Symbol
528
+ Label of the Node at which load is applied and is to be removed.
529
+
530
+ magnitude: Sympifyable
531
+ Magnitude of the load applied.
532
+
533
+ direction: Sympifyable
534
+ The angle, in degrees, that the load vector makes with the horizontal
535
+ in the counter-clockwise direction. It takes the values 0 to 360,
536
+ inclusive.
537
+
538
+ Examples
539
+ ========
540
+
541
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
542
+ >>> from sympy import symbols
543
+ >>> t = Truss()
544
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0))
545
+ >>> P = symbols('P')
546
+ >>> t.apply_load(('A', P, 90), ('A', P/2, 45), ('A', P/4, 90))
547
+ >>> t.loads
548
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
549
+ >>> t.remove_load(('A', P/4, 90), ('A', P/2, 45))
550
+ >>> t.loads
551
+ {'A': [[P, 90]]}
552
+ """
553
+ for i in args:
554
+ location = i[0]
555
+ magnitude = i[1]
556
+ direction = i[2]
557
+ magnitude = sympify(magnitude)
558
+ direction = sympify(direction)
559
+
560
+ if location not in self._node_coordinates:
561
+ raise ValueError("Load must be removed from a known node")
562
+
563
+ else:
564
+ if [magnitude, direction] not in self._loads[location]:
565
+ raise ValueError("No load of this magnitude and direction has been applied at this node")
566
+ else:
567
+ self._loads[location].remove([magnitude, direction])
568
+ if self._loads[location] == []:
569
+ self._loads.pop(location)
570
+
571
+ def apply_support(self, *args):
572
+ """
573
+ This method adds a pinned or roller support at specified node(s).
574
+
575
+ Parameters
576
+ ==========
577
+ The input(s) of this method are of the form (location, type).
578
+
579
+ location: String or Symbol
580
+ Label of the Node at which support is added.
581
+
582
+ type: String
583
+ Type of the support being provided at the node.
584
+
585
+ Examples
586
+ ========
587
+
588
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
589
+ >>> t = Truss()
590
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0))
591
+ >>> t.apply_support(('A', 'pinned'), ('B', 'roller'))
592
+ >>> t.supports
593
+ {'A': 'pinned', 'B': 'roller'}
594
+ """
595
+ for i in args:
596
+ location = i[0]
597
+ type = i[1]
598
+ if location not in self._node_coordinates:
599
+ raise ValueError("Support must be added on a known node")
600
+
601
+ else:
602
+ if location not in self._supports:
603
+ if type == 'pinned':
604
+ self.apply_load((location, Symbol('R_'+str(location)+'_x'), 0))
605
+ self.apply_load((location, Symbol('R_'+str(location)+'_y'), 90))
606
+ elif type == 'roller':
607
+ self.apply_load((location, Symbol('R_'+str(location)+'_y'), 90))
608
+ elif self._supports[location] == 'pinned':
609
+ if type == 'roller':
610
+ self.remove_load((location, Symbol('R_'+str(location)+'_x'), 0))
611
+ elif self._supports[location] == 'roller':
612
+ if type == 'pinned':
613
+ self.apply_load((location, Symbol('R_'+str(location)+'_x'), 0))
614
+ self._supports[location] = type
615
+
616
+ def remove_support(self, *args):
617
+ """
618
+ This method removes support from specified node(s.)
619
+
620
+ Parameters
621
+ ==========
622
+
623
+ locations: String or Symbol
624
+ Label of the Node(s) at which support is to be removed.
625
+
626
+ Examples
627
+ ========
628
+
629
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
630
+ >>> t = Truss()
631
+ >>> t.add_node(('A', 0, 0), ('B', 3, 0))
632
+ >>> t.apply_support(('A', 'pinned'), ('B', 'roller'))
633
+ >>> t.supports
634
+ {'A': 'pinned', 'B': 'roller'}
635
+ >>> t.remove_support('A','B')
636
+ >>> t.supports
637
+ {}
638
+ """
639
+ for location in args:
640
+
641
+ if location not in self._node_coordinates:
642
+ raise ValueError("No such node exists in the Truss")
643
+
644
+ elif location not in self._supports:
645
+ raise ValueError("No support has been added to the given node")
646
+
647
+ else:
648
+ if self._supports[location] == 'pinned':
649
+ self.remove_load((location, Symbol('R_'+str(location)+'_x'), 0))
650
+ self.remove_load((location, Symbol('R_'+str(location)+'_y'), 90))
651
+ elif self._supports[location] == 'roller':
652
+ self.remove_load((location, Symbol('R_'+str(location)+'_y'), 90))
653
+ self._supports.pop(location)
654
+
655
+ def solve(self):
656
+ """
657
+ This method solves for all reaction forces of all supports and all internal forces
658
+ of all the members in the truss, provided the Truss is solvable.
659
+
660
+ A Truss is solvable if the following condition is met,
661
+
662
+ 2n >= r + m
663
+
664
+ Where n is the number of nodes, r is the number of reaction forces, where each pinned
665
+ support has 2 reaction forces and each roller has 1, and m is the number of members.
666
+
667
+ The given condition is derived from the fact that a system of equations is solvable
668
+ only when the number of variables is lesser than or equal to the number of equations.
669
+ Equilibrium Equations in x and y directions give two equations per node giving 2n number
670
+ equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m.
671
+ The number of variables is simply the sum of the number of reaction forces and member
672
+ forces.
673
+
674
+ .. note::
675
+ The sign convention for the internal forces present in a member revolves around whether each
676
+ force is compressive or tensile. While forming equations for each node, internal force due
677
+ to a member on the node is assumed to be away from the node i.e. each force is assumed to
678
+ be compressive by default. Hence, a positive value for an internal force implies the
679
+ presence of compressive force in the member and a negative value implies a tensile force.
680
+
681
+ Examples
682
+ ========
683
+
684
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
685
+ >>> t = Truss()
686
+ >>> t.add_node(("node_1", 0, 0), ("node_2", 6, 0), ("node_3", 2, 2), ("node_4", 2, 0))
687
+ >>> t.add_member(("member_1", "node_1", "node_4"), ("member_2", "node_2", "node_4"), ("member_3", "node_1", "node_3"))
688
+ >>> t.add_member(("member_4", "node_2", "node_3"), ("member_5", "node_3", "node_4"))
689
+ >>> t.apply_load(("node_4", 10, 270))
690
+ >>> t.apply_support(("node_1", "pinned"), ("node_2", "roller"))
691
+ >>> t.solve()
692
+ >>> t.reaction_loads
693
+ {'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3}
694
+ >>> t.internal_forces
695
+ {'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10}
696
+ """
697
+ count_reaction_loads = 0
698
+ for node in self._nodes:
699
+ if node[0] in self._supports:
700
+ if self._supports[node[0]]=='pinned':
701
+ count_reaction_loads += 2
702
+ elif self._supports[node[0]]=='roller':
703
+ count_reaction_loads += 1
704
+ if 2*len(self._nodes) != len(self._members) + count_reaction_loads:
705
+ raise ValueError("The given truss cannot be solved")
706
+ coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))]
707
+ load_matrix = zeros(2*len(self.nodes), 1)
708
+ load_matrix_row = 0
709
+ for node in self._nodes:
710
+ if node[0] in self._loads:
711
+ for load in self._loads[node[0]]:
712
+ if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'):
713
+ load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180)
714
+ load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180)
715
+ load_matrix_row += 2
716
+ cols = 0
717
+ row = 0
718
+ for node in self._nodes:
719
+ if node[0] in self._supports:
720
+ if self._supports[node[0]]=='pinned':
721
+ coefficients_matrix[row][cols] += 1
722
+ coefficients_matrix[row+1][cols+1] += 1
723
+ cols += 2
724
+ elif self._supports[node[0]]=='roller':
725
+ coefficients_matrix[row+1][cols] += 1
726
+ cols += 1
727
+ row += 2
728
+ for member in self._members:
729
+ start = self._members[member][0]
730
+ end = self._members[member][1]
731
+ length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2)
732
+ start_index = self._node_labels.index(start)
733
+ end_index = self._node_labels.index(end)
734
+ horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length
735
+ vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length
736
+ horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length
737
+ vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length
738
+ coefficients_matrix[start_index*2][cols] += horizontal_component_start
739
+ coefficients_matrix[start_index*2+1][cols] += vertical_component_start
740
+ coefficients_matrix[end_index*2][cols] += horizontal_component_end
741
+ coefficients_matrix[end_index*2+1][cols] += vertical_component_end
742
+ cols += 1
743
+ forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix
744
+ self._reaction_loads = {}
745
+ i = 0
746
+ min_load = inf
747
+ for node in self._nodes:
748
+ if node[0] in self._loads:
749
+ for load in self._loads[node[0]]:
750
+ if type(load[0]) not in [Symbol, Mul, Add]:
751
+ min_load = min(min_load, load[0])
752
+ for j in range(len(forces_matrix)):
753
+ if type(forces_matrix[j]) not in [Symbol, Mul, Add]:
754
+ if abs(forces_matrix[j]/min_load) <1E-10:
755
+ forces_matrix[j] = 0
756
+ for node in self._nodes:
757
+ if node[0] in self._supports:
758
+ if self._supports[node[0]]=='pinned':
759
+ self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i]
760
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1]
761
+ i += 2
762
+ elif self._supports[node[0]]=='roller':
763
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i]
764
+ i += 1
765
+ for member in self._members:
766
+ self._internal_forces[member] = forces_matrix[i]
767
+ i += 1
768
+ return
769
+
770
+ @doctest_depends_on(modules=('numpy',))
771
+ def draw(self, subs_dict=None):
772
+ """
773
+ Returns a plot object of the Truss with all its nodes, members,
774
+ supports and loads.
775
+
776
+ .. note::
777
+ The user must be careful while entering load values in their
778
+ directions. The draw function assumes a sign convention that
779
+ is used for plotting loads.
780
+
781
+ Given a right-handed coordinate system with XYZ coordinates,
782
+ the supports are assumed to be such that the reaction forces of a
783
+ pinned support is in the +X and +Y direction while those of a
784
+ roller support is in the +Y direction. For the load, the range
785
+ of angles, one can input goes all the way to 360 degrees which, in the
786
+ the plot is the angle that the load vector makes with the positive x-axis in the anticlockwise direction.
787
+
788
+ For example, for a 90-degree angle, the load will be a vertically
789
+ directed along +Y while a 270-degree angle denotes a vertical
790
+ load as well but along -Y.
791
+
792
+ Examples
793
+ ========
794
+
795
+ .. plot::
796
+ :context: close-figs
797
+ :format: doctest
798
+ :include-source: True
799
+
800
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
801
+ >>> import math
802
+ >>> t = Truss()
803
+ >>> t.add_node(("A", -4, 0), ("B", 0, 0), ("C", 4, 0), ("D", 8, 0))
804
+ >>> t.add_node(("E", 6, 2/math.sqrt(3)))
805
+ >>> t.add_node(("F", 2, 2*math.sqrt(3)))
806
+ >>> t.add_node(("G", -2, 2/math.sqrt(3)))
807
+ >>> t.add_member(("AB","A","B"), ("BC","B","C"), ("CD","C","D"))
808
+ >>> t.add_member(("AG","A","G"), ("GB","G","B"), ("GF","G","F"))
809
+ >>> t.add_member(("BF","B","F"), ("FC","F","C"), ("CE","C","E"))
810
+ >>> t.add_member(("FE","F","E"), ("DE","D","E"))
811
+ >>> t.apply_support(("A","pinned"), ("D","roller"))
812
+ >>> t.apply_load(("G", 3, 90), ("E", 3, 90), ("F", 2, 90))
813
+ >>> p = t.draw()
814
+ >>> p # doctest: +ELLIPSIS
815
+ Plot object containing:
816
+ [0]: cartesian line: 1 for x over (1.0, 1.0)
817
+ ...
818
+ >>> p.show()
819
+ """
820
+ if not numpy:
821
+ raise ImportError("To use this function numpy module is required")
822
+
823
+ x = Symbol('x')
824
+
825
+ markers = []
826
+ annotations = []
827
+ rectangles = []
828
+
829
+ node_markers = self._draw_nodes(subs_dict)
830
+ markers += node_markers
831
+
832
+ member_rectangles = self._draw_members()
833
+ rectangles += member_rectangles
834
+
835
+ support_markers = self._draw_supports()
836
+ markers += support_markers
837
+
838
+ load_annotations = self._draw_loads()
839
+ annotations += load_annotations
840
+
841
+ xmax = -INF
842
+ xmin = INF
843
+ ymax = -INF
844
+ ymin = INF
845
+
846
+ for node in self._node_coordinates:
847
+ xmax = max(xmax, self._node_coordinates[node][0])
848
+ xmin = min(xmin, self._node_coordinates[node][0])
849
+ ymax = max(ymax, self._node_coordinates[node][1])
850
+ ymin = min(ymin, self._node_coordinates[node][1])
851
+
852
+ lim = max(xmax*1.1-xmin*0.8+1, ymax*1.1-ymin*0.8+1)
853
+
854
+ if lim==xmax*1.1-xmin*0.8+1:
855
+ sing_plot = plot(1, (x, 1, 1), markers=markers, show=False, annotations=annotations, xlim=(xmin-0.05*lim, xmax*1.1), ylim=(xmin-0.05*lim, xmax*1.1), axis=False, rectangles=rectangles)
856
+
857
+ else:
858
+ sing_plot = plot(1, (x, 1, 1), markers=markers, show=False, annotations=annotations, xlim=(ymin-0.05*lim, ymax*1.1), ylim=(ymin-0.05*lim, ymax*1.1), axis=False, rectangles=rectangles)
859
+
860
+ return sing_plot
861
+
862
+
863
+ def _draw_nodes(self, subs_dict):
864
+ node_markers = []
865
+
866
+ for node in self._node_coordinates:
867
+ if (type(self._node_coordinates[node][0]) in (Symbol, Quantity)):
868
+ if self._node_coordinates[node][0] in subs_dict:
869
+ self._node_coordinates[node][0] = subs_dict[self._node_coordinates[node][0]]
870
+ else:
871
+ raise ValueError("provided substituted dictionary is not adequate")
872
+ elif (type(self._node_coordinates[node][0]) == Mul):
873
+ objects = self._node_coordinates[node][0].as_coeff_Mul()
874
+ for object in objects:
875
+ if type(object) in (Symbol, Quantity):
876
+ if subs_dict==None or object not in subs_dict:
877
+ raise ValueError("provided substituted dictionary is not adequate")
878
+ else:
879
+ self._node_coordinates[node][0] /= object
880
+ self._node_coordinates[node][0] *= subs_dict[object]
881
+
882
+ if (type(self._node_coordinates[node][1]) in (Symbol, Quantity)):
883
+ if self._node_coordinates[node][1] in subs_dict:
884
+ self._node_coordinates[node][1] = subs_dict[self._node_coordinates[node][1]]
885
+ else:
886
+ raise ValueError("provided substituted dictionary is not adequate")
887
+ elif (type(self._node_coordinates[node][1]) == Mul):
888
+ objects = self._node_coordinates[node][1].as_coeff_Mul()
889
+ for object in objects:
890
+ if type(object) in (Symbol, Quantity):
891
+ if subs_dict==None or object not in subs_dict:
892
+ raise ValueError("provided substituted dictionary is not adequate")
893
+ else:
894
+ self._node_coordinates[node][1] /= object
895
+ self._node_coordinates[node][1] *= subs_dict[object]
896
+
897
+ for node in self._node_coordinates:
898
+ node_markers.append(
899
+ {
900
+ 'args':[[self._node_coordinates[node][0]], [self._node_coordinates[node][1]]],
901
+ 'marker':'o',
902
+ 'markersize':5,
903
+ 'color':'black'
904
+ }
905
+ )
906
+ return node_markers
907
+
908
+ def _draw_members(self):
909
+
910
+ member_rectangles = []
911
+
912
+ xmax = -INF
913
+ xmin = INF
914
+ ymax = -INF
915
+ ymin = INF
916
+
917
+ for node in self._node_coordinates:
918
+ xmax = max(xmax, self._node_coordinates[node][0])
919
+ xmin = min(xmin, self._node_coordinates[node][0])
920
+ ymax = max(ymax, self._node_coordinates[node][1])
921
+ ymin = min(ymin, self._node_coordinates[node][1])
922
+
923
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
924
+ max_diff = 1.1*xmax-0.8*xmin
925
+ else:
926
+ max_diff = 1.1*ymax-0.8*ymin
927
+
928
+ for member in self._members:
929
+ x1 = self._node_coordinates[self._members[member][0]][0]
930
+ y1 = self._node_coordinates[self._members[member][0]][1]
931
+ x2 = self._node_coordinates[self._members[member][1]][0]
932
+ y2 = self._node_coordinates[self._members[member][1]][1]
933
+ if x2!=x1 and y2!=y1:
934
+ if x2>x1:
935
+ member_rectangles.append(
936
+ {
937
+ 'xy':(x1-0.005*max_diff*cos(pi/4+atan((y2-y1)/(x2-x1)))/2, y1-0.005*max_diff*sin(pi/4+atan((y2-y1)/(x2-x1)))/2),
938
+ 'width':sqrt((x1-x2)**2+(y1-y2)**2)+0.005*max_diff/math.sqrt(2),
939
+ 'height':0.005*max_diff,
940
+ 'angle':180*atan((y2-y1)/(x2-x1))/pi,
941
+ 'color':'brown'
942
+ }
943
+ )
944
+ else:
945
+ member_rectangles.append(
946
+ {
947
+ 'xy':(x2-0.005*max_diff*cos(pi/4+atan((y2-y1)/(x2-x1)))/2, y2-0.005*max_diff*sin(pi/4+atan((y2-y1)/(x2-x1)))/2),
948
+ 'width':sqrt((x1-x2)**2+(y1-y2)**2)+0.005*max_diff/math.sqrt(2),
949
+ 'height':0.005*max_diff,
950
+ 'angle':180*atan((y2-y1)/(x2-x1))/pi,
951
+ 'color':'brown'
952
+ }
953
+ )
954
+ elif y2==y1:
955
+ if x2>x1:
956
+ member_rectangles.append(
957
+ {
958
+ 'xy':(x1-0.005*max_diff/2, y1-0.005*max_diff/2),
959
+ 'width':sqrt((x1-x2)**2+(y1-y2)**2),
960
+ 'height':0.005*max_diff,
961
+ 'angle':90*(1-math.copysign(1, x2-x1)),
962
+ 'color':'brown'
963
+ }
964
+ )
965
+ else:
966
+ member_rectangles.append(
967
+ {
968
+ 'xy':(x1-0.005*max_diff/2, y1-0.005*max_diff/2),
969
+ 'width':sqrt((x1-x2)**2+(y1-y2)**2),
970
+ 'height':-0.005*max_diff,
971
+ 'angle':90*(1-math.copysign(1, x2-x1)),
972
+ 'color':'brown'
973
+ }
974
+ )
975
+ else:
976
+ if y1<y2:
977
+ member_rectangles.append(
978
+ {
979
+ 'xy':(x1-0.005*max_diff/2, y1-0.005*max_diff/2),
980
+ 'width':sqrt((x1-x2)**2+(y1-y2)**2)+0.005*max_diff/2,
981
+ 'height':0.005*max_diff,
982
+ 'angle':90*math.copysign(1, y2-y1),
983
+ 'color':'brown'
984
+ }
985
+ )
986
+ else:
987
+ member_rectangles.append(
988
+ {
989
+ 'xy':(x2-0.005*max_diff/2, y2-0.005*max_diff/2),
990
+ 'width':-(sqrt((x1-x2)**2+(y1-y2)**2)+0.005*max_diff/2),
991
+ 'height':0.005*max_diff,
992
+ 'angle':90*math.copysign(1, y2-y1),
993
+ 'color':'brown'
994
+ }
995
+ )
996
+
997
+ return member_rectangles
998
+
999
+ def _draw_supports(self):
1000
+ support_markers = []
1001
+
1002
+ xmax = -INF
1003
+ xmin = INF
1004
+ ymax = -INF
1005
+ ymin = INF
1006
+
1007
+ for node in self._node_coordinates:
1008
+ xmax = max(xmax, self._node_coordinates[node][0])
1009
+ xmin = min(xmin, self._node_coordinates[node][0])
1010
+ ymax = max(ymax, self._node_coordinates[node][1])
1011
+ ymin = min(ymin, self._node_coordinates[node][1])
1012
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
1013
+ max_diff = 1.1*xmax-0.8*xmin
1014
+ else:
1015
+ max_diff = 1.1*ymax-0.8*ymin
1016
+
1017
+ for node in self._supports:
1018
+ if self._supports[node]=='pinned':
1019
+ support_markers.append(
1020
+ {
1021
+ 'args':[
1022
+ [self._node_coordinates[node][0]],
1023
+ [self._node_coordinates[node][1]]
1024
+ ],
1025
+ 'marker':6,
1026
+ 'markersize':15,
1027
+ 'color':'black',
1028
+ 'markerfacecolor':'none'
1029
+ }
1030
+ )
1031
+ support_markers.append(
1032
+ {
1033
+ 'args':[
1034
+ [self._node_coordinates[node][0]],
1035
+ [self._node_coordinates[node][1]-0.035*max_diff]
1036
+ ],
1037
+ 'marker':'_',
1038
+ 'markersize':14,
1039
+ 'color':'black'
1040
+ }
1041
+ )
1042
+
1043
+ elif self._supports[node]=='roller':
1044
+ support_markers.append(
1045
+ {
1046
+ 'args':[
1047
+ [self._node_coordinates[node][0]],
1048
+ [self._node_coordinates[node][1]-0.02*max_diff]
1049
+ ],
1050
+ 'marker':'o',
1051
+ 'markersize':11,
1052
+ 'color':'black',
1053
+ 'markerfacecolor':'none'
1054
+ }
1055
+ )
1056
+ support_markers.append(
1057
+ {
1058
+ 'args':[
1059
+ [self._node_coordinates[node][0]],
1060
+ [self._node_coordinates[node][1]-0.0375*max_diff]
1061
+ ],
1062
+ 'marker':'_',
1063
+ 'markersize':14,
1064
+ 'color':'black'
1065
+ }
1066
+ )
1067
+ return support_markers
1068
+
1069
+ def _draw_loads(self):
1070
+ load_annotations = []
1071
+
1072
+ xmax = -INF
1073
+ xmin = INF
1074
+ ymax = -INF
1075
+ ymin = INF
1076
+
1077
+ for node in self._node_coordinates:
1078
+ xmax = max(xmax, self._node_coordinates[node][0])
1079
+ xmin = min(xmin, self._node_coordinates[node][0])
1080
+ ymax = max(ymax, self._node_coordinates[node][1])
1081
+ ymin = min(ymin, self._node_coordinates[node][1])
1082
+
1083
+ if abs(1.1*xmax-0.8*xmin)>abs(1.1*ymax-0.8*ymin):
1084
+ max_diff = 1.1*xmax-0.8*xmin+5
1085
+ else:
1086
+ max_diff = 1.1*ymax-0.8*ymin+5
1087
+
1088
+ for node in self._loads:
1089
+ for load in self._loads[node]:
1090
+ if load[0] in [Symbol('R_'+str(node)+'_x'), Symbol('R_'+str(node)+'_y')]:
1091
+ continue
1092
+ x = self._node_coordinates[node][0]
1093
+ y = self._node_coordinates[node][1]
1094
+ load_annotations.append(
1095
+ {
1096
+ 'text':'',
1097
+ 'xy':(
1098
+ x-math.cos(pi*load[1]/180)*(max_diff/100),
1099
+ y-math.sin(pi*load[1]/180)*(max_diff/100)
1100
+ ),
1101
+ 'xytext':(
1102
+ x-(max_diff/100+abs(xmax-xmin)+abs(ymax-ymin))*math.cos(pi*load[1]/180)/20,
1103
+ y-(max_diff/100+abs(xmax-xmin)+abs(ymax-ymin))*math.sin(pi*load[1]/180)/20
1104
+ ),
1105
+ 'arrowprops':{'width':1.5, 'headlength':5, 'headwidth':5, 'facecolor':'black'}
1106
+ }
1107
+ )
1108
+ return load_annotations
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lti import (TransferFunction, PIDController, Series, MIMOSeries, Parallel, MIMOParallel,
2
+ Feedback, MIMOFeedback, TransferFunctionMatrix, StateSpace, gbt, bilinear, forward_diff,
3
+ backward_diff, phase_margin, gain_margin)
4
+ from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
5
+ step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
6
+ ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
7
+ bode_phase_plot, bode_plot, nyquist_plot_expr, nyquist_plot, nichols_plot_expr, nichols_plot)
8
+
9
+ __all__ = ['TransferFunction', 'PIDController', 'Series', 'MIMOSeries', 'Parallel',
10
+ 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix', 'StateSpace',
11
+ 'gbt', 'bilinear', 'forward_diff', 'backward_diff', 'phase_margin', 'gain_margin',
12
+ 'pole_zero_numerical_data', 'pole_zero_plot', 'step_response_numerical_data',
13
+ 'step_response_plot', 'impulse_response_numerical_data', 'impulse_response_plot',
14
+ 'ramp_response_numerical_data', 'ramp_response_plot',
15
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
16
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot', 'nyquist_plot_expr', 'nyquist_plot',
17
+ 'nichols_plot_expr', 'nichols_plot']
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/control_plots.py ADDED
@@ -0,0 +1,1135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I, pi
2
+ from sympy.functions.elementary.exponential import (exp, log)
3
+ from sympy.polys.partfrac import apart
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.external import import_module
6
+ from sympy.functions import arg, Abs
7
+ from sympy.integrals.laplace import _fast_inverse_laplace
8
+ from sympy.physics.control.lti import SISOLinearTimeInvariant
9
+ from sympy.plotting.series import LineOver1DRangeSeries
10
+ from sympy.plotting.plot import plot_parametric
11
+ from sympy.polys.domains import ZZ, QQ
12
+ from sympy.polys.polytools import Poly
13
+ from sympy.printing.latex import latex
14
+ from sympy.geometry.polygon import deg
15
+
16
+ __all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
17
+ 'step_response_numerical_data', 'step_response_plot',
18
+ 'impulse_response_numerical_data', 'impulse_response_plot',
19
+ 'ramp_response_numerical_data', 'ramp_response_plot',
20
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
21
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot',
22
+ 'nyquist_plot_expr', 'nyquist_plot', 'nichols_plot_expr',
23
+ 'nichols_plot']
24
+
25
+
26
+ matplotlib = import_module(
27
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
28
+ catch=(RuntimeError,))
29
+
30
+ if matplotlib:
31
+ plt = matplotlib.pyplot
32
+
33
+
34
+ def _check_system(system):
35
+ """Function to check whether the dynamical system passed for plots is
36
+ compatible or not."""
37
+ if not isinstance(system, SISOLinearTimeInvariant):
38
+ raise NotImplementedError("Only SISO LTI systems are currently supported.")
39
+ sys = system.to_expr()
40
+ len_free_symbols = len(sys.free_symbols)
41
+ if len_free_symbols > 1:
42
+ raise ValueError("Extra degree of freedom found. Make sure"
43
+ " that there are no free symbols in the dynamical system other"
44
+ " than the variable of Laplace transform.")
45
+ if sys.has(exp):
46
+ # Should test that exp is not part of a constant, in which case
47
+ # no exception is required, compare exp(s) with s*exp(1)
48
+ raise NotImplementedError("Time delay terms are not supported.")
49
+
50
+
51
+ def _poly_roots(poly):
52
+ """Function to get the roots of a polynomial."""
53
+ def _eval(l):
54
+ return [float(i) if i.is_real else complex(i) for i in l]
55
+ if poly.domain in (QQ, ZZ):
56
+ return _eval(poly.all_roots())
57
+ # XXX: Use all_roots() for irrational coefficients when possible
58
+ # See https://github.com/sympy/sympy/issues/22943
59
+ return _eval(poly.nroots())
60
+
61
+
62
+ def pole_zero_numerical_data(system):
63
+ """
64
+ Returns the numerical data of poles and zeros of the system.
65
+ It is internally used by ``pole_zero_plot`` to get the data
66
+ for plotting poles and zeros. Users can use this data to further
67
+ analyse the dynamics of the system or plot using a different
68
+ backend/plotting-module.
69
+
70
+ Parameters
71
+ ==========
72
+
73
+ system : SISOLinearTimeInvariant
74
+ The system for which the pole-zero data is to be computed.
75
+
76
+ Returns
77
+ =======
78
+
79
+ tuple : (zeros, poles)
80
+ zeros = Zeros of the system as a list of Python float/complex.
81
+ poles = Poles of the system as a list of Python float/complex.
82
+
83
+ Raises
84
+ ======
85
+
86
+ NotImplementedError
87
+ When a SISO LTI system is not passed.
88
+
89
+ When time delay terms are present in the system.
90
+
91
+ ValueError
92
+ When more than one free symbol is present in the system.
93
+ The only variable in the transfer function should be
94
+ the variable of the Laplace transform.
95
+
96
+ Examples
97
+ ========
98
+
99
+ >>> from sympy.abc import s
100
+ >>> from sympy.physics.control.lti import TransferFunction
101
+ >>> from sympy.physics.control.control_plots import pole_zero_numerical_data
102
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
103
+ >>> pole_zero_numerical_data(tf1)
104
+ ([-1j, 1j], [-2.0, -1.0, (-0.5-0.8660254037844386j), (-0.5+0.8660254037844386j)])
105
+
106
+ See Also
107
+ ========
108
+
109
+ pole_zero_plot
110
+
111
+ """
112
+ _check_system(system)
113
+ system = system.doit() # Get the equivalent TransferFunction object.
114
+
115
+ num_poly = Poly(system.num, system.var)
116
+ den_poly = Poly(system.den, system.var)
117
+
118
+ return _poly_roots(num_poly), _poly_roots(den_poly)
119
+
120
+
121
+ def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
122
+ zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
123
+ show=True, **kwargs):
124
+ r"""
125
+ Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
126
+
127
+ A Pole-Zero plot is a graphical representation of a system's poles and
128
+ zeros. It is plotted on a complex plane, with circular markers representing
129
+ the system's zeros and 'x' shaped markers representing the system's poles.
130
+
131
+ Parameters
132
+ ==========
133
+
134
+ system : SISOLinearTimeInvariant type systems
135
+ The system for which the pole-zero plot is to be computed.
136
+ pole_color : str, tuple, optional
137
+ The color of the pole points on the plot. Default color
138
+ is blue. The color can be provided as a matplotlib color string,
139
+ or a 3-tuple of floats each in the 0-1 range.
140
+ pole_markersize : Number, optional
141
+ The size of the markers used to mark the poles in the plot.
142
+ Default pole markersize is 10.
143
+ zero_color : str, tuple, optional
144
+ The color of the zero points on the plot. Default color
145
+ is orange. The color can be provided as a matplotlib color string,
146
+ or a 3-tuple of floats each in the 0-1 range.
147
+ zero_markersize : Number, optional
148
+ The size of the markers used to mark the zeros in the plot.
149
+ Default zero markersize is 7.
150
+ grid : boolean, optional
151
+ If ``True``, the plot will have a grid. Defaults to True.
152
+ show_axes : boolean, optional
153
+ If ``True``, the coordinate axes will be shown. Defaults to False.
154
+ show : boolean, optional
155
+ If ``True``, the plot will be displayed otherwise
156
+ the equivalent matplotlib ``plot`` object will be returned.
157
+ Defaults to True.
158
+
159
+ Examples
160
+ ========
161
+
162
+ .. plot::
163
+ :context: close-figs
164
+ :format: doctest
165
+ :include-source: True
166
+
167
+ >>> from sympy.abc import s
168
+ >>> from sympy.physics.control.lti import TransferFunction
169
+ >>> from sympy.physics.control.control_plots import pole_zero_plot
170
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
171
+ >>> pole_zero_plot(tf1) # doctest: +SKIP
172
+
173
+ See Also
174
+ ========
175
+
176
+ pole_zero_numerical_data
177
+
178
+ References
179
+ ==========
180
+
181
+ .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
182
+
183
+ """
184
+ zeros, poles = pole_zero_numerical_data(system)
185
+
186
+ zero_real = [i.real for i in zeros]
187
+ zero_imag = [i.imag for i in zeros]
188
+
189
+ pole_real = [i.real for i in poles]
190
+ pole_imag = [i.imag for i in poles]
191
+
192
+ plt.plot(pole_real, pole_imag, 'x', mfc='none',
193
+ markersize=pole_markersize, color=pole_color)
194
+ plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
195
+ color=zero_color)
196
+ plt.xlabel('Real Axis')
197
+ plt.ylabel('Imaginary Axis')
198
+ plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
199
+
200
+ if grid:
201
+ plt.grid()
202
+ if show_axes:
203
+ plt.axhline(0, color='black')
204
+ plt.axvline(0, color='black')
205
+ if show:
206
+ plt.show()
207
+ return
208
+
209
+ return plt
210
+
211
+
212
+ def step_response_numerical_data(system, prec=8, lower_limit=0,
213
+ upper_limit=10, **kwargs):
214
+ """
215
+ Returns the numerical values of the points in the step response plot
216
+ of a SISO continuous-time system. By default, adaptive sampling
217
+ is used. If the user wants to instead get an uniformly
218
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
219
+ and ``n`` must be passed as additional kwargs.
220
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
221
+ for more details.
222
+
223
+ Parameters
224
+ ==========
225
+
226
+ system : SISOLinearTimeInvariant
227
+ The system for which the unit step response data is to be computed.
228
+ prec : int, optional
229
+ The decimal point precision for the point coordinate values.
230
+ Defaults to 8.
231
+ lower_limit : Number, optional
232
+ The lower limit of the plot range. Defaults to 0.
233
+ upper_limit : Number, optional
234
+ The upper limit of the plot range. Defaults to 10.
235
+ kwargs :
236
+ Additional keyword arguments are passed to the underlying
237
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
238
+
239
+ Returns
240
+ =======
241
+
242
+ tuple : (x, y)
243
+ x = Time-axis values of the points in the step response. NumPy array.
244
+ y = Amplitude-axis values of the points in the step response. NumPy array.
245
+
246
+ Raises
247
+ ======
248
+
249
+ NotImplementedError
250
+ When a SISO LTI system is not passed.
251
+
252
+ When time delay terms are present in the system.
253
+
254
+ ValueError
255
+ When more than one free symbol is present in the system.
256
+ The only variable in the transfer function should be
257
+ the variable of the Laplace transform.
258
+
259
+ When ``lower_limit`` parameter is less than 0.
260
+
261
+ Examples
262
+ ========
263
+
264
+ >>> from sympy.abc import s
265
+ >>> from sympy.physics.control.lti import TransferFunction
266
+ >>> from sympy.physics.control.control_plots import step_response_numerical_data
267
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
268
+ >>> step_response_numerical_data(tf1) # doctest: +SKIP
269
+ ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
270
+ [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
271
+
272
+ See Also
273
+ ========
274
+
275
+ step_response_plot
276
+
277
+ """
278
+ if lower_limit < 0:
279
+ raise ValueError("Lower limit of time must be greater "
280
+ "than or equal to zero.")
281
+ _check_system(system)
282
+ _x = Dummy("x")
283
+ expr = system.to_expr()/(system.var)
284
+ expr = apart(expr, system.var, full=True)
285
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
286
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
287
+ **kwargs).get_points()
288
+
289
+
290
+ def step_response_plot(system, color='b', prec=8, lower_limit=0,
291
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
292
+ r"""
293
+ Returns the unit step response of a continuous-time system. It is
294
+ the response of the system when the input signal is a step function.
295
+
296
+ Parameters
297
+ ==========
298
+
299
+ system : SISOLinearTimeInvariant type
300
+ The LTI SISO system for which the Step Response is to be computed.
301
+ color : str, tuple, optional
302
+ The color of the line. Default is Blue.
303
+ show : boolean, optional
304
+ If ``True``, the plot will be displayed otherwise
305
+ the equivalent matplotlib ``plot`` object will be returned.
306
+ Defaults to True.
307
+ lower_limit : Number, optional
308
+ The lower limit of the plot range. Defaults to 0.
309
+ upper_limit : Number, optional
310
+ The upper limit of the plot range. Defaults to 10.
311
+ prec : int, optional
312
+ The decimal point precision for the point coordinate values.
313
+ Defaults to 8.
314
+ show_axes : boolean, optional
315
+ If ``True``, the coordinate axes will be shown. Defaults to False.
316
+ grid : boolean, optional
317
+ If ``True``, the plot will have a grid. Defaults to True.
318
+
319
+ Examples
320
+ ========
321
+
322
+ .. plot::
323
+ :context: close-figs
324
+ :format: doctest
325
+ :include-source: True
326
+
327
+ >>> from sympy.abc import s
328
+ >>> from sympy.physics.control.lti import TransferFunction
329
+ >>> from sympy.physics.control.control_plots import step_response_plot
330
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
331
+ >>> step_response_plot(tf1) # doctest: +SKIP
332
+
333
+ See Also
334
+ ========
335
+
336
+ impulse_response_plot, ramp_response_plot
337
+
338
+ References
339
+ ==========
340
+
341
+ .. [1] https://www.mathworks.com/help/control/ref/lti.step.html
342
+
343
+ """
344
+ x, y = step_response_numerical_data(system, prec=prec,
345
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
346
+ plt.plot(x, y, color=color)
347
+ plt.xlabel('Time (s)')
348
+ plt.ylabel('Amplitude')
349
+ plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
350
+
351
+ if grid:
352
+ plt.grid()
353
+ if show_axes:
354
+ plt.axhline(0, color='black')
355
+ plt.axvline(0, color='black')
356
+ if show:
357
+ plt.show()
358
+ return
359
+
360
+ return plt
361
+
362
+
363
+ def impulse_response_numerical_data(system, prec=8, lower_limit=0,
364
+ upper_limit=10, **kwargs):
365
+ """
366
+ Returns the numerical values of the points in the impulse response plot
367
+ of a SISO continuous-time system. By default, adaptive sampling
368
+ is used. If the user wants to instead get an uniformly
369
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
370
+ and ``n`` must be passed as additional kwargs.
371
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
372
+ for more details.
373
+
374
+ Parameters
375
+ ==========
376
+
377
+ system : SISOLinearTimeInvariant
378
+ The system for which the impulse response data is to be computed.
379
+ prec : int, optional
380
+ The decimal point precision for the point coordinate values.
381
+ Defaults to 8.
382
+ lower_limit : Number, optional
383
+ The lower limit of the plot range. Defaults to 0.
384
+ upper_limit : Number, optional
385
+ The upper limit of the plot range. Defaults to 10.
386
+ kwargs :
387
+ Additional keyword arguments are passed to the underlying
388
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
389
+
390
+ Returns
391
+ =======
392
+
393
+ tuple : (x, y)
394
+ x = Time-axis values of the points in the impulse response. NumPy array.
395
+ y = Amplitude-axis values of the points in the impulse response. NumPy array.
396
+
397
+ Raises
398
+ ======
399
+
400
+ NotImplementedError
401
+ When a SISO LTI system is not passed.
402
+
403
+ When time delay terms are present in the system.
404
+
405
+ ValueError
406
+ When more than one free symbol is present in the system.
407
+ The only variable in the transfer function should be
408
+ the variable of the Laplace transform.
409
+
410
+ When ``lower_limit`` parameter is less than 0.
411
+
412
+ Examples
413
+ ========
414
+
415
+ >>> from sympy.abc import s
416
+ >>> from sympy.physics.control.lti import TransferFunction
417
+ >>> from sympy.physics.control.control_plots import impulse_response_numerical_data
418
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
419
+ >>> impulse_response_numerical_data(tf1) # doctest: +SKIP
420
+ ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
421
+ [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
422
+
423
+ See Also
424
+ ========
425
+
426
+ impulse_response_plot
427
+
428
+ """
429
+ if lower_limit < 0:
430
+ raise ValueError("Lower limit of time must be greater "
431
+ "than or equal to zero.")
432
+ _check_system(system)
433
+ _x = Dummy("x")
434
+ expr = system.to_expr()
435
+ expr = apart(expr, system.var, full=True)
436
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
437
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
438
+ **kwargs).get_points()
439
+
440
+
441
+ def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
442
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
443
+ r"""
444
+ Returns the unit impulse response (Input is the Dirac-Delta Function) of a
445
+ continuous-time system.
446
+
447
+ Parameters
448
+ ==========
449
+
450
+ system : SISOLinearTimeInvariant type
451
+ The LTI SISO system for which the Impulse Response is to be computed.
452
+ color : str, tuple, optional
453
+ The color of the line. Default is Blue.
454
+ show : boolean, optional
455
+ If ``True``, the plot will be displayed otherwise
456
+ the equivalent matplotlib ``plot`` object will be returned.
457
+ Defaults to True.
458
+ lower_limit : Number, optional
459
+ The lower limit of the plot range. Defaults to 0.
460
+ upper_limit : Number, optional
461
+ The upper limit of the plot range. Defaults to 10.
462
+ prec : int, optional
463
+ The decimal point precision for the point coordinate values.
464
+ Defaults to 8.
465
+ show_axes : boolean, optional
466
+ If ``True``, the coordinate axes will be shown. Defaults to False.
467
+ grid : boolean, optional
468
+ If ``True``, the plot will have a grid. Defaults to True.
469
+
470
+ Examples
471
+ ========
472
+
473
+ .. plot::
474
+ :context: close-figs
475
+ :format: doctest
476
+ :include-source: True
477
+
478
+ >>> from sympy.abc import s
479
+ >>> from sympy.physics.control.lti import TransferFunction
480
+ >>> from sympy.physics.control.control_plots import impulse_response_plot
481
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
482
+ >>> impulse_response_plot(tf1) # doctest: +SKIP
483
+
484
+ See Also
485
+ ========
486
+
487
+ step_response_plot, ramp_response_plot
488
+
489
+ References
490
+ ==========
491
+
492
+ .. [1] https://www.mathworks.com/help/control/ref/dynamicsystem.impulse.html
493
+
494
+ """
495
+ x, y = impulse_response_numerical_data(system, prec=prec,
496
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
497
+ plt.plot(x, y, color=color)
498
+ plt.xlabel('Time (s)')
499
+ plt.ylabel('Amplitude')
500
+ plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
501
+
502
+ if grid:
503
+ plt.grid()
504
+ if show_axes:
505
+ plt.axhline(0, color='black')
506
+ plt.axvline(0, color='black')
507
+ if show:
508
+ plt.show()
509
+ return
510
+
511
+ return plt
512
+
513
+
514
+ def ramp_response_numerical_data(system, slope=1, prec=8,
515
+ lower_limit=0, upper_limit=10, **kwargs):
516
+ """
517
+ Returns the numerical values of the points in the ramp response plot
518
+ of a SISO continuous-time system. By default, adaptive sampling
519
+ is used. If the user wants to instead get an uniformly
520
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
521
+ and ``n`` must be passed as additional kwargs.
522
+ Refer to the parameters of class :class:`sympy.plotting.series.LineOver1DRangeSeries`
523
+ for more details.
524
+
525
+ Parameters
526
+ ==========
527
+
528
+ system : SISOLinearTimeInvariant
529
+ The system for which the ramp response data is to be computed.
530
+ slope : Number, optional
531
+ The slope of the input ramp function. Defaults to 1.
532
+ prec : int, optional
533
+ The decimal point precision for the point coordinate values.
534
+ Defaults to 8.
535
+ lower_limit : Number, optional
536
+ The lower limit of the plot range. Defaults to 0.
537
+ upper_limit : Number, optional
538
+ The upper limit of the plot range. Defaults to 10.
539
+ kwargs :
540
+ Additional keyword arguments are passed to the underlying
541
+ :class:`sympy.plotting.series.LineOver1DRangeSeries` class.
542
+
543
+ Returns
544
+ =======
545
+
546
+ tuple : (x, y)
547
+ x = Time-axis values of the points in the ramp response plot. NumPy array.
548
+ y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
549
+
550
+ Raises
551
+ ======
552
+
553
+ NotImplementedError
554
+ When a SISO LTI system is not passed.
555
+
556
+ When time delay terms are present in the system.
557
+
558
+ ValueError
559
+ When more than one free symbol is present in the system.
560
+ The only variable in the transfer function should be
561
+ the variable of the Laplace transform.
562
+
563
+ When ``lower_limit`` parameter is less than 0.
564
+
565
+ When ``slope`` is negative.
566
+
567
+ Examples
568
+ ========
569
+
570
+ >>> from sympy.abc import s
571
+ >>> from sympy.physics.control.lti import TransferFunction
572
+ >>> from sympy.physics.control.control_plots import ramp_response_numerical_data
573
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
574
+ >>> ramp_response_numerical_data(tf1) # doctest: +SKIP
575
+ (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
576
+ [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
577
+
578
+ See Also
579
+ ========
580
+
581
+ ramp_response_plot
582
+
583
+ """
584
+ if slope < 0:
585
+ raise ValueError("Slope must be greater than or equal"
586
+ " to zero.")
587
+ if lower_limit < 0:
588
+ raise ValueError("Lower limit of time must be greater "
589
+ "than or equal to zero.")
590
+ _check_system(system)
591
+ _x = Dummy("x")
592
+ expr = (slope*system.to_expr())/((system.var)**2)
593
+ expr = apart(expr, system.var, full=True)
594
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
595
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
596
+ **kwargs).get_points()
597
+
598
+
599
+ def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
600
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
601
+ r"""
602
+ Returns the ramp response of a continuous-time system.
603
+
604
+ Ramp function is defined as the straight line
605
+ passing through origin ($f(x) = mx$). The slope of
606
+ the ramp function can be varied by the user and
607
+ the default value is 1.
608
+
609
+ Parameters
610
+ ==========
611
+
612
+ system : SISOLinearTimeInvariant type
613
+ The LTI SISO system for which the Ramp Response is to be computed.
614
+ slope : Number, optional
615
+ The slope of the input ramp function. Defaults to 1.
616
+ color : str, tuple, optional
617
+ The color of the line. Default is Blue.
618
+ show : boolean, optional
619
+ If ``True``, the plot will be displayed otherwise
620
+ the equivalent matplotlib ``plot`` object will be returned.
621
+ Defaults to True.
622
+ lower_limit : Number, optional
623
+ The lower limit of the plot range. Defaults to 0.
624
+ upper_limit : Number, optional
625
+ The upper limit of the plot range. Defaults to 10.
626
+ prec : int, optional
627
+ The decimal point precision for the point coordinate values.
628
+ Defaults to 8.
629
+ show_axes : boolean, optional
630
+ If ``True``, the coordinate axes will be shown. Defaults to False.
631
+ grid : boolean, optional
632
+ If ``True``, the plot will have a grid. Defaults to True.
633
+
634
+ Examples
635
+ ========
636
+
637
+ .. plot::
638
+ :context: close-figs
639
+ :format: doctest
640
+ :include-source: True
641
+
642
+ >>> from sympy.abc import s
643
+ >>> from sympy.physics.control.lti import TransferFunction
644
+ >>> from sympy.physics.control.control_plots import ramp_response_plot
645
+ >>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
646
+ >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
647
+
648
+ See Also
649
+ ========
650
+
651
+ step_response_plot, impulse_response_plot
652
+
653
+ References
654
+ ==========
655
+
656
+ .. [1] https://en.wikipedia.org/wiki/Ramp_function
657
+
658
+ """
659
+ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
660
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
661
+ plt.plot(x, y, color=color)
662
+ plt.xlabel('Time (s)')
663
+ plt.ylabel('Amplitude')
664
+ plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
665
+
666
+ if grid:
667
+ plt.grid()
668
+ if show_axes:
669
+ plt.axhline(0, color='black')
670
+ plt.axvline(0, color='black')
671
+ if show:
672
+ plt.show()
673
+ return
674
+
675
+ return plt
676
+
677
+
678
+ def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
679
+ """
680
+ Returns the numerical data of the Bode magnitude plot of the system.
681
+ It is internally used by ``bode_magnitude_plot`` to get the data
682
+ for plotting Bode magnitude plot. Users can use this data to further
683
+ analyse the dynamics of the system or plot using a different
684
+ backend/plotting-module.
685
+
686
+ Parameters
687
+ ==========
688
+
689
+ system : SISOLinearTimeInvariant
690
+ The system for which the data is to be computed.
691
+ initial_exp : Number, optional
692
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
693
+ final_exp : Number, optional
694
+ The final exponent of 10 of the semilog plot. Defaults to 5.
695
+ freq_unit : string, optional
696
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
697
+
698
+ Returns
699
+ =======
700
+
701
+ tuple : (x, y)
702
+ x = x-axis values of the Bode magnitude plot.
703
+ y = y-axis values of the Bode magnitude plot.
704
+
705
+ Raises
706
+ ======
707
+
708
+ NotImplementedError
709
+ When a SISO LTI system is not passed.
710
+
711
+ When time delay terms are present in the system.
712
+
713
+ ValueError
714
+ When more than one free symbol is present in the system.
715
+ The only variable in the transfer function should be
716
+ the variable of the Laplace transform.
717
+
718
+ When incorrect frequency units are given as input.
719
+
720
+ Examples
721
+ ========
722
+
723
+ >>> from sympy.abc import s
724
+ >>> from sympy.physics.control.lti import TransferFunction
725
+ >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
726
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
727
+ >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
728
+ ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
729
+ [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
730
+
731
+ See Also
732
+ ========
733
+
734
+ bode_magnitude_plot, bode_phase_numerical_data
735
+
736
+ """
737
+ _check_system(system)
738
+ expr = system.to_expr()
739
+ freq_units = ('rad/sec', 'Hz')
740
+ if freq_unit not in freq_units:
741
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
742
+
743
+ _w = Dummy("w", real=True)
744
+ if freq_unit == 'Hz':
745
+ repl = I*_w*2*pi
746
+ else:
747
+ repl = I*_w
748
+ w_expr = expr.subs({system.var: repl})
749
+
750
+ mag = 20*log(Abs(w_expr), 10)
751
+
752
+ x, y = LineOver1DRangeSeries(mag,
753
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
754
+
755
+ return x, y
756
+
757
+
758
+ def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
759
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
760
+ r"""
761
+ Returns the Bode magnitude plot of a continuous-time system.
762
+
763
+ See ``bode_plot`` for all the parameters.
764
+ """
765
+ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
766
+ final_exp=final_exp, freq_unit=freq_unit)
767
+ plt.plot(x, y, color=color, **kwargs)
768
+ plt.xscale('log')
769
+
770
+
771
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
772
+ plt.ylabel('Magnitude (dB)')
773
+ plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
774
+
775
+ if grid:
776
+ plt.grid(True)
777
+ if show_axes:
778
+ plt.axhline(0, color='black')
779
+ plt.axvline(0, color='black')
780
+ if show:
781
+ plt.show()
782
+ return
783
+
784
+ return plt
785
+
786
+
787
+ def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', phase_unwrap = True, **kwargs):
788
+ """
789
+ Returns the numerical data of the Bode phase plot of the system.
790
+ It is internally used by ``bode_phase_plot`` to get the data
791
+ for plotting Bode phase plot. Users can use this data to further
792
+ analyse the dynamics of the system or plot using a different
793
+ backend/plotting-module.
794
+
795
+ Parameters
796
+ ==========
797
+
798
+ system : SISOLinearTimeInvariant
799
+ The system for which the Bode phase plot data is to be computed.
800
+ initial_exp : Number, optional
801
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
802
+ final_exp : Number, optional
803
+ The final exponent of 10 of the semilog plot. Defaults to 5.
804
+ freq_unit : string, optional
805
+ User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
806
+ phase_unit : string, optional
807
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
808
+ phase_unwrap : bool, optional
809
+ Set to ``True`` by default.
810
+
811
+ Returns
812
+ =======
813
+
814
+ tuple : (x, y)
815
+ x = x-axis values of the Bode phase plot.
816
+ y = y-axis values of the Bode phase plot.
817
+
818
+ Raises
819
+ ======
820
+
821
+ NotImplementedError
822
+ When a SISO LTI system is not passed.
823
+
824
+ When time delay terms are present in the system.
825
+
826
+ ValueError
827
+ When more than one free symbol is present in the system.
828
+ The only variable in the transfer function should be
829
+ the variable of the Laplace transform.
830
+
831
+ When incorrect frequency or phase units are given as input.
832
+
833
+ Examples
834
+ ========
835
+
836
+ >>> from sympy.abc import s
837
+ >>> from sympy.physics.control.lti import TransferFunction
838
+ >>> from sympy.physics.control.control_plots import bode_phase_numerical_data
839
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
840
+ >>> bode_phase_numerical_data(tf1) # doctest: +SKIP
841
+ ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
842
+ [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
843
+
844
+ See Also
845
+ ========
846
+
847
+ bode_magnitude_plot, bode_phase_numerical_data
848
+
849
+ """
850
+ _check_system(system)
851
+ expr = system.to_expr()
852
+ freq_units = ('rad/sec', 'Hz')
853
+ phase_units = ('rad', 'deg')
854
+ if freq_unit not in freq_units:
855
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
856
+ if phase_unit not in phase_units:
857
+ raise ValueError('Only "rad" and "deg" are accepted phase units.')
858
+
859
+ _w = Dummy("w", real=True)
860
+ if freq_unit == 'Hz':
861
+ repl = I*_w*2*pi
862
+ else:
863
+ repl = I*_w
864
+ w_expr = expr.subs({system.var: repl})
865
+
866
+ if phase_unit == 'deg':
867
+ phase = arg(w_expr)*180/pi
868
+ else:
869
+ phase = arg(w_expr)
870
+
871
+ x, y = LineOver1DRangeSeries(phase,
872
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
873
+
874
+ half = None
875
+ if phase_unwrap:
876
+ if(phase_unit == 'rad'):
877
+ half = pi
878
+ elif(phase_unit == 'deg'):
879
+ half = 180
880
+ if half:
881
+ unit = 2*half
882
+ for i in range(1, len(y)):
883
+ diff = y[i] - y[i - 1]
884
+ if diff > half: # Jump from -half to half
885
+ y[i] = (y[i] - unit)
886
+ elif diff < -half: # Jump from half to -half
887
+ y[i] = (y[i] + unit)
888
+
889
+ return x, y
890
+
891
+
892
+ def bode_phase_plot(system, initial_exp=-5, final_exp=5,
893
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
894
+ r"""
895
+ Returns the Bode phase plot of a continuous-time system.
896
+
897
+ See ``bode_plot`` for all the parameters.
898
+ """
899
+ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
900
+ final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap)
901
+ plt.plot(x, y, color=color, **kwargs)
902
+ plt.xscale('log')
903
+
904
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
905
+ plt.ylabel('Phase (%s)' % phase_unit)
906
+ plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
907
+
908
+ if grid:
909
+ plt.grid(True)
910
+ if show_axes:
911
+ plt.axhline(0, color='black')
912
+ plt.axvline(0, color='black')
913
+ if show:
914
+ plt.show()
915
+ return
916
+
917
+ return plt
918
+
919
+
920
+ def bode_plot(system, initial_exp=-5, final_exp=5,
921
+ grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', phase_unwrap=True, **kwargs):
922
+ r"""
923
+ Returns the Bode phase and magnitude plots of a continuous-time system.
924
+
925
+ Parameters
926
+ ==========
927
+
928
+ system : SISOLinearTimeInvariant type
929
+ The LTI SISO system for which the Bode Plot is to be computed.
930
+ initial_exp : Number, optional
931
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
932
+ final_exp : Number, optional
933
+ The final exponent of 10 of the semilog plot. Defaults to 5.
934
+ show : boolean, optional
935
+ If ``True``, the plot will be displayed otherwise
936
+ the equivalent matplotlib ``plot`` object will be returned.
937
+ Defaults to True.
938
+ prec : int, optional
939
+ The decimal point precision for the point coordinate values.
940
+ Defaults to 8.
941
+ grid : boolean, optional
942
+ If ``True``, the plot will have a grid. Defaults to True.
943
+ show_axes : boolean, optional
944
+ If ``True``, the coordinate axes will be shown. Defaults to False.
945
+ freq_unit : string, optional
946
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
947
+ phase_unit : string, optional
948
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
949
+
950
+ Examples
951
+ ========
952
+
953
+ .. plot::
954
+ :context: close-figs
955
+ :format: doctest
956
+ :include-source: True
957
+
958
+ >>> from sympy.abc import s
959
+ >>> from sympy.physics.control.lti import TransferFunction
960
+ >>> from sympy.physics.control.control_plots import bode_plot
961
+ >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
962
+ >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
963
+
964
+ See Also
965
+ ========
966
+
967
+ bode_magnitude_plot, bode_phase_plot
968
+
969
+ """
970
+ plt.subplot(211)
971
+ mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
972
+ show=False, grid=grid, show_axes=show_axes,
973
+ freq_unit=freq_unit, **kwargs)
974
+ mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
975
+ mag.xlabel(None)
976
+ plt.subplot(212)
977
+ bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
978
+ show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, phase_unwrap=phase_unwrap, **kwargs).title(None)
979
+
980
+ if show:
981
+ plt.show()
982
+ return
983
+
984
+ return plt
985
+
986
+
987
+ def nyquist_plot_expr(system):
988
+ """Function to get the expression for Nyquist plot."""
989
+ s = system.var
990
+ w = Dummy('w', real=True)
991
+ repl = I * w
992
+ expr = system.to_expr()
993
+ w_expr = expr.subs({s: repl})
994
+ w_expr = w_expr.as_real_imag()
995
+ real_expr = w_expr[0]
996
+ imag_expr = w_expr[1]
997
+ return real_expr, imag_expr, w
998
+
999
+
1000
+ def nichols_plot_expr(system):
1001
+ """Function to get the expression for Nichols plot."""
1002
+ s = system.var
1003
+ w = Dummy('w', real=True)
1004
+ sys_expr = system.to_expr()
1005
+ H_jw = sys_expr.subs(s, I*w)
1006
+ mag_expr = Abs(H_jw)
1007
+ mag_dB_expr = 20*log(mag_expr, 10)
1008
+ phase_expr = arg(H_jw)
1009
+ phase_deg_expr = deg(phase_expr)
1010
+ return mag_dB_expr, phase_deg_expr, w
1011
+
1012
+
1013
+ def nyquist_plot(system, initial_omega=0.01, final_omega=100, show=True,
1014
+ color='b', **kwargs):
1015
+ r"""
1016
+ Generates the Nyquist plot for a continuous-time system.
1017
+
1018
+ Parameters
1019
+ ==========
1020
+
1021
+ system : SISOLinearTimeInvariant
1022
+ The LTI SISO system for which the Nyquist plot is to be generated.
1023
+ initial_omega : float, optional
1024
+ The starting frequency value. Defaults to 0.01.
1025
+ final_omega : float, optional
1026
+ The ending frequency value. Defaults to 100.
1027
+ show : bool, optional
1028
+ If True, the plot is displayed. Default is True.
1029
+ color : str, optional
1030
+ The color of the Nyquist plot. Default is 'b' (blue).
1031
+ grid : bool, optional
1032
+ If True, grid lines are displayed. Default is False.
1033
+ **kwargs
1034
+ Additional keyword arguments for customization.
1035
+
1036
+ Examples
1037
+ ========
1038
+
1039
+ .. plot::
1040
+ :context: close-figs
1041
+ :format: doctest
1042
+ :include-source: True
1043
+
1044
+ >>> from sympy.abc import s
1045
+ >>> from sympy.physics.control.lti import TransferFunction
1046
+ >>> from sympy.physics.control.control_plots import nyquist_plot
1047
+ >>> tf1 = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
1048
+ >>> nyquist_plot(tf1) # doctest: +SKIP
1049
+
1050
+ See Also
1051
+ ========
1052
+
1053
+ nichols_plot, bode_plot
1054
+
1055
+ """
1056
+ _check_system(system)
1057
+ real_expr, imag_expr, w = nyquist_plot_expr(system)
1058
+ w_values = [(w, initial_omega, final_omega)]
1059
+ p = plot_parametric(
1060
+ (real_expr, imag_expr), # The curve
1061
+ (real_expr, -imag_expr), # Its mirror image
1062
+ *w_values,
1063
+ show=False,
1064
+ line_color=color,
1065
+ adaptive=True,
1066
+ title=f'Nyquist Plot of ${latex(system)}$',
1067
+ xlabel='Real Axis',
1068
+ ylabel='Imaginary Axis',
1069
+ size=(6, 5),
1070
+ kwargs=kwargs)
1071
+ if show:
1072
+ p.show()
1073
+ return
1074
+ return p
1075
+
1076
+
1077
+ def nichols_plot(system, initial_omega=0.01, final_omega=100, show=True, color='b', **kwargs):
1078
+ r"""
1079
+ Generates the Nichols plot for a LTI system.
1080
+
1081
+ Parameters
1082
+ ==========
1083
+
1084
+ system : SISOLinearTimeInvariant
1085
+ The LTI SISO system for which the Nyquist plot is to be generated.
1086
+ initial_omega : float, optional
1087
+ The starting frequency value. Defaults to 0.01.
1088
+ final_omega : float, optional
1089
+ The ending frequency value. Defaults to 100.
1090
+ show : bool, optional
1091
+ If True, the plot is displayed. Default is True.
1092
+ color : str, optional
1093
+ The color of the Nyquist plot. Default is 'b' (blue).
1094
+ grid : bool, optional
1095
+ If True, grid lines are displayed. Default is False.
1096
+ **kwargs
1097
+ Additional keyword arguments for customization.
1098
+
1099
+ Examples
1100
+ ========
1101
+
1102
+ .. plot::
1103
+ :context: close-figs
1104
+ :format: doctest
1105
+ :include-source: True
1106
+
1107
+ >>> from sympy.abc import s
1108
+ >>> from sympy.physics.control.lti import TransferFunction
1109
+ >>> from sympy.physics.control.control_plots import nichols_plot
1110
+ >>> tf1 = TransferFunction(1.5, s**2+14*s+40.02, s)
1111
+ >>> nichols_plot(tf1) # doctest: +SKIP
1112
+
1113
+ See Also
1114
+ ========
1115
+
1116
+ nyquist_plot, bode_plot
1117
+
1118
+ """
1119
+ _check_system(system)
1120
+ magnitude_dB_expr, phase_deg_expr, w = nichols_plot_expr(system)
1121
+ w_values = [(w, initial_omega, final_omega)]
1122
+ p = plot_parametric(
1123
+ (phase_deg_expr, magnitude_dB_expr),
1124
+ *w_values,
1125
+ show=False,
1126
+ line_color=color,
1127
+ title=f'Nichols Plot of ${latex(system)}$',
1128
+ xlabel='Phase [deg]',
1129
+ ylabel='Magnitude [dB]',
1130
+ size=(6,5),
1131
+ kwargs=kwargs)
1132
+ if show:
1133
+ p.show()
1134
+ return
1135
+ return p
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/lti.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import isclose
2
+ from sympy.core.numbers import I, all_close
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.functions.elementary.complexes import (Abs, arg)
5
+ from sympy.functions.elementary.exponential import log
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.abc import s, p, a
8
+ from sympy import pi
9
+ from sympy.external import import_module
10
+ from sympy.physics.control.control_plots import \
11
+ (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
12
+ step_response_plot, impulse_response_numerical_data,
13
+ impulse_response_plot, ramp_response_numerical_data,
14
+ ramp_response_plot, bode_magnitude_numerical_data,
15
+ bode_phase_numerical_data, bode_plot, nyquist_plot_expr,
16
+ nichols_plot_expr)
17
+
18
+ from sympy.physics.control.lti import (TransferFunction,
19
+ Series, Parallel, TransferFunctionMatrix)
20
+ from sympy.testing.pytest import raises, skip
21
+
22
+ matplotlib = import_module(
23
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
24
+ catch=(RuntimeError,))
25
+
26
+ numpy = import_module('numpy')
27
+
28
+ tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
29
+ tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
30
+ tf3 = TransferFunction(p, p**3 - 1, p)
31
+ tf4 = TransferFunction(10, p**3, p)
32
+ tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
33
+ tf6 = TransferFunction(1, 1, s)
34
+ tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
35
+ tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
36
+
37
+ ser1 = Series(tf4, TransferFunction(1, p - 5, p))
38
+ ser2 = Series(tf3, TransferFunction(p, p + 2, p))
39
+
40
+ par1 = Parallel(tf1, tf2)
41
+
42
+
43
+ def _to_tuple(a, b):
44
+ return tuple(a), tuple(b)
45
+
46
+ def _trim_tuple(a, b):
47
+ a, b = _to_tuple(a, b)
48
+ return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
49
+ tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
50
+
51
+ def y_coordinate_equality(plot_data_func, evalf_func, system):
52
+ """Checks whether the y-coordinate value of the plotted
53
+ data point is equal to the value of the function at a
54
+ particular x."""
55
+ x, y = plot_data_func(system)
56
+ x, y = _trim_tuple(x, y)
57
+ y_exp = tuple(evalf_func(system, x_i) for x_i in x)
58
+ return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
59
+
60
+
61
+ def test_errors():
62
+ if not matplotlib:
63
+ skip("Matplotlib not the default backend")
64
+
65
+ # Invalid `system` check
66
+ tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
67
+ expr = 1/(s**2 - 1)
68
+ raises(NotImplementedError, lambda: pole_zero_plot(tfm))
69
+ raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
70
+ raises(NotImplementedError, lambda: impulse_response_plot(expr))
71
+ raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
72
+ raises(NotImplementedError, lambda: step_response_plot(tfm))
73
+ raises(NotImplementedError, lambda: step_response_numerical_data(expr))
74
+ raises(NotImplementedError, lambda: ramp_response_plot(expr))
75
+ raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
76
+ raises(NotImplementedError, lambda: bode_plot(tfm))
77
+
78
+ # More than 1 variables
79
+ tf_a = TransferFunction(a, s + 1, s)
80
+ raises(ValueError, lambda: pole_zero_plot(tf_a))
81
+ raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
82
+ raises(ValueError, lambda: impulse_response_plot(tf_a))
83
+ raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
84
+ raises(ValueError, lambda: step_response_plot(tf_a))
85
+ raises(ValueError, lambda: step_response_numerical_data(tf_a))
86
+ raises(ValueError, lambda: ramp_response_plot(tf_a))
87
+ raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
88
+ raises(ValueError, lambda: bode_plot(tf_a))
89
+
90
+ # lower_limit > 0 for response plots
91
+ raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
92
+ raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
93
+ raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
94
+
95
+ # slope in ramp_response_plot() is negative
96
+ raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
97
+
98
+ # incorrect frequency or phase unit
99
+ raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
100
+ raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
101
+
102
+
103
+ def test_pole_zero():
104
+
105
+ def pz_tester(sys, expected_value):
106
+ _z, _p = pole_zero_numerical_data(sys)
107
+ z_check = all_close(_z, expected_value[0])
108
+ p_check = all_close(_p, expected_value[1])
109
+ return p_check and z_check
110
+
111
+ exp1 = [[], [-0.24999999999999994-1.3919410907075054j, -0.24999999999999994+1.3919410907075054j]]
112
+ exp2 = [[0.0], [-0.25-0.3227486121839514j, -0.25+0.3227486121839514j]]
113
+ exp3 = [[0.0], [0.9999999999999998+0j, -0.5000000000000004-0.8660254037844395j,
114
+ -0.5000000000000004+0.8660254037844395j]]
115
+ exp4 = [[], [0.0, 0.0, 0.0, 5.0]]
116
+ exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
117
+ [-0.24999999999999986-0.322748612183951348j,
118
+ -0.2499999999999998+0.32274861218395134j,
119
+ -0.24999999999999986-1.3919410907075052j,
120
+ -0.2499999999999998+1.3919410907075052j]]
121
+ exp6 = [[], [-1.1641600331447917-3.545808351896439j,
122
+ -0.8358399668552097+2.5458083518964383j]]
123
+
124
+ assert pz_tester(tf1, exp1)
125
+ assert pz_tester(tf2, exp2)
126
+ assert pz_tester(tf3, exp3)
127
+ assert pz_tester(ser1, exp4)
128
+ assert pz_tester(par1, exp5)
129
+ assert pz_tester(tf8, exp6)
130
+
131
+
132
+ def test_bode():
133
+ if not numpy:
134
+ skip("NumPy is required for this test")
135
+
136
+ def bode_phase_evalf(system, point):
137
+ expr = system.to_expr()
138
+ _w = Dummy("w", real=True)
139
+ w_expr = expr.subs({system.var: I*_w})
140
+ return arg(w_expr).subs({_w: point}).evalf()
141
+
142
+ def bode_mag_evalf(system, point):
143
+ expr = system.to_expr()
144
+ _w = Dummy("w", real=True)
145
+ w_expr = expr.subs({system.var: I*_w})
146
+ return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
147
+
148
+ def test_bode_data(sys):
149
+ return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
150
+ and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
151
+
152
+ assert test_bode_data(tf1)
153
+ assert test_bode_data(tf2)
154
+ assert test_bode_data(tf3)
155
+ assert test_bode_data(tf4)
156
+ assert test_bode_data(tf5)
157
+
158
+
159
+ def check_point_accuracy(a, b):
160
+ return all(isclose(*_, rel_tol=1e-1, abs_tol=1e-6
161
+ ) for _ in zip(a, b))
162
+
163
+
164
+ def test_impulse_response():
165
+ if not numpy:
166
+ skip("NumPy is required for this test")
167
+
168
+ def impulse_res_tester(sys, expected_value):
169
+ x, y = _to_tuple(*impulse_response_numerical_data(sys,
170
+ adaptive=False, n=10))
171
+ x_check = check_point_accuracy(x, expected_value[0])
172
+ y_check = check_point_accuracy(y, expected_value[1])
173
+ return x_check and y_check
174
+
175
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
176
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
177
+ (0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
178
+ 0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
179
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
180
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
181
+ 0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
182
+ -0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
183
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
184
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
185
+ 3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
186
+ 795.6538758627842, 2416.9920942096983, 7342.159505206647))
187
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
188
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
189
+ 55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
190
+ 395.0617283950618, 500.0))
191
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
192
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
193
+ 0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
194
+ 0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
195
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
196
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
197
+ (-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
198
+ 25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
199
+ -1747.0262164682233))
200
+ exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
201
+ 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
202
+ 8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
203
+ 358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
204
+ 4.147764422869658e+20))
205
+
206
+ assert impulse_res_tester(tf1, exp1)
207
+ assert impulse_res_tester(tf2, exp2)
208
+ assert impulse_res_tester(tf3, exp3)
209
+ assert impulse_res_tester(tf4, exp4)
210
+ assert impulse_res_tester(tf5, exp5)
211
+ assert impulse_res_tester(tf7, exp6)
212
+ assert impulse_res_tester(ser1, exp7)
213
+
214
+
215
+ def test_step_response():
216
+ if not numpy:
217
+ skip("NumPy is required for this test")
218
+
219
+ def step_res_tester(sys, expected_value):
220
+ x, y = _to_tuple(*step_response_numerical_data(sys,
221
+ adaptive=False, n=10))
222
+ x_check = check_point_accuracy(x, expected_value[0])
223
+ y_check = check_point_accuracy(y, expected_value[1])
224
+ return x_check and y_check
225
+
226
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
227
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
228
+ (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
229
+ 0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
230
+ 0.4486997874319281, 0.4839358435839171))
231
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
232
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
233
+ (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
234
+ 0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
235
+ -0.003636420058445484))
236
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
237
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
238
+ (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
239
+ 86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
240
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
241
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
242
+ (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
243
+ 493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
244
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
245
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
246
+ (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
247
+ 0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
248
+ 0.49997448824584123, 0.5000039745919259))
249
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
250
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
251
+ (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
252
+ 9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
253
+ 2447.387582370878))
254
+
255
+ assert step_res_tester(tf1, exp1)
256
+ assert step_res_tester(tf2, exp2)
257
+ assert step_res_tester(tf3, exp3)
258
+ assert step_res_tester(tf4, exp4)
259
+ assert step_res_tester(tf5, exp5)
260
+ assert step_res_tester(ser2, exp6)
261
+
262
+
263
+ def test_ramp_response():
264
+ if not numpy:
265
+ skip("NumPy is required for this test")
266
+
267
+ def ramp_res_tester(sys, num_points, expected_value, slope=1):
268
+ x, y = _to_tuple(*ramp_response_numerical_data(sys,
269
+ slope=slope, adaptive=False, n=num_points))
270
+ x_check = check_point_accuracy(x, expected_value[0])
271
+ y_check = check_point_accuracy(y, expected_value[1])
272
+ return x_check and y_check
273
+
274
+ exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
275
+ 2.7956587704217783, 3.9224897567931514, 4.85022655284895))
276
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
277
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
278
+ (2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
279
+ 0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
280
+ 1.304684417610106))
281
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
282
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
283
+ 0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
284
+ 391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
285
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
286
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
287
+ 154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
288
+ 7803.688462124678, 12500.0))
289
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
290
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
291
+ 14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
292
+ 39.09983919254265, 44.10006013058409))
293
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
294
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
295
+ 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
296
+
297
+ assert ramp_res_tester(tf1, 6, exp1)
298
+ assert ramp_res_tester(tf2, 10, exp2, 1.2)
299
+ assert ramp_res_tester(tf3, 10, exp3, 1.5)
300
+ assert ramp_res_tester(tf4, 10, exp4, 3)
301
+ assert ramp_res_tester(tf5, 10, exp5, 9)
302
+ assert ramp_res_tester(tf6, 10, exp6)
303
+
304
+
305
+ def test_nyquist_plot_expr():
306
+ r1, i1, w1 = nyquist_plot_expr(tf1)
307
+ r2, i2, w2 = nyquist_plot_expr(tf2)
308
+ r3, i3, w3 = nyquist_plot_expr(tf3)
309
+ r4, i4, w4 = nyquist_plot_expr(tf4)
310
+ assert r1 == (2 - w1**2)/(0.25*w1**2 + (2 - w1**2)**2)
311
+ assert i1 == -0.5*w1/(0.25*w1**2 + (2 - w1**2)**2)
312
+ assert r2 == 3*w2**2/(9*w2**2 + (1 - 6*w2**2)**2)
313
+ assert i2 == w2*(1 - 6*w2**2)/(9*w2**2 + (1 - 6*w2**2)**2)
314
+ assert r3 == -w3**4/(w3**6 + 1)
315
+ assert i3 == -w3/(w3**6 + 1)
316
+ assert r4 == 0
317
+ assert i4 == 10/w4**3
318
+
319
+
320
+ def test_nichols_expr():
321
+ m1, p1, w1 = nichols_plot_expr(tf1)
322
+ m2, p2, w2 = nichols_plot_expr(tf2)
323
+ m3, p3, w3 = nichols_plot_expr(tf3)
324
+ m4, p4, w4 = nichols_plot_expr(tf4)
325
+ assert m1 == 20*log(1/sqrt(w1**4 - 3.75*w1**2 + 4))/log(10)
326
+ assert p1 == 180*arg(1/(-w1**2 + 0.5*w1*I + 2))/pi
327
+ assert m2 == 20*log(Abs(w2)/sqrt(36*w2**4 - 3*w2**2 + 1))/log(10)
328
+ assert p2 == 180*arg(w2*I/(-6*w2**2 + 3*w2*I + 1))/pi
329
+ assert m3 == 20*log(Abs(w3)/sqrt(w3**6 + 1))/log(10)
330
+ assert p3 == 180*arg(-w3*I/(w3**3*I + 1))/pi
331
+ assert m4 == 20*log(10/(w4**2*Abs(w4)))/log(10)
332
+ assert p4 == 180*arg(I/w4**3)/pi
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py ADDED
The diff for this file is too large to render. See raw diff
 
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module to handle gamma matrices expressed as tensor objects.
3
+
4
+ Examples
5
+ ========
6
+
7
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
8
+ >>> from sympy.tensor.tensor import tensor_indices
9
+ >>> i = tensor_indices('i', LorentzIndex)
10
+ >>> G(i)
11
+ GammaMatrix(i)
12
+
13
+ Note that there is already an instance of GammaMatrixHead in four dimensions:
14
+ GammaMatrix, which is simply declare as
15
+
16
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix
17
+ >>> from sympy.tensor.tensor import tensor_indices
18
+ >>> i = tensor_indices('i', LorentzIndex)
19
+ >>> GammaMatrix(i)
20
+ GammaMatrix(i)
21
+
22
+ To access the metric tensor
23
+
24
+ >>> LorentzIndex.metric
25
+ metric(LorentzIndex,LorentzIndex)
26
+
27
+ """
28
+ from sympy.core.mul import Mul
29
+ from sympy.core.singleton import S
30
+ from sympy.matrices.dense import eye
31
+ from sympy.matrices.expressions.trace import trace
32
+ from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
33
+ TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
34
+
35
+
36
+ # DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
37
+
38
+
39
+ LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
40
+
41
+
42
+ GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
43
+ TensorSymmetry.no_symmetry(1), comm=None)
44
+
45
+
46
+ def extract_type_tens(expression, component):
47
+ """
48
+ Extract from a ``TensExpr`` all tensors with `component`.
49
+
50
+ Returns two tensor expressions:
51
+
52
+ * the first contains all ``Tensor`` of having `component`.
53
+ * the second contains all remaining.
54
+
55
+
56
+ """
57
+ if isinstance(expression, Tensor):
58
+ sp = [expression]
59
+ elif isinstance(expression, TensMul):
60
+ sp = expression.args
61
+ else:
62
+ raise ValueError('wrong type')
63
+
64
+ # Collect all gamma matrices of the same dimension
65
+ new_expr = S.One
66
+ residual_expr = S.One
67
+ for i in sp:
68
+ if isinstance(i, Tensor) and i.component == component:
69
+ new_expr *= i
70
+ else:
71
+ residual_expr *= i
72
+ return new_expr, residual_expr
73
+
74
+
75
+ def simplify_gamma_expression(expression):
76
+ extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
77
+ res_expr = _simplify_single_line(extracted_expr)
78
+ return res_expr * residual_expr
79
+
80
+
81
+ def simplify_gpgp(ex, sort=True):
82
+ """
83
+ simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
89
+ LorentzIndex, simplify_gpgp
90
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
91
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
92
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
93
+ >>> ps = p(i0)*G(-i0)
94
+ >>> qs = q(i0)*G(-i0)
95
+ >>> simplify_gpgp(ps*qs*qs)
96
+ GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
97
+ """
98
+ def _simplify_gpgp(ex):
99
+ components = ex.components
100
+ a = []
101
+ comp_map = []
102
+ for i, comp in enumerate(components):
103
+ comp_map.extend([i]*comp.rank)
104
+ dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
105
+ for i in range(len(components)):
106
+ if components[i] != GammaMatrix:
107
+ continue
108
+ for dx in dum:
109
+ if dx[2] == i:
110
+ p_pos1 = dx[3]
111
+ elif dx[3] == i:
112
+ p_pos1 = dx[2]
113
+ else:
114
+ continue
115
+ comp1 = components[p_pos1]
116
+ if comp1.comm == 0 and comp1.rank == 1:
117
+ a.append((i, p_pos1))
118
+ if not a:
119
+ return ex
120
+ elim = set()
121
+ tv = []
122
+ hit = True
123
+ coeff = S.One
124
+ ta = None
125
+ while hit:
126
+ hit = False
127
+ for i, ai in enumerate(a[:-1]):
128
+ if ai[0] in elim:
129
+ continue
130
+ if ai[0] != a[i + 1][0] - 1:
131
+ continue
132
+ if components[ai[1]] != components[a[i + 1][1]]:
133
+ continue
134
+ elim.add(ai[0])
135
+ elim.add(ai[1])
136
+ elim.add(a[i + 1][0])
137
+ elim.add(a[i + 1][1])
138
+ if not ta:
139
+ ta = ex.split()
140
+ mu = TensorIndex('mu', LorentzIndex)
141
+ hit = True
142
+ if i == 0:
143
+ coeff = ex.coeff
144
+ tx = components[ai[1]](mu)*components[ai[1]](-mu)
145
+ if len(a) == 2:
146
+ tx *= 4 # eye(4)
147
+ tv.append(tx)
148
+ break
149
+
150
+ if tv:
151
+ a = [x for j, x in enumerate(ta) if j not in elim]
152
+ a.extend(tv)
153
+ t = tensor_mul(*a)*coeff
154
+ # t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
155
+ return t
156
+ else:
157
+ return ex
158
+
159
+ if sort:
160
+ ex = ex.sorted_components()
161
+ # this would be better off with pattern matching
162
+ while 1:
163
+ t = _simplify_gpgp(ex)
164
+ if t != ex:
165
+ ex = t
166
+ else:
167
+ return t
168
+
169
+
170
+ def gamma_trace(t):
171
+ """
172
+ trace of a single line of gamma matrices
173
+
174
+ Examples
175
+ ========
176
+
177
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
178
+ gamma_trace, LorentzIndex
179
+ >>> from sympy.tensor.tensor import tensor_indices, tensor_heads
180
+ >>> p, q = tensor_heads('p, q', [LorentzIndex])
181
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
182
+ >>> ps = p(i0)*G(-i0)
183
+ >>> qs = q(i0)*G(-i0)
184
+ >>> gamma_trace(G(i0)*G(i1))
185
+ 4*metric(i0, i1)
186
+ >>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
187
+ 0
188
+ >>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
189
+ 0
190
+
191
+ """
192
+ if isinstance(t, TensAdd):
193
+ res = TensAdd(*[gamma_trace(x) for x in t.args])
194
+ return res
195
+ t = _simplify_single_line(t)
196
+ res = _trace_single_line(t)
197
+ return res
198
+
199
+
200
+ def _simplify_single_line(expression):
201
+ """
202
+ Simplify single-line product of gamma matrices.
203
+
204
+ Examples
205
+ ========
206
+
207
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
208
+ LorentzIndex, _simplify_single_line
209
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
210
+ >>> p = TensorHead('p', [LorentzIndex])
211
+ >>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
212
+ >>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
213
+ 0
214
+
215
+ """
216
+ t1, t2 = extract_type_tens(expression, GammaMatrix)
217
+ if t1 != 1:
218
+ t1 = kahane_simplify(t1)
219
+ res = t1*t2
220
+ return res
221
+
222
+
223
+ def _trace_single_line(t):
224
+ """
225
+ Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
226
+
227
+ Notes
228
+ =====
229
+
230
+ If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
231
+ indices trace over them; otherwise traces are not implied (explain)
232
+
233
+
234
+ Examples
235
+ ========
236
+
237
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
238
+ LorentzIndex, _trace_single_line
239
+ >>> from sympy.tensor.tensor import tensor_indices, TensorHead
240
+ >>> p = TensorHead('p', [LorentzIndex])
241
+ >>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
242
+ >>> _trace_single_line(G(i0)*G(i1))
243
+ 4*metric(i0, i1)
244
+ >>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
245
+ 0
246
+
247
+ """
248
+ def _trace_single_line1(t):
249
+ t = t.sorted_components()
250
+ components = t.components
251
+ ncomps = len(components)
252
+ g = LorentzIndex.metric
253
+ # gamma matirices are in a[i:j]
254
+ hit = 0
255
+ for i in range(ncomps):
256
+ if components[i] == GammaMatrix:
257
+ hit = 1
258
+ break
259
+
260
+ for j in range(i + hit, ncomps):
261
+ if components[j] != GammaMatrix:
262
+ break
263
+ else:
264
+ j = ncomps
265
+ numG = j - i
266
+ if numG == 0:
267
+ tcoeff = t.coeff
268
+ return t.nocoeff if tcoeff else t
269
+ if numG % 2 == 1:
270
+ return TensMul.from_data(S.Zero, [], [], [])
271
+ elif numG > 4:
272
+ # find the open matrix indices and connect them:
273
+ a = t.split()
274
+ ind1 = a[i].get_indices()[0]
275
+ ind2 = a[i + 1].get_indices()[0]
276
+ aa = a[:i] + a[i + 2:]
277
+ t1 = tensor_mul(*aa)*g(ind1, ind2)
278
+ t1 = t1.contract_metric(g)
279
+ args = [t1]
280
+ sign = 1
281
+ for k in range(i + 2, j):
282
+ sign = -sign
283
+ ind2 = a[k].get_indices()[0]
284
+ aa = a[:i] + a[i + 1:k] + a[k + 1:]
285
+ t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
286
+ t2 = t2.contract_metric(g)
287
+ t2 = simplify_gpgp(t2, False)
288
+ args.append(t2)
289
+ t3 = TensAdd(*args)
290
+ t3 = _trace_single_line(t3)
291
+ return t3
292
+ else:
293
+ a = t.split()
294
+ t1 = _gamma_trace1(*a[i:j])
295
+ a2 = a[:i] + a[j:]
296
+ t2 = tensor_mul(*a2)
297
+ t3 = t1*t2
298
+ if not t3:
299
+ return t3
300
+ t3 = t3.contract_metric(g)
301
+ return t3
302
+
303
+ t = t.expand()
304
+ if isinstance(t, TensAdd):
305
+ a = [_trace_single_line1(x)*x.coeff for x in t.args]
306
+ return TensAdd(*a)
307
+ elif isinstance(t, (Tensor, TensMul)):
308
+ r = t.coeff*_trace_single_line1(t)
309
+ return r
310
+ else:
311
+ return trace(t)
312
+
313
+
314
+ def _gamma_trace1(*a):
315
+ gctr = 4 # FIXME specific for d=4
316
+ g = LorentzIndex.metric
317
+ if not a:
318
+ return gctr
319
+ n = len(a)
320
+ if n%2 == 1:
321
+ #return TensMul.from_data(S.Zero, [], [], [])
322
+ return S.Zero
323
+ if n == 2:
324
+ ind0 = a[0].get_indices()[0]
325
+ ind1 = a[1].get_indices()[0]
326
+ return gctr*g(ind0, ind1)
327
+ if n == 4:
328
+ ind0 = a[0].get_indices()[0]
329
+ ind1 = a[1].get_indices()[0]
330
+ ind2 = a[2].get_indices()[0]
331
+ ind3 = a[3].get_indices()[0]
332
+
333
+ return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
334
+ g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
335
+
336
+
337
+ def kahane_simplify(expression):
338
+ r"""
339
+ This function cancels contracted elements in a product of four
340
+ dimensional gamma matrices, resulting in an expression equal to the given
341
+ one, without the contracted gamma matrices.
342
+
343
+ Parameters
344
+ ==========
345
+
346
+ `expression` the tensor expression containing the gamma matrices to simplify.
347
+
348
+ Notes
349
+ =====
350
+
351
+ If spinor indices are given, the matrices must be given in
352
+ the order given in the product.
353
+
354
+ Algorithm
355
+ =========
356
+
357
+ The idea behind the algorithm is to use some well-known identities,
358
+ i.e., for contractions enclosing an even number of `\gamma` matrices
359
+
360
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
361
+
362
+ for an odd number of `\gamma` matrices
363
+
364
+ `\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
365
+
366
+ Instead of repeatedly applying these identities to cancel out all contracted indices,
367
+ it is possible to recognize the links that would result from such an operation,
368
+ the problem is thus reduced to a simple rearrangement of free gamma matrices.
369
+
370
+ Examples
371
+ ========
372
+
373
+ When using, always remember that the original expression coefficient
374
+ has to be handled separately
375
+
376
+ >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
377
+ >>> from sympy.physics.hep.gamma_matrices import kahane_simplify
378
+ >>> from sympy.tensor.tensor import tensor_indices
379
+ >>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
380
+ >>> ta = G(i0)*G(-i0)
381
+ >>> kahane_simplify(ta)
382
+ Matrix([
383
+ [4, 0, 0, 0],
384
+ [0, 4, 0, 0],
385
+ [0, 0, 4, 0],
386
+ [0, 0, 0, 4]])
387
+ >>> tb = G(i0)*G(i1)*G(-i0)
388
+ >>> kahane_simplify(tb)
389
+ -2*GammaMatrix(i1)
390
+ >>> t = G(i0)*G(-i0)
391
+ >>> kahane_simplify(t)
392
+ Matrix([
393
+ [4, 0, 0, 0],
394
+ [0, 4, 0, 0],
395
+ [0, 0, 4, 0],
396
+ [0, 0, 0, 4]])
397
+ >>> t = G(i0)*G(-i0)
398
+ >>> kahane_simplify(t)
399
+ Matrix([
400
+ [4, 0, 0, 0],
401
+ [0, 4, 0, 0],
402
+ [0, 0, 4, 0],
403
+ [0, 0, 0, 4]])
404
+
405
+ If there are no contractions, the same expression is returned
406
+
407
+ >>> tc = G(i0)*G(i1)
408
+ >>> kahane_simplify(tc)
409
+ GammaMatrix(i0)*GammaMatrix(i1)
410
+
411
+ References
412
+ ==========
413
+
414
+ [1] Algorithm for Reducing Contracted Products of gamma Matrices,
415
+ Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
416
+ """
417
+
418
+ if isinstance(expression, Mul):
419
+ return expression
420
+ if isinstance(expression, TensAdd):
421
+ return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
422
+
423
+ if isinstance(expression, Tensor):
424
+ return expression
425
+
426
+ assert isinstance(expression, TensMul)
427
+
428
+ gammas = expression.args
429
+
430
+ for gamma in gammas:
431
+ assert gamma.component == GammaMatrix
432
+
433
+ free = expression.free
434
+ # spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
435
+
436
+ # if len(spinor_free) == 2:
437
+ # spinor_free.sort(key=lambda x: x[2])
438
+ # assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
439
+ # assert spinor_free[0][2] == 0
440
+ # elif spinor_free:
441
+ # raise ValueError('spinor indices do not match')
442
+
443
+ dum = []
444
+ for dum_pair in expression.dum:
445
+ if expression.index_types[dum_pair[0]] == LorentzIndex:
446
+ dum.append((dum_pair[0], dum_pair[1]))
447
+
448
+ dum = sorted(dum)
449
+
450
+ if len(dum) == 0: # or GammaMatrixHead:
451
+ # no contractions in `expression`, just return it.
452
+ return expression
453
+
454
+ # find the `first_dum_pos`, i.e. the position of the first contracted
455
+ # gamma matrix, Kahane's algorithm as described in his paper requires the
456
+ # gamma matrix expression to start with a contracted gamma matrix, this is
457
+ # a workaround which ignores possible initial free indices, and re-adds
458
+ # them later.
459
+
460
+ first_dum_pos = min(map(min, dum))
461
+
462
+ # for p1, p2, a1, a2 in expression.dum_in_args:
463
+ # if p1 != 0 or p2 != 0:
464
+ # # only Lorentz indices, skip Dirac indices:
465
+ # continue
466
+ # first_dum_pos = min(p1, p2)
467
+ # break
468
+
469
+ total_number = len(free) + len(dum)*2
470
+ number_of_contractions = len(dum)
471
+
472
+ free_pos = [None]*total_number
473
+ for i in free:
474
+ free_pos[i[1]] = i[0]
475
+
476
+ # `index_is_free` is a list of booleans, to identify index position
477
+ # and whether that index is free or dummy.
478
+ index_is_free = [False]*total_number
479
+
480
+ for i, indx in enumerate(free):
481
+ index_is_free[indx[1]] = True
482
+
483
+ # `links` is a dictionary containing the graph described in Kahane's paper,
484
+ # to every key correspond one or two values, representing the linked indices.
485
+ # All values in `links` are integers, negative numbers are used in the case
486
+ # where it is necessary to insert gamma matrices between free indices, in
487
+ # order to make Kahane's algorithm work (see paper).
488
+ links = {i: [] for i in range(first_dum_pos, total_number)}
489
+
490
+ # `cum_sign` is a step variable to mark the sign of every index, see paper.
491
+ cum_sign = -1
492
+ # `cum_sign_list` keeps storage for all `cum_sign` (every index).
493
+ cum_sign_list = [None]*total_number
494
+ block_free_count = 0
495
+
496
+ # multiply `resulting_coeff` by the coefficient parameter, the rest
497
+ # of the algorithm ignores a scalar coefficient.
498
+ resulting_coeff = S.One
499
+
500
+ # initialize a list of lists of indices. The outer list will contain all
501
+ # additive tensor expressions, while the inner list will contain the
502
+ # free indices (rearranged according to the algorithm).
503
+ resulting_indices = [[]]
504
+
505
+ # start to count the `connected_components`, which together with the number
506
+ # of contractions, determines a -1 or +1 factor to be multiplied.
507
+ connected_components = 1
508
+
509
+ # First loop: here we fill `cum_sign_list`, and draw the links
510
+ # among consecutive indices (they are stored in `links`). Links among
511
+ # non-consecutive indices will be drawn later.
512
+ for i, is_free in enumerate(index_is_free):
513
+ # if `expression` starts with free indices, they are ignored here;
514
+ # they are later added as they are to the beginning of all
515
+ # `resulting_indices` list of lists of indices.
516
+ if i < first_dum_pos:
517
+ continue
518
+
519
+ if is_free:
520
+ block_free_count += 1
521
+ # if previous index was free as well, draw an arch in `links`.
522
+ if block_free_count > 1:
523
+ links[i - 1].append(i)
524
+ links[i].append(i - 1)
525
+ else:
526
+ # Change the sign of the index (`cum_sign`) if the number of free
527
+ # indices preceding it is even.
528
+ cum_sign *= 1 if (block_free_count % 2) else -1
529
+ if block_free_count == 0 and i != first_dum_pos:
530
+ # check if there are two consecutive dummy indices:
531
+ # in this case create virtual indices with negative position,
532
+ # these "virtual" indices represent the insertion of two
533
+ # gamma^0 matrices to separate consecutive dummy indices, as
534
+ # Kahane's algorithm requires dummy indices to be separated by
535
+ # free indices. The product of two gamma^0 matrices is unity,
536
+ # so the new expression being examined is the same as the
537
+ # original one.
538
+ if cum_sign == -1:
539
+ links[-1-i] = [-1-i+1]
540
+ links[-1-i+1] = [-1-i]
541
+ if (i - cum_sign) in links:
542
+ if i != first_dum_pos:
543
+ links[i].append(i - cum_sign)
544
+ if block_free_count != 0:
545
+ if i - cum_sign < len(index_is_free):
546
+ if index_is_free[i - cum_sign]:
547
+ links[i - cum_sign].append(i)
548
+ block_free_count = 0
549
+
550
+ cum_sign_list[i] = cum_sign
551
+
552
+ # The previous loop has only created links between consecutive free indices,
553
+ # it is necessary to properly create links among dummy (contracted) indices,
554
+ # according to the rules described in Kahane's paper. There is only one exception
555
+ # to Kahane's rules: the negative indices, which handle the case of some
556
+ # consecutive free indices (Kahane's paper just describes dummy indices
557
+ # separated by free indices, hinting that free indices can be added without
558
+ # altering the expression result).
559
+ for i in dum:
560
+ # get the positions of the two contracted indices:
561
+ pos1 = i[0]
562
+ pos2 = i[1]
563
+
564
+ # create Kahane's upper links, i.e. the upper arcs between dummy
565
+ # (i.e. contracted) indices:
566
+ links[pos1].append(pos2)
567
+ links[pos2].append(pos1)
568
+
569
+ # create Kahane's lower links, this corresponds to the arcs below
570
+ # the line described in the paper:
571
+
572
+ # first we move `pos1` and `pos2` according to the sign of the indices:
573
+ linkpos1 = pos1 + cum_sign_list[pos1]
574
+ linkpos2 = pos2 + cum_sign_list[pos2]
575
+
576
+ # otherwise, perform some checks before creating the lower arcs:
577
+
578
+ # make sure we are not exceeding the total number of indices:
579
+ if linkpos1 >= total_number:
580
+ continue
581
+ if linkpos2 >= total_number:
582
+ continue
583
+
584
+ # make sure we are not below the first dummy index in `expression`:
585
+ if linkpos1 < first_dum_pos:
586
+ continue
587
+ if linkpos2 < first_dum_pos:
588
+ continue
589
+
590
+ # check if the previous loop created "virtual" indices between dummy
591
+ # indices, in such a case relink `linkpos1` and `linkpos2`:
592
+ if (-1-linkpos1) in links:
593
+ linkpos1 = -1-linkpos1
594
+ if (-1-linkpos2) in links:
595
+ linkpos2 = -1-linkpos2
596
+
597
+ # move only if not next to free index:
598
+ if linkpos1 >= 0 and not index_is_free[linkpos1]:
599
+ linkpos1 = pos1
600
+
601
+ if linkpos2 >=0 and not index_is_free[linkpos2]:
602
+ linkpos2 = pos2
603
+
604
+ # create the lower arcs:
605
+ if linkpos2 not in links[linkpos1]:
606
+ links[linkpos1].append(linkpos2)
607
+ if linkpos1 not in links[linkpos2]:
608
+ links[linkpos2].append(linkpos1)
609
+
610
+ # This loop starts from the `first_dum_pos` index (first dummy index)
611
+ # walks through the graph deleting the visited indices from `links`,
612
+ # it adds a gamma matrix for every free index in encounters, while it
613
+ # completely ignores dummy indices and virtual indices.
614
+ pointer = first_dum_pos
615
+ previous_pointer = 0
616
+ while True:
617
+ if pointer in links:
618
+ next_ones = links.pop(pointer)
619
+ else:
620
+ break
621
+
622
+ if previous_pointer in next_ones:
623
+ next_ones.remove(previous_pointer)
624
+
625
+ previous_pointer = pointer
626
+
627
+ if next_ones:
628
+ pointer = next_ones[0]
629
+ else:
630
+ break
631
+
632
+ if pointer == previous_pointer:
633
+ break
634
+ if pointer >=0 and free_pos[pointer] is not None:
635
+ for ri in resulting_indices:
636
+ ri.append(free_pos[pointer])
637
+
638
+ # The following loop removes the remaining connected components in `links`.
639
+ # If there are free indices inside a connected component, it gives a
640
+ # contribution to the resulting expression given by the factor
641
+ # `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
642
+ # paper represented as {gamma_a, gamma_b, ... , gamma_z},
643
+ # virtual indices are ignored. The variable `connected_components` is
644
+ # increased by one for every connected component this loop encounters.
645
+
646
+ # If the connected component has virtual and dummy indices only
647
+ # (no free indices), it contributes to `resulting_indices` by a factor of two.
648
+ # The multiplication by two is a result of the
649
+ # factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
650
+ # Note: curly brackets are meant as in the paper, as a generalized
651
+ # multi-element anticommutator!
652
+
653
+ while links:
654
+ connected_components += 1
655
+ pointer = min(links.keys())
656
+ previous_pointer = pointer
657
+ # the inner loop erases the visited indices from `links`, and it adds
658
+ # all free indices to `prepend_indices` list, virtual indices are
659
+ # ignored.
660
+ prepend_indices = []
661
+ while True:
662
+ if pointer in links:
663
+ next_ones = links.pop(pointer)
664
+ else:
665
+ break
666
+
667
+ if previous_pointer in next_ones:
668
+ if len(next_ones) > 1:
669
+ next_ones.remove(previous_pointer)
670
+
671
+ previous_pointer = pointer
672
+
673
+ if next_ones:
674
+ pointer = next_ones[0]
675
+
676
+ if pointer >= first_dum_pos and free_pos[pointer] is not None:
677
+ prepend_indices.insert(0, free_pos[pointer])
678
+ # if `prepend_indices` is void, it means there are no free indices
679
+ # in the loop (and it can be shown that there must be a virtual index),
680
+ # loops of virtual indices only contribute by a factor of two:
681
+ if len(prepend_indices) == 0:
682
+ resulting_coeff *= 2
683
+ # otherwise, add the free indices in `prepend_indices` to
684
+ # the `resulting_indices`:
685
+ else:
686
+ expr1 = prepend_indices
687
+ expr2 = list(reversed(prepend_indices))
688
+ resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
689
+
690
+ # sign correction, as described in Kahane's paper:
691
+ resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
692
+ # power of two factor, as described in Kahane's paper:
693
+ resulting_coeff *= 2**(number_of_contractions)
694
+
695
+ # If `first_dum_pos` is not zero, it means that there are trailing free gamma
696
+ # matrices in front of `expression`, so multiply by them:
697
+ resulting_indices = [ free_pos[0:first_dum_pos] + ri for ri in resulting_indices ]
698
+
699
+ resulting_expr = S.Zero
700
+ for i in resulting_indices:
701
+ temp_expr = S.One
702
+ for j in i:
703
+ temp_expr *= GammaMatrix(j)
704
+ resulting_expr += temp_expr
705
+
706
+ t = resulting_coeff * resulting_expr
707
+ t1 = None
708
+ if isinstance(t, TensAdd):
709
+ t1 = t.args[0]
710
+ elif isinstance(t, TensMul):
711
+ t1 = t
712
+ if t1:
713
+ pass
714
+ else:
715
+ t = eye(4)*t
716
+ return t
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.dense import eye, Matrix
2
+ from sympy.tensor.tensor import tensor_indices, TensorHead, tensor_heads, \
3
+ TensExpr, canon_bp
4
+ from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex, \
5
+ kahane_simplify, gamma_trace, _simplify_single_line, simplify_gamma_expression
6
+ from sympy import Symbol
7
+
8
+
9
+ def _is_tensor_eq(arg1, arg2):
10
+ arg1 = canon_bp(arg1)
11
+ arg2 = canon_bp(arg2)
12
+ if isinstance(arg1, TensExpr):
13
+ return arg1.equals(arg2)
14
+ elif isinstance(arg2, TensExpr):
15
+ return arg2.equals(arg1)
16
+ return arg1 == arg2
17
+
18
+ def execute_gamma_simplify_tests_for_function(tfunc, D):
19
+ """
20
+ Perform tests to check if sfunc is able to simplify gamma matrix expressions.
21
+
22
+ Parameters
23
+ ==========
24
+
25
+ `sfunc` a function to simplify a `TIDS`, shall return the simplified `TIDS`.
26
+ `D` the number of dimension (in most cases `D=4`).
27
+
28
+ """
29
+
30
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
31
+ a1, a2, a3, a4, a5, a6 = tensor_indices("a1:7", LorentzIndex)
32
+ mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52 = tensor_indices("mu11, mu12, mu21, mu31, mu32, mu41, mu51, mu52", LorentzIndex)
33
+ mu61, mu71, mu72 = tensor_indices("mu61, mu71, mu72", LorentzIndex)
34
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices("m0:7", LorentzIndex)
35
+
36
+ def g(xx, yy):
37
+ return (G(xx)*G(yy) + G(yy)*G(xx))/2
38
+
39
+ # Some examples taken from Kahane's paper, 4 dim only:
40
+ if D == 4:
41
+ t = (G(a1)*G(mu11)*G(a2)*G(mu21)*G(-a1)*G(mu31)*G(-a2))
42
+ assert _is_tensor_eq(tfunc(t), -4*G(mu11)*G(mu31)*G(mu21) - 4*G(mu31)*G(mu11)*G(mu21))
43
+
44
+ t = (G(a1)*G(mu11)*G(mu12)*\
45
+ G(a2)*G(mu21)*\
46
+ G(a3)*G(mu31)*G(mu32)*\
47
+ G(a4)*G(mu41)*\
48
+ G(-a2)*G(mu51)*G(mu52)*\
49
+ G(-a1)*G(mu61)*\
50
+ G(-a3)*G(mu71)*G(mu72)*\
51
+ G(-a4))
52
+ assert _is_tensor_eq(tfunc(t), \
53
+ 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu31)*G(mu32)*G(mu72)*G(mu71)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu11)*G(mu52)*G(mu51)*G(mu12)*G(mu61)*G(mu21)*G(mu41) + 16*G(mu71)*G(mu72)*G(mu32)*G(mu31)*G(mu12)*G(mu51)*G(mu52)*G(mu11)*G(mu61)*G(mu21)*G(mu41))
54
+
55
+ # Fully Lorentz-contracted expressions, these return scalars:
56
+
57
+ def add_delta(ne):
58
+ return ne * eye(4) # DiracSpinorIndex.delta(DiracSpinorIndex.auto_left, -DiracSpinorIndex.auto_right)
59
+
60
+ t = (G(mu)*G(-mu))
61
+ ts = add_delta(D)
62
+ assert _is_tensor_eq(tfunc(t), ts)
63
+
64
+ t = (G(mu)*G(nu)*G(-mu)*G(-nu))
65
+ ts = add_delta(2*D - D**2) # -8
66
+ assert _is_tensor_eq(tfunc(t), ts)
67
+
68
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
69
+ ts = add_delta(D**2) # 16
70
+ assert _is_tensor_eq(tfunc(t), ts)
71
+
72
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
73
+ ts = add_delta(4*D - 4*D**2 + D**3) # 16
74
+ assert _is_tensor_eq(tfunc(t), ts)
75
+
76
+ t = (G(mu)*G(nu)*G(rho)*G(-rho)*G(-nu)*G(-mu))
77
+ ts = add_delta(D**3) # 64
78
+ assert _is_tensor_eq(tfunc(t), ts)
79
+
80
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(-a3)*G(-a1)*G(-a2)*G(-a4))
81
+ ts = add_delta(-8*D + 16*D**2 - 8*D**3 + D**4) # -32
82
+ assert _is_tensor_eq(tfunc(t), ts)
83
+
84
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
85
+ ts = add_delta(-16*D + 24*D**2 - 8*D**3 + D**4) # 64
86
+ assert _is_tensor_eq(tfunc(t), ts)
87
+
88
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
89
+ ts = add_delta(8*D - 12*D**2 + 6*D**3 - D**4) # -32
90
+ assert _is_tensor_eq(tfunc(t), ts)
91
+
92
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a2)*G(-a1)*G(-a5)*G(-a4))
93
+ ts = add_delta(64*D - 112*D**2 + 60*D**3 - 12*D**4 + D**5) # 256
94
+ assert _is_tensor_eq(tfunc(t), ts)
95
+
96
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(-a3)*G(-a1)*G(-a2)*G(-a4)*G(-a5))
97
+ ts = add_delta(64*D - 120*D**2 + 72*D**3 - 16*D**4 + D**5) # -128
98
+ assert _is_tensor_eq(tfunc(t), ts)
99
+
100
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a3)*G(-a2)*G(-a1)*G(-a6)*G(-a5)*G(-a4))
101
+ ts = add_delta(416*D - 816*D**2 + 528*D**3 - 144*D**4 + 18*D**5 - D**6) # -128
102
+ assert _is_tensor_eq(tfunc(t), ts)
103
+
104
+ t = (G(a1)*G(a2)*G(a3)*G(a4)*G(a5)*G(a6)*G(-a2)*G(-a3)*G(-a1)*G(-a6)*G(-a4)*G(-a5))
105
+ ts = add_delta(416*D - 848*D**2 + 584*D**3 - 172*D**4 + 22*D**5 - D**6) # -128
106
+ assert _is_tensor_eq(tfunc(t), ts)
107
+
108
+ # Expressions with free indices:
109
+
110
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
111
+ assert _is_tensor_eq(tfunc(t), (-2*G(sigma)*G(rho)*G(nu) + (4-D)*G(nu)*G(rho)*G(sigma)))
112
+
113
+ t = (G(mu)*G(nu)*G(-mu))
114
+ assert _is_tensor_eq(tfunc(t), (2-D)*G(nu))
115
+
116
+ t = (G(mu)*G(nu)*G(rho)*G(-mu))
117
+ assert _is_tensor_eq(tfunc(t), 2*G(nu)*G(rho) + 2*G(rho)*G(nu) - (4-D)*G(nu)*G(rho))
118
+
119
+ t = 2*G(m2)*G(m0)*G(m1)*G(-m0)*G(-m1)
120
+ st = tfunc(t)
121
+ assert _is_tensor_eq(st, (D*(-2*D + 4))*G(m2))
122
+
123
+ t = G(m2)*G(m0)*G(m1)*G(-m0)*G(-m2)
124
+ st = tfunc(t)
125
+ assert _is_tensor_eq(st, ((-D + 2)**2)*G(m1))
126
+
127
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)
128
+ st = tfunc(t)
129
+ assert _is_tensor_eq(st, (D - 4)*G(m0)*G(m2)*G(m3) + 4*G(m0)*g(m2, m3))
130
+
131
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(-m1)*G(-m0)
132
+ st = tfunc(t)
133
+ assert _is_tensor_eq(st, ((D - 4)**2)*G(m2)*G(m3) + (8*D - 16)*g(m2, m3))
134
+
135
+ t = G(m2)*G(m0)*G(m1)*G(-m2)*G(-m0)
136
+ st = tfunc(t)
137
+ assert _is_tensor_eq(st, ((-D + 2)*(D - 4) + 4)*G(m1))
138
+
139
+ t = G(m3)*G(m1)*G(m0)*G(m2)*G(-m3)*G(-m0)*G(-m2)
140
+ st = tfunc(t)
141
+ assert _is_tensor_eq(st, (-4*D + (-D + 2)**2*(D - 4) + 8)*G(m1))
142
+
143
+ t = 2*G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)
144
+ st = tfunc(t)
145
+ assert _is_tensor_eq(st, ((-2*D + 8)*G(m1)*G(m2)*G(m3) - 4*G(m3)*G(m2)*G(m1)))
146
+
147
+ t = G(m5)*G(m0)*G(m1)*G(m4)*G(m2)*G(-m4)*G(m3)*G(-m0)
148
+ st = tfunc(t)
149
+ assert _is_tensor_eq(st, (((-D + 2)*(-D + 4))*G(m5)*G(m1)*G(m2)*G(m3) + (2*D - 4)*G(m5)*G(m3)*G(m2)*G(m1)))
150
+
151
+ t = -G(m0)*G(m1)*G(m2)*G(m3)*G(-m0)*G(m4)
152
+ st = tfunc(t)
153
+ assert _is_tensor_eq(st, ((D - 4)*G(m1)*G(m2)*G(m3)*G(m4) + 2*G(m3)*G(m2)*G(m1)*G(m4)))
154
+
155
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
156
+ st = tfunc(t)
157
+
158
+ result1 = ((-D + 4)**2 + 4)*G(m1)*G(m2)*G(m3)*G(m4) +\
159
+ (4*D - 16)*G(m3)*G(m2)*G(m1)*G(m4) + (4*D - 16)*G(m4)*G(m1)*G(m2)*G(m3)\
160
+ + 4*G(m2)*G(m1)*G(m4)*G(m3) + 4*G(m3)*G(m4)*G(m1)*G(m2) +\
161
+ 4*G(m4)*G(m3)*G(m2)*G(m1)
162
+
163
+ # Kahane's algorithm yields this result, which is equivalent to `result1`
164
+ # in four dimensions, but is not automatically recognized as equal:
165
+ result2 = 8*G(m1)*G(m2)*G(m3)*G(m4) + 8*G(m4)*G(m3)*G(m2)*G(m1)
166
+
167
+ if D == 4:
168
+ assert _is_tensor_eq(st, (result1)) or _is_tensor_eq(st, (result2))
169
+ else:
170
+ assert _is_tensor_eq(st, (result1))
171
+
172
+ # and a few very simple cases, with no contracted indices:
173
+
174
+ t = G(m0)
175
+ st = tfunc(t)
176
+ assert _is_tensor_eq(st, t)
177
+
178
+ t = -7*G(m0)
179
+ st = tfunc(t)
180
+ assert _is_tensor_eq(st, t)
181
+
182
+ t = 224*G(m0)*G(m1)*G(-m2)*G(m3)
183
+ st = tfunc(t)
184
+ assert _is_tensor_eq(st, t)
185
+
186
+
187
+ def test_kahane_algorithm():
188
+ # Wrap this function to convert to and from TIDS:
189
+
190
+ def tfunc(e):
191
+ return _simplify_single_line(e)
192
+
193
+ execute_gamma_simplify_tests_for_function(tfunc, D=4)
194
+
195
+
196
+ def test_kahane_simplify1():
197
+ i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14,i15 = tensor_indices('i0:16', LorentzIndex)
198
+ mu, nu, rho, sigma = tensor_indices("mu, nu, rho, sigma", LorentzIndex)
199
+ D = 4
200
+ t = G(i0)*G(i1)
201
+ r = kahane_simplify(t)
202
+ assert r.equals(t)
203
+
204
+ t = G(i0)*G(i1)*G(-i0)
205
+ r = kahane_simplify(t)
206
+ assert r.equals(-2*G(i1))
207
+ t = G(i0)*G(i1)*G(-i0)
208
+ r = kahane_simplify(t)
209
+ assert r.equals(-2*G(i1))
210
+
211
+ t = G(i0)*G(i1)
212
+ r = kahane_simplify(t)
213
+ assert r.equals(t)
214
+ t = G(i0)*G(i1)
215
+ r = kahane_simplify(t)
216
+ assert r.equals(t)
217
+ t = G(i0)*G(-i0)
218
+ r = kahane_simplify(t)
219
+ assert r.equals(4*eye(4))
220
+ t = G(i0)*G(-i0)
221
+ r = kahane_simplify(t)
222
+ assert r.equals(4*eye(4))
223
+ t = G(i0)*G(-i0)
224
+ r = kahane_simplify(t)
225
+ assert r.equals(4*eye(4))
226
+ t = G(i0)*G(i1)*G(-i0)
227
+ r = kahane_simplify(t)
228
+ assert r.equals(-2*G(i1))
229
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
230
+ r = kahane_simplify(t)
231
+ assert r.equals((2*D - D**2)*eye(4))
232
+ t = G(i0)*G(i1)*G(-i0)*G(-i1)
233
+ r = kahane_simplify(t)
234
+ assert r.equals((2*D - D**2)*eye(4))
235
+ t = G(i0)*G(-i0)*G(i1)*G(-i1)
236
+ r = kahane_simplify(t)
237
+ assert r.equals(16*eye(4))
238
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
239
+ r = kahane_simplify(t)
240
+ assert r.equals(D**2*eye(4))
241
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
242
+ r = kahane_simplify(t)
243
+ assert r.equals(D**2*eye(4))
244
+ t = (G(mu)*G(nu)*G(-nu)*G(-mu))
245
+ r = kahane_simplify(t)
246
+ assert r.equals(D**2*eye(4))
247
+ t = (G(mu)*G(nu)*G(-rho)*G(-nu)*G(-mu)*G(rho))
248
+ r = kahane_simplify(t)
249
+ assert r.equals((4*D - 4*D**2 + D**3)*eye(4))
250
+ t = (G(-mu)*G(-nu)*G(-rho)*G(-sigma)*G(nu)*G(mu)*G(sigma)*G(rho))
251
+ r = kahane_simplify(t)
252
+ assert r.equals((-16*D + 24*D**2 - 8*D**3 + D**4)*eye(4))
253
+ t = (G(-mu)*G(nu)*G(-rho)*G(sigma)*G(rho)*G(-nu)*G(mu)*G(-sigma))
254
+ r = kahane_simplify(t)
255
+ assert r.equals((8*D - 12*D**2 + 6*D**3 - D**4)*eye(4))
256
+
257
+ # Expressions with free indices:
258
+ t = (G(mu)*G(nu)*G(rho)*G(sigma)*G(-mu))
259
+ r = kahane_simplify(t)
260
+ assert r.equals(-2*G(sigma)*G(rho)*G(nu))
261
+ t = (G(mu)*G(-mu)*G(rho)*G(sigma))
262
+ r = kahane_simplify(t)
263
+ assert r.equals(4*G(rho)*G(sigma))
264
+ t = (G(rho)*G(sigma)*G(mu)*G(-mu))
265
+ r = kahane_simplify(t)
266
+ assert r.equals(4*G(rho)*G(sigma))
267
+
268
+ def test_gamma_matrix_class():
269
+ i, j, k = tensor_indices('i,j,k', LorentzIndex)
270
+
271
+ # define another type of TensorHead to see if exprs are correctly handled:
272
+ A = TensorHead('A', [LorentzIndex])
273
+
274
+ t = A(k)*G(i)*G(-i)
275
+ ts = simplify_gamma_expression(t)
276
+ assert _is_tensor_eq(ts, Matrix([
277
+ [4, 0, 0, 0],
278
+ [0, 4, 0, 0],
279
+ [0, 0, 4, 0],
280
+ [0, 0, 0, 4]])*A(k))
281
+
282
+ t = G(i)*A(k)*G(j)
283
+ ts = simplify_gamma_expression(t)
284
+ assert _is_tensor_eq(ts, A(k)*G(i)*G(j))
285
+
286
+ execute_gamma_simplify_tests_for_function(simplify_gamma_expression, D=4)
287
+
288
+
289
+ def test_gamma_matrix_trace():
290
+ g = LorentzIndex.metric
291
+
292
+ m0, m1, m2, m3, m4, m5, m6 = tensor_indices('m0:7', LorentzIndex)
293
+ n0, n1, n2, n3, n4, n5 = tensor_indices('n0:6', LorentzIndex)
294
+
295
+ # working in D=4 dimensions
296
+ D = 4
297
+
298
+ # traces of odd number of gamma matrices are zero:
299
+ t = G(m0)
300
+ t1 = gamma_trace(t)
301
+ assert t1.equals(0)
302
+
303
+ t = G(m0)*G(m1)*G(m2)
304
+ t1 = gamma_trace(t)
305
+ assert t1.equals(0)
306
+
307
+ t = G(m0)*G(m1)*G(-m0)
308
+ t1 = gamma_trace(t)
309
+ assert t1.equals(0)
310
+
311
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)
312
+ t1 = gamma_trace(t)
313
+ assert t1.equals(0)
314
+
315
+ # traces without internal contractions:
316
+ t = G(m0)*G(m1)
317
+ t1 = gamma_trace(t)
318
+ assert _is_tensor_eq(t1, 4*g(m0, m1))
319
+
320
+ t = G(m0)*G(m1)*G(m2)*G(m3)
321
+ t1 = gamma_trace(t)
322
+ t2 = -4*g(m0, m2)*g(m1, m3) + 4*g(m0, m1)*g(m2, m3) + 4*g(m0, m3)*g(m1, m2)
323
+ assert _is_tensor_eq(t1, t2)
324
+
325
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)
326
+ t1 = gamma_trace(t)
327
+ t2 = t1*g(-m0, -m5)
328
+ t2 = t2.contract_metric(g)
329
+ assert _is_tensor_eq(t2, D*gamma_trace(G(m1)*G(m2)*G(m3)*G(m4)))
330
+
331
+ # traces of expressions with internal contractions:
332
+ t = G(m0)*G(-m0)
333
+ t1 = gamma_trace(t)
334
+ assert t1.equals(4*D)
335
+
336
+ t = G(m0)*G(m1)*G(-m0)*G(-m1)
337
+ t1 = gamma_trace(t)
338
+ assert t1.equals(8*D - 4*D**2)
339
+
340
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)
341
+ t1 = gamma_trace(t)
342
+ t2 = (-4*D)*g(m1, m3)*g(m2, m4) + (4*D)*g(m1, m2)*g(m3, m4) + \
343
+ (4*D)*g(m1, m4)*g(m2, m3)
344
+ assert _is_tensor_eq(t1, t2)
345
+
346
+ t = G(-m5)*G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(-m0)*G(m5)
347
+ t1 = gamma_trace(t)
348
+ t2 = (32*D + 4*(-D + 4)**2 - 64)*(g(m1, m2)*g(m3, m4) - \
349
+ g(m1, m3)*g(m2, m4) + g(m1, m4)*g(m2, m3))
350
+ assert _is_tensor_eq(t1, t2)
351
+
352
+ t = G(m0)*G(m1)*G(-m0)*G(m3)
353
+ t1 = gamma_trace(t)
354
+ assert t1.equals((-4*D + 8)*g(m1, m3))
355
+
356
+ # p, q = S1('p,q')
357
+ # ps = p(m0)*G(-m0)
358
+ # qs = q(m0)*G(-m0)
359
+ # t = ps*qs*ps*qs
360
+ # t1 = gamma_trace(t)
361
+ # assert t1 == 8*p(m0)*q(-m0)*p(m1)*q(-m1) - 4*p(m0)*p(-m0)*q(m1)*q(-m1)
362
+
363
+ t = G(m0)*G(m1)*G(m2)*G(m3)*G(m4)*G(m5)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)*G(-m5)
364
+ t1 = gamma_trace(t)
365
+ assert t1.equals(-4*D**6 + 120*D**5 - 1040*D**4 + 3360*D**3 - 4480*D**2 + 2048*D)
366
+
367
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(-n2)*G(-n1)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
368
+ t1 = gamma_trace(t)
369
+ tresu = -7168*D + 16768*D**2 - 14400*D**3 + 5920*D**4 - 1232*D**5 + 120*D**6 - 4*D**7
370
+ assert t1.equals(tresu)
371
+
372
+ # checked with Mathematica
373
+ # In[1]:= <<Tracer.m
374
+ # In[2]:= Spur[l];
375
+ # In[3]:= GammaTrace[l, {m0},{m1},{n1},{m2},{n2},{m3},{m4},{n3},{n4},{m0},{m1},{m2},{m3},{m4}]
376
+ t = G(m0)*G(m1)*G(n1)*G(m2)*G(n2)*G(m3)*G(m4)*G(n3)*G(n4)*G(-m0)*G(-m1)*G(-m2)*G(-m3)*G(-m4)
377
+ t1 = gamma_trace(t)
378
+ # t1 = t1.expand_coeff()
379
+ c1 = -4*D**5 + 120*D**4 - 1200*D**3 + 5280*D**2 - 10560*D + 7808
380
+ c2 = -4*D**5 + 88*D**4 - 560*D**3 + 1440*D**2 - 1600*D + 640
381
+ assert _is_tensor_eq(t1, c1*g(n1, n4)*g(n2, n3) + c2*g(n1, n2)*g(n3, n4) + \
382
+ (-c1)*g(n1, n3)*g(n2, n4))
383
+
384
+ p, q = tensor_heads('p,q', [LorentzIndex])
385
+ ps = p(m0)*G(-m0)
386
+ qs = q(m0)*G(-m0)
387
+ p2 = p(m0)*p(-m0)
388
+ q2 = q(m0)*q(-m0)
389
+ pq = p(m0)*q(-m0)
390
+ t = ps*qs*ps*qs
391
+ r = gamma_trace(t)
392
+ assert _is_tensor_eq(r, 8*pq*pq - 4*p2*q2)
393
+ t = ps*qs*ps*qs*ps*qs
394
+ r = gamma_trace(t)
395
+ assert _is_tensor_eq(r, -12*p2*pq*q2 + 16*pq*pq*pq)
396
+ t = ps*qs*ps*qs*ps*qs*ps*qs
397
+ r = gamma_trace(t)
398
+ assert _is_tensor_eq(r, -32*pq*pq*p2*q2 + 32*pq*pq*pq*pq + 4*p2*p2*q2*q2)
399
+
400
+ t = 4*p(m1)*p(m0)*p(-m0)*q(-m1)*q(m2)*q(-m2)
401
+ assert _is_tensor_eq(gamma_trace(t), t)
402
+ t = ps*ps*ps*ps*ps*ps*ps*ps
403
+ r = gamma_trace(t)
404
+ assert r.equals(4*p2*p2*p2*p2)
405
+
406
+
407
+ def test_bug_13636():
408
+ """Test issue 13636 regarding handling traces of sums of products
409
+ of GammaMatrix mixed with other factors."""
410
+ pi, ki, pf = tensor_heads("pi, ki, pf", [LorentzIndex])
411
+ i0, i1, i2, i3, i4 = tensor_indices("i0:5", LorentzIndex)
412
+ x = Symbol("x")
413
+ pis = pi(i2) * G(-i2)
414
+ kis = ki(i3) * G(-i3)
415
+ pfs = pf(i4) * G(-i4)
416
+
417
+ a = pfs * G(i0) * kis * G(i1) * pis * G(-i1) * kis * G(-i0)
418
+ b = pfs * G(i0) * kis * G(i1) * pis * x * G(-i0) * pi(-i1)
419
+ ta = gamma_trace(a)
420
+ tb = gamma_trace(b)
421
+ t_a_plus_b = gamma_trace(a + b)
422
+ assert ta == 4 * (
423
+ -4 * ki(i0) * ki(-i0) * pf(i1) * pi(-i1)
424
+ + 8 * ki(i0) * ki(i1) * pf(-i0) * pi(-i1)
425
+ )
426
+ assert tb == -8 * x * ki(i0) * pf(-i0) * pi(i1) * pi(-i1)
427
+ assert t_a_plus_b == ta + tb
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/hydrogen.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+ from sympy.core.singleton import S
3
+ from sympy.functions.combinatorial.factorials import factorial
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.polynomials import assoc_laguerre
7
+ from sympy.functions.special.spherical_harmonics import Ynm
8
+
9
+
10
+ def R_nl(n, l, r, Z=1):
11
+ """
12
+ Returns the Hydrogen radial wavefunction R_{nl}.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ n : integer
18
+ Principal Quantum Number which is
19
+ an integer with possible values as 1, 2, 3, 4,...
20
+ l : integer
21
+ ``l`` is the Angular Momentum Quantum Number with
22
+ values ranging from 0 to ``n-1``.
23
+ r :
24
+ Radial coordinate.
25
+ Z :
26
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
27
+
28
+ Everything is in Hartree atomic units.
29
+
30
+ Examples
31
+ ========
32
+
33
+ >>> from sympy.physics.hydrogen import R_nl
34
+ >>> from sympy.abc import r, Z
35
+ >>> R_nl(1, 0, r, Z)
36
+ 2*sqrt(Z**3)*exp(-Z*r)
37
+ >>> R_nl(2, 0, r, Z)
38
+ sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4
39
+ >>> R_nl(2, 1, r, Z)
40
+ sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12
41
+
42
+ For Hydrogen atom, you can just use the default value of Z=1:
43
+
44
+ >>> R_nl(1, 0, r)
45
+ 2*exp(-r)
46
+ >>> R_nl(2, 0, r)
47
+ sqrt(2)*(2 - r)*exp(-r/2)/4
48
+ >>> R_nl(3, 0, r)
49
+ 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27
50
+
51
+ For Silver atom, you would use Z=47:
52
+
53
+ >>> R_nl(1, 0, r, Z=47)
54
+ 94*sqrt(47)*exp(-47*r)
55
+ >>> R_nl(2, 0, r, Z=47)
56
+ 47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4
57
+ >>> R_nl(3, 0, r, Z=47)
58
+ 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27
59
+
60
+ The normalization of the radial wavefunction is:
61
+
62
+ >>> from sympy import integrate, oo
63
+ >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo))
64
+ 1
65
+ >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo))
66
+ 1
67
+ >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo))
68
+ 1
69
+
70
+ It holds for any atomic number:
71
+
72
+ >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo))
73
+ 1
74
+ >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo))
75
+ 1
76
+ >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo))
77
+ 1
78
+
79
+ """
80
+ # sympify arguments
81
+ n, l, r, Z = map(S, [n, l, r, Z])
82
+ # radial quantum number
83
+ n_r = n - l - 1
84
+ # rescaled "r"
85
+ a = 1/Z # Bohr radius
86
+ r0 = 2 * r / (n * a)
87
+ # normalization coefficient
88
+ C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l)))
89
+ # This is an equivalent normalization coefficient, that can be found in
90
+ # some books. Both coefficients seem to be the same fast:
91
+ # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l)))
92
+ return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2)
93
+
94
+
95
+ def Psi_nlm(n, l, m, r, phi, theta, Z=1):
96
+ """
97
+ Returns the Hydrogen wave function psi_{nlm}. It's the product of
98
+ the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}.
99
+
100
+ Parameters
101
+ ==========
102
+
103
+ n : integer
104
+ Principal Quantum Number which is
105
+ an integer with possible values as 1, 2, 3, 4,...
106
+ l : integer
107
+ ``l`` is the Angular Momentum Quantum Number with
108
+ values ranging from 0 to ``n-1``.
109
+ m : integer
110
+ ``m`` is the Magnetic Quantum Number with values
111
+ ranging from ``-l`` to ``l``.
112
+ r :
113
+ radial coordinate
114
+ phi :
115
+ azimuthal angle
116
+ theta :
117
+ polar angle
118
+ Z :
119
+ atomic number (1 for Hydrogen, 2 for Helium, ...)
120
+
121
+ Everything is in Hartree atomic units.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy.physics.hydrogen import Psi_nlm
127
+ >>> from sympy import Symbol
128
+ >>> r=Symbol("r", positive=True)
129
+ >>> phi=Symbol("phi", real=True)
130
+ >>> theta=Symbol("theta", real=True)
131
+ >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True)
132
+ >>> Psi_nlm(1,0,0,r,phi,theta,Z)
133
+ Z**(3/2)*exp(-Z*r)/sqrt(pi)
134
+ >>> Psi_nlm(2,1,1,r,phi,theta,Z)
135
+ -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi))
136
+
137
+ Integrating the absolute square of a hydrogen wavefunction psi_{nlm}
138
+ over the whole space leads 1.
139
+
140
+ The normalization of the hydrogen wavefunctions Psi_nlm is:
141
+
142
+ >>> from sympy import integrate, conjugate, pi, oo, sin
143
+ >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z)
144
+ >>> abs_sqrd=wf*conjugate(wf)
145
+ >>> jacobi=r**2*sin(theta)
146
+ >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi))
147
+ 1
148
+ """
149
+
150
+ # sympify arguments
151
+ n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z])
152
+ # check if values for n,l,m make physically sense
153
+ if n.is_integer and n < 1:
154
+ raise ValueError("'n' must be positive integer")
155
+ if l.is_integer and not (n > l):
156
+ raise ValueError("'n' must be greater than 'l'")
157
+ if m.is_integer and not (abs(m) <= l):
158
+ raise ValueError("|'m'| must be less or equal 'l'")
159
+ # return the hydrogen wave function
160
+ return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True)
161
+
162
+
163
+ def E_nl(n, Z=1):
164
+ """
165
+ Returns the energy of the state (n, l) in Hartree atomic units.
166
+
167
+ The energy does not depend on "l".
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ n : integer
173
+ Principal Quantum Number which is
174
+ an integer with possible values as 1, 2, 3, 4,...
175
+ Z :
176
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy.physics.hydrogen import E_nl
182
+ >>> from sympy.abc import n, Z
183
+ >>> E_nl(n, Z)
184
+ -Z**2/(2*n**2)
185
+ >>> E_nl(1)
186
+ -1/2
187
+ >>> E_nl(2)
188
+ -1/8
189
+ >>> E_nl(3)
190
+ -1/18
191
+ >>> E_nl(3, 47)
192
+ -2209/18
193
+
194
+ """
195
+ n, Z = S(n), S(Z)
196
+ if n.is_integer and (n < 1):
197
+ raise ValueError("'n' must be positive integer")
198
+ return -Z**2/(2*n**2)
199
+
200
+
201
+ def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")):
202
+ """
203
+ Returns the relativistic energy of the state (n, l, spin) in Hartree atomic
204
+ units.
205
+
206
+ The energy is calculated from the Dirac equation. The rest mass energy is
207
+ *not* included.
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ n : integer
213
+ Principal Quantum Number which is
214
+ an integer with possible values as 1, 2, 3, 4,...
215
+ l : integer
216
+ ``l`` is the Angular Momentum Quantum Number with
217
+ values ranging from 0 to ``n-1``.
218
+ spin_up :
219
+ True if the electron spin is up (default), otherwise down
220
+ Z :
221
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
222
+ c :
223
+ Speed of light in atomic units. Default value is 137.035999037,
224
+ taken from https://arxiv.org/abs/1012.3627
225
+
226
+ Examples
227
+ ========
228
+
229
+ >>> from sympy.physics.hydrogen import E_nl_dirac
230
+ >>> E_nl_dirac(1, 0)
231
+ -0.500006656595360
232
+
233
+ >>> E_nl_dirac(2, 0)
234
+ -0.125002080189006
235
+ >>> E_nl_dirac(2, 1)
236
+ -0.125000416028342
237
+ >>> E_nl_dirac(2, 1, False)
238
+ -0.125002080189006
239
+
240
+ >>> E_nl_dirac(3, 0)
241
+ -0.0555562951740285
242
+ >>> E_nl_dirac(3, 1)
243
+ -0.0555558020932949
244
+ >>> E_nl_dirac(3, 1, False)
245
+ -0.0555562951740285
246
+ >>> E_nl_dirac(3, 2)
247
+ -0.0555556377366884
248
+ >>> E_nl_dirac(3, 2, False)
249
+ -0.0555558020932949
250
+
251
+ """
252
+ n, l, Z, c = map(S, [n, l, Z, c])
253
+ if not (l >= 0):
254
+ raise ValueError("'l' must be positive or zero")
255
+ if not (n > l):
256
+ raise ValueError("'n' must be greater than 'l'")
257
+ if (l == 0 and spin_up is False):
258
+ raise ValueError("Spin must be up for l==0.")
259
+ # skappa is sign*kappa, where sign contains the correct sign
260
+ if spin_up:
261
+ skappa = -l - 1
262
+ else:
263
+ skappa = -l
264
+ beta = sqrt(skappa**2 - Z**2/c**2)
265
+ return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/matrices.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Known matrices related to physics"""
2
+
3
+ from sympy.core.numbers import I
4
+ from sympy.matrices.dense import MutableDenseMatrix as Matrix
5
+ from sympy.utilities.decorator import deprecated
6
+
7
+
8
+ def msigma(i):
9
+ r"""Returns a Pauli matrix `\sigma_i` with `i=1,2,3`.
10
+
11
+ References
12
+ ==========
13
+
14
+ .. [1] https://en.wikipedia.org/wiki/Pauli_matrices
15
+
16
+ Examples
17
+ ========
18
+
19
+ >>> from sympy.physics.matrices import msigma
20
+ >>> msigma(1)
21
+ Matrix([
22
+ [0, 1],
23
+ [1, 0]])
24
+ """
25
+ if i == 1:
26
+ mat = (
27
+ (0, 1),
28
+ (1, 0)
29
+ )
30
+ elif i == 2:
31
+ mat = (
32
+ (0, -I),
33
+ (I, 0)
34
+ )
35
+ elif i == 3:
36
+ mat = (
37
+ (1, 0),
38
+ (0, -1)
39
+ )
40
+ else:
41
+ raise IndexError("Invalid Pauli index")
42
+ return Matrix(mat)
43
+
44
+
45
+ def pat_matrix(m, dx, dy, dz):
46
+ """Returns the Parallel Axis Theorem matrix to translate the inertia
47
+ matrix a distance of `(dx, dy, dz)` for a body of mass m.
48
+
49
+ Examples
50
+ ========
51
+
52
+ To translate a body having a mass of 2 units a distance of 1 unit along
53
+ the `x`-axis we get:
54
+
55
+ >>> from sympy.physics.matrices import pat_matrix
56
+ >>> pat_matrix(2, 1, 0, 0)
57
+ Matrix([
58
+ [0, 0, 0],
59
+ [0, 2, 0],
60
+ [0, 0, 2]])
61
+
62
+ """
63
+ dxdy = -dx*dy
64
+ dydz = -dy*dz
65
+ dzdx = -dz*dx
66
+ dxdx = dx**2
67
+ dydy = dy**2
68
+ dzdz = dz**2
69
+ mat = ((dydy + dzdz, dxdy, dzdx),
70
+ (dxdy, dxdx + dzdz, dydz),
71
+ (dzdx, dydz, dydy + dxdx))
72
+ return m*Matrix(mat)
73
+
74
+
75
+ def mgamma(mu, lower=False):
76
+ r"""Returns a Dirac gamma matrix `\gamma^\mu` in the standard
77
+ (Dirac) representation.
78
+
79
+ Explanation
80
+ ===========
81
+
82
+ If you want `\gamma_\mu`, use ``gamma(mu, True)``.
83
+
84
+ We use a convention:
85
+
86
+ `\gamma^5 = i \cdot \gamma^0 \cdot \gamma^1 \cdot \gamma^2 \cdot \gamma^3`
87
+
88
+ `\gamma_5 = i \cdot \gamma_0 \cdot \gamma_1 \cdot \gamma_2 \cdot \gamma_3 = - \gamma^5`
89
+
90
+ References
91
+ ==========
92
+
93
+ .. [1] https://en.wikipedia.org/wiki/Gamma_matrices
94
+
95
+ Examples
96
+ ========
97
+
98
+ >>> from sympy.physics.matrices import mgamma
99
+ >>> mgamma(1)
100
+ Matrix([
101
+ [ 0, 0, 0, 1],
102
+ [ 0, 0, 1, 0],
103
+ [ 0, -1, 0, 0],
104
+ [-1, 0, 0, 0]])
105
+ """
106
+ if mu not in (0, 1, 2, 3, 5):
107
+ raise IndexError("Invalid Dirac index")
108
+ if mu == 0:
109
+ mat = (
110
+ (1, 0, 0, 0),
111
+ (0, 1, 0, 0),
112
+ (0, 0, -1, 0),
113
+ (0, 0, 0, -1)
114
+ )
115
+ elif mu == 1:
116
+ mat = (
117
+ (0, 0, 0, 1),
118
+ (0, 0, 1, 0),
119
+ (0, -1, 0, 0),
120
+ (-1, 0, 0, 0)
121
+ )
122
+ elif mu == 2:
123
+ mat = (
124
+ (0, 0, 0, -I),
125
+ (0, 0, I, 0),
126
+ (0, I, 0, 0),
127
+ (-I, 0, 0, 0)
128
+ )
129
+ elif mu == 3:
130
+ mat = (
131
+ (0, 0, 1, 0),
132
+ (0, 0, 0, -1),
133
+ (-1, 0, 0, 0),
134
+ (0, 1, 0, 0)
135
+ )
136
+ elif mu == 5:
137
+ mat = (
138
+ (0, 0, 1, 0),
139
+ (0, 0, 0, 1),
140
+ (1, 0, 0, 0),
141
+ (0, 1, 0, 0)
142
+ )
143
+ m = Matrix(mat)
144
+ if lower:
145
+ if mu in (1, 2, 3, 5):
146
+ m = -m
147
+ return m
148
+
149
+ #Minkowski tensor using the convention (+,-,-,-) used in the Quantum Field
150
+ #Theory
151
+ minkowski_tensor = Matrix( (
152
+ (1, 0, 0, 0),
153
+ (0, -1, 0, 0),
154
+ (0, 0, -1, 0),
155
+ (0, 0, 0, -1)
156
+ ))
157
+
158
+
159
+ @deprecated(
160
+ """
161
+ The sympy.physics.matrices.mdft method is deprecated. Use
162
+ sympy.DFT(n).as_explicit() instead.
163
+ """,
164
+ deprecated_since_version="1.9",
165
+ active_deprecations_target="deprecated-physics-mdft",
166
+ )
167
+ def mdft(n):
168
+ r"""
169
+ .. deprecated:: 1.9
170
+
171
+ Use DFT from sympy.matrices.expressions.fourier instead.
172
+
173
+ To get identical behavior to ``mdft(n)``, use ``DFT(n).as_explicit()``.
174
+ """
175
+ from sympy.matrices.expressions.fourier import DFT
176
+ return DFT(n).as_mutable()
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'vector',
3
+
4
+ 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross',
5
+ 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations',
6
+ 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint',
7
+ 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl',
8
+ 'divergence', 'gradient', 'is_conservative', 'is_solenoidal',
9
+ 'scalar_potential', 'scalar_potential_difference',
10
+
11
+ 'KanesMethod',
12
+
13
+ 'RigidBody',
14
+
15
+ 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy',
16
+ 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint',
17
+ 'mlatex', 'msubs', 'find_dynamicsymbols',
18
+
19
+ 'inertia', 'inertia_of_point_mass', 'Inertia',
20
+
21
+ 'Force', 'Torque',
22
+
23
+ 'Particle',
24
+
25
+ 'LagrangesMethod',
26
+
27
+ 'Linearizer',
28
+
29
+ 'Body',
30
+
31
+ 'SymbolicSystem', 'System',
32
+
33
+ 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint',
34
+ 'SphericalJoint', 'WeldJoint',
35
+
36
+ 'JointsMethod',
37
+
38
+ 'WrappingCylinder', 'WrappingGeometryBase', 'WrappingSphere',
39
+
40
+ 'PathwayBase', 'LinearPathway', 'ObstacleSetPathway', 'WrappingPathway',
41
+
42
+ 'ActuatorBase', 'ForceActuator', 'LinearDamper', 'LinearSpring',
43
+ 'TorqueActuator', 'DuffingSpring', 'CoulombKineticFriction',
44
+ ]
45
+
46
+ from sympy.physics import vector
47
+
48
+ from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point,
49
+ cross, dot, express, time_derivative, outer, kinematic_equations,
50
+ get_motion_params, partial_velocity, dynamicsymbols, vprint,
51
+ vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence,
52
+ gradient, is_conservative, is_solenoidal, scalar_potential,
53
+ scalar_potential_difference)
54
+
55
+ from .kane import KanesMethod
56
+
57
+ from .rigidbody import RigidBody
58
+
59
+ from .functions import (linear_momentum, angular_momentum, kinetic_energy,
60
+ potential_energy, Lagrangian, mechanics_printing,
61
+ mprint, msprint, mpprint, mlatex, msubs,
62
+ find_dynamicsymbols)
63
+
64
+ from .inertia import inertia, inertia_of_point_mass, Inertia
65
+
66
+ from .loads import Force, Torque
67
+
68
+ from .particle import Particle
69
+
70
+ from .lagrange import LagrangesMethod
71
+
72
+ from .linearize import Linearizer
73
+
74
+ from .body import Body
75
+
76
+ from .system import SymbolicSystem, System
77
+
78
+ from .jointsmethod import JointsMethod
79
+
80
+ from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint,
81
+ SphericalJoint, WeldJoint)
82
+
83
+ from .wrapping_geometry import (WrappingCylinder, WrappingGeometryBase,
84
+ WrappingSphere)
85
+
86
+ from .pathway import (PathwayBase, LinearPathway, ObstacleSetPathway,
87
+ WrappingPathway)
88
+
89
+ from .actuator import (ActuatorBase, ForceActuator, LinearDamper, LinearSpring,
90
+ TorqueActuator, DuffingSpring, CoulombKineticFriction)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/actuator.py ADDED
@@ -0,0 +1,1147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of actuators for linked force and torque application."""
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy import S, sympify, exp, sign
6
+ from sympy.physics.mechanics.joint import PinJoint
7
+ from sympy.physics.mechanics.loads import Torque
8
+ from sympy.physics.mechanics.pathway import PathwayBase
9
+ from sympy.physics.mechanics.rigidbody import RigidBody
10
+ from sympy.physics.vector import ReferenceFrame, Vector
11
+
12
+
13
+ __all__ = [
14
+ 'ActuatorBase',
15
+ 'ForceActuator',
16
+ 'LinearDamper',
17
+ 'LinearSpring',
18
+ 'TorqueActuator',
19
+ 'DuffingSpring',
20
+ 'CoulombKineticFriction',
21
+ ]
22
+
23
+
24
+ class ActuatorBase(ABC):
25
+ """Abstract base class for all actuator classes to inherit from.
26
+
27
+ Notes
28
+ =====
29
+
30
+ Instances of this class cannot be directly instantiated by users. However,
31
+ it can be used to created custom actuator types through subclassing.
32
+
33
+ """
34
+
35
+ def __init__(self):
36
+ """Initializer for ``ActuatorBase``."""
37
+ pass
38
+
39
+ @abstractmethod
40
+ def to_loads(self):
41
+ """Loads required by the equations of motion method classes.
42
+
43
+ Explanation
44
+ ===========
45
+
46
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
47
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
48
+ when constructing the equations of motion. This method acts as a
49
+ utility to produce the correctly-structred pairs of points and vectors
50
+ required so that these can be easily concatenated with other items in
51
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
52
+ loads are also in the correct form to also be passed to the other
53
+ equations of motion method classes, e.g. ``LagrangesMethod``.
54
+
55
+ """
56
+ pass
57
+
58
+ def __repr__(self):
59
+ """Default representation of an actuator."""
60
+ return f'{self.__class__.__name__}()'
61
+
62
+
63
+ class ForceActuator(ActuatorBase):
64
+ """Force-producing actuator.
65
+
66
+ Explanation
67
+ ===========
68
+
69
+ A ``ForceActuator`` is an actuator that produces a (expansile) force along
70
+ its length.
71
+
72
+ A force actuator uses a pathway instance to determine the direction and
73
+ number of forces that it applies to a system. Consider the simplest case
74
+ where a ``LinearPathway`` instance is used. This pathway is made up of two
75
+ points that can move relative to each other, and results in a pair of equal
76
+ and opposite forces acting on the endpoints. If the positive time-varying
77
+ Euclidean distance between the two points is defined, then the "extension
78
+ velocity" is the time derivative of this distance. The extension velocity
79
+ is positive when the two points are moving away from each other and
80
+ negative when moving closer to each other. The direction for the force
81
+ acting on either point is determined by constructing a unit vector directed
82
+ from the other point to this point. This establishes a sign convention such
83
+ that a positive force magnitude tends to push the points apart, this is the
84
+ meaning of "expansile" in this context. The following diagram shows the
85
+ positive force sense and the distance between the points::
86
+
87
+ P Q
88
+ o<--- F --->o
89
+ | |
90
+ |<--l(t)--->|
91
+
92
+ Examples
93
+ ========
94
+
95
+ To construct an actuator, an expression (or symbol) must be supplied to
96
+ represent the force it can produce, alongside a pathway specifying its line
97
+ of action. Let's also create a global reference frame and spatially fix one
98
+ of the points in it while setting the other to be positioned such that it
99
+ can freely move in the frame's x direction specified by the coordinate
100
+ ``q``.
101
+
102
+ >>> from sympy import symbols
103
+ >>> from sympy.physics.mechanics import (ForceActuator, LinearPathway,
104
+ ... Point, ReferenceFrame)
105
+ >>> from sympy.physics.vector import dynamicsymbols
106
+ >>> N = ReferenceFrame('N')
107
+ >>> q = dynamicsymbols('q')
108
+ >>> force = symbols('F')
109
+ >>> pA, pB = Point('pA'), Point('pB')
110
+ >>> pA.set_vel(N, 0)
111
+ >>> pB.set_pos(pA, q*N.x)
112
+ >>> pB.pos_from(pA)
113
+ q(t)*N.x
114
+ >>> linear_pathway = LinearPathway(pA, pB)
115
+ >>> actuator = ForceActuator(force, linear_pathway)
116
+ >>> actuator
117
+ ForceActuator(F, LinearPathway(pA, pB))
118
+
119
+ Parameters
120
+ ==========
121
+
122
+ force : Expr
123
+ The scalar expression defining the (expansile) force that the actuator
124
+ produces.
125
+ pathway : PathwayBase
126
+ The pathway that the actuator follows. This must be an instance of a
127
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
128
+
129
+ """
130
+
131
+ def __init__(self, force, pathway):
132
+ """Initializer for ``ForceActuator``.
133
+
134
+ Parameters
135
+ ==========
136
+
137
+ force : Expr
138
+ The scalar expression defining the (expansile) force that the
139
+ actuator produces.
140
+ pathway : PathwayBase
141
+ The pathway that the actuator follows. This must be an instance of
142
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
143
+
144
+ """
145
+ self.force = force
146
+ self.pathway = pathway
147
+
148
+ @property
149
+ def force(self):
150
+ """The magnitude of the force produced by the actuator."""
151
+ return self._force
152
+
153
+ @force.setter
154
+ def force(self, force):
155
+ if hasattr(self, '_force'):
156
+ msg = (
157
+ f'Can\'t set attribute `force` to {repr(force)} as it is '
158
+ f'immutable.'
159
+ )
160
+ raise AttributeError(msg)
161
+ self._force = sympify(force, strict=True)
162
+
163
+ @property
164
+ def pathway(self):
165
+ """The ``Pathway`` defining the actuator's line of action."""
166
+ return self._pathway
167
+
168
+ @pathway.setter
169
+ def pathway(self, pathway):
170
+ if hasattr(self, '_pathway'):
171
+ msg = (
172
+ f'Can\'t set attribute `pathway` to {repr(pathway)} as it is '
173
+ f'immutable.'
174
+ )
175
+ raise AttributeError(msg)
176
+ if not isinstance(pathway, PathwayBase):
177
+ msg = (
178
+ f'Value {repr(pathway)} passed to `pathway` was of type '
179
+ f'{type(pathway)}, must be {PathwayBase}.'
180
+ )
181
+ raise TypeError(msg)
182
+ self._pathway = pathway
183
+
184
+ def to_loads(self):
185
+ """Loads required by the equations of motion method classes.
186
+
187
+ Explanation
188
+ ===========
189
+
190
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
191
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
192
+ when constructing the equations of motion. This method acts as a
193
+ utility to produce the correctly-structred pairs of points and vectors
194
+ required so that these can be easily concatenated with other items in
195
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
196
+ loads are also in the correct form to also be passed to the other
197
+ equations of motion method classes, e.g. ``LagrangesMethod``.
198
+
199
+ Examples
200
+ ========
201
+
202
+ The below example shows how to generate the loads produced by a force
203
+ actuator that follows a linear pathway. In this example we'll assume
204
+ that the force actuator is being used to model a simple linear spring.
205
+ First, create a linear pathway between two points separated by the
206
+ coordinate ``q`` in the ``x`` direction of the global frame ``N``.
207
+
208
+ >>> from sympy.physics.mechanics import (LinearPathway, Point,
209
+ ... ReferenceFrame)
210
+ >>> from sympy.physics.vector import dynamicsymbols
211
+ >>> q = dynamicsymbols('q')
212
+ >>> N = ReferenceFrame('N')
213
+ >>> pA, pB = Point('pA'), Point('pB')
214
+ >>> pB.set_pos(pA, q*N.x)
215
+ >>> pathway = LinearPathway(pA, pB)
216
+
217
+ Now create a symbol ``k`` to describe the spring's stiffness and
218
+ instantiate a force actuator that produces a (contractile) force
219
+ proportional to both the spring's stiffness and the pathway's length.
220
+ Note that actuator classes use the sign convention that expansile
221
+ forces are positive, so for a spring to produce a contractile force the
222
+ spring force needs to be calculated as the negative for the stiffness
223
+ multiplied by the length.
224
+
225
+ >>> from sympy import symbols
226
+ >>> from sympy.physics.mechanics import ForceActuator
227
+ >>> stiffness = symbols('k')
228
+ >>> spring_force = -stiffness*pathway.length
229
+ >>> spring = ForceActuator(spring_force, pathway)
230
+
231
+ The forces produced by the spring can be generated in the list of loads
232
+ form that ``KanesMethod`` (and other equations of motion methods)
233
+ requires by calling the ``to_loads`` method.
234
+
235
+ >>> spring.to_loads()
236
+ [(pA, k*q(t)*N.x), (pB, - k*q(t)*N.x)]
237
+
238
+ A simple linear damper can be modeled in a similar way. Create another
239
+ symbol ``c`` to describe the dampers damping coefficient. This time
240
+ instantiate a force actuator that produces a force proportional to both
241
+ the damper's damping coefficient and the pathway's extension velocity.
242
+ Note that the damping force is negative as it acts in the opposite
243
+ direction to which the damper is changing in length.
244
+
245
+ >>> damping_coefficient = symbols('c')
246
+ >>> damping_force = -damping_coefficient*pathway.extension_velocity
247
+ >>> damper = ForceActuator(damping_force, pathway)
248
+
249
+ Again, the forces produces by the damper can be generated by calling
250
+ the ``to_loads`` method.
251
+
252
+ >>> damper.to_loads()
253
+ [(pA, c*Derivative(q(t), t)*N.x), (pB, - c*Derivative(q(t), t)*N.x)]
254
+
255
+ """
256
+ return self.pathway.to_loads(self.force)
257
+
258
+ def __repr__(self):
259
+ """Representation of a ``ForceActuator``."""
260
+ return f'{self.__class__.__name__}({self.force}, {self.pathway})'
261
+
262
+
263
+ class LinearSpring(ForceActuator):
264
+ """A spring with its spring force as a linear function of its length.
265
+
266
+ Explanation
267
+ ===========
268
+
269
+ Note that the "linear" in the name ``LinearSpring`` refers to the fact that
270
+ the spring force is a linear function of the springs length. I.e. for a
271
+ linear spring with stiffness ``k``, distance between its ends of ``x``, and
272
+ an equilibrium length of ``0``, the spring force will be ``-k*x``, which is
273
+ a linear function in ``x``. To create a spring that follows a linear, or
274
+ straight, pathway between its two ends, a ``LinearPathway`` instance needs
275
+ to be passed to the ``pathway`` parameter.
276
+
277
+ A ``LinearSpring`` is a subclass of ``ForceActuator`` and so follows the
278
+ same sign conventions for length, extension velocity, and the direction of
279
+ the forces it applies to its points of attachment on bodies. The sign
280
+ convention for the direction of forces is such that, for the case where a
281
+ linear spring is instantiated with a ``LinearPathway`` instance as its
282
+ pathway, they act to push the two ends of the spring away from one another.
283
+ Because springs produces a contractile force and acts to pull the two ends
284
+ together towards the equilibrium length when stretched, the scalar portion
285
+ of the forces on the endpoint are negative in order to flip the sign of the
286
+ forces on the endpoints when converted into vector quantities. The
287
+ following diagram shows the positive force sense and the distance between
288
+ the points::
289
+
290
+ P Q
291
+ o<--- F --->o
292
+ | |
293
+ |<--l(t)--->|
294
+
295
+ Examples
296
+ ========
297
+
298
+ To construct a linear spring, an expression (or symbol) must be supplied to
299
+ represent the stiffness (spring constant) of the spring, alongside a
300
+ pathway specifying its line of action. Let's also create a global reference
301
+ frame and spatially fix one of the points in it while setting the other to
302
+ be positioned such that it can freely move in the frame's x direction
303
+ specified by the coordinate ``q``.
304
+
305
+ >>> from sympy import symbols
306
+ >>> from sympy.physics.mechanics import (LinearPathway, LinearSpring,
307
+ ... Point, ReferenceFrame)
308
+ >>> from sympy.physics.vector import dynamicsymbols
309
+ >>> N = ReferenceFrame('N')
310
+ >>> q = dynamicsymbols('q')
311
+ >>> stiffness = symbols('k')
312
+ >>> pA, pB = Point('pA'), Point('pB')
313
+ >>> pA.set_vel(N, 0)
314
+ >>> pB.set_pos(pA, q*N.x)
315
+ >>> pB.pos_from(pA)
316
+ q(t)*N.x
317
+ >>> linear_pathway = LinearPathway(pA, pB)
318
+ >>> spring = LinearSpring(stiffness, linear_pathway)
319
+ >>> spring
320
+ LinearSpring(k, LinearPathway(pA, pB))
321
+
322
+ This spring will produce a force that is proportional to both its stiffness
323
+ and the pathway's length. Note that this force is negative as SymPy's sign
324
+ convention for actuators is that negative forces are contractile.
325
+
326
+ >>> spring.force
327
+ -k*sqrt(q(t)**2)
328
+
329
+ To create a linear spring with a non-zero equilibrium length, an expression
330
+ (or symbol) can be passed to the ``equilibrium_length`` parameter on
331
+ construction on a ``LinearSpring`` instance. Let's create a symbol ``l``
332
+ to denote a non-zero equilibrium length and create another linear spring.
333
+
334
+ >>> l = symbols('l')
335
+ >>> spring = LinearSpring(stiffness, linear_pathway, equilibrium_length=l)
336
+ >>> spring
337
+ LinearSpring(k, LinearPathway(pA, pB), equilibrium_length=l)
338
+
339
+ The spring force of this new spring is again proportional to both its
340
+ stiffness and the pathway's length. However, the spring will not produce
341
+ any force when ``q(t)`` equals ``l``. Note that the force will become
342
+ expansile when ``q(t)`` is less than ``l``, as expected.
343
+
344
+ >>> spring.force
345
+ -k*(-l + sqrt(q(t)**2))
346
+
347
+ Parameters
348
+ ==========
349
+
350
+ stiffness : Expr
351
+ The spring constant.
352
+ pathway : PathwayBase
353
+ The pathway that the actuator follows. This must be an instance of a
354
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
355
+ equilibrium_length : Expr, optional
356
+ The length at which the spring is in equilibrium, i.e. it produces no
357
+ force. The default value is 0, i.e. the spring force is a linear
358
+ function of the pathway's length with no constant offset.
359
+
360
+ See Also
361
+ ========
362
+
363
+ ForceActuator: force-producing actuator (superclass of ``LinearSpring``).
364
+ LinearPathway: straight-line pathway between a pair of points.
365
+
366
+ """
367
+
368
+ def __init__(self, stiffness, pathway, equilibrium_length=S.Zero):
369
+ """Initializer for ``LinearSpring``.
370
+
371
+ Parameters
372
+ ==========
373
+
374
+ stiffness : Expr
375
+ The spring constant.
376
+ pathway : PathwayBase
377
+ The pathway that the actuator follows. This must be an instance of
378
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
379
+ equilibrium_length : Expr, optional
380
+ The length at which the spring is in equilibrium, i.e. it produces
381
+ no force. The default value is 0, i.e. the spring force is a linear
382
+ function of the pathway's length with no constant offset.
383
+
384
+ """
385
+ self.stiffness = stiffness
386
+ self.pathway = pathway
387
+ self.equilibrium_length = equilibrium_length
388
+
389
+ @property
390
+ def force(self):
391
+ """The spring force produced by the linear spring."""
392
+ return -self.stiffness*(self.pathway.length - self.equilibrium_length)
393
+
394
+ @force.setter
395
+ def force(self, force):
396
+ raise AttributeError('Can\'t set computed attribute `force`.')
397
+
398
+ @property
399
+ def stiffness(self):
400
+ """The spring constant for the linear spring."""
401
+ return self._stiffness
402
+
403
+ @stiffness.setter
404
+ def stiffness(self, stiffness):
405
+ if hasattr(self, '_stiffness'):
406
+ msg = (
407
+ f'Can\'t set attribute `stiffness` to {repr(stiffness)} as it '
408
+ f'is immutable.'
409
+ )
410
+ raise AttributeError(msg)
411
+ self._stiffness = sympify(stiffness, strict=True)
412
+
413
+ @property
414
+ def equilibrium_length(self):
415
+ """The length of the spring at which it produces no force."""
416
+ return self._equilibrium_length
417
+
418
+ @equilibrium_length.setter
419
+ def equilibrium_length(self, equilibrium_length):
420
+ if hasattr(self, '_equilibrium_length'):
421
+ msg = (
422
+ f'Can\'t set attribute `equilibrium_length` to '
423
+ f'{repr(equilibrium_length)} as it is immutable.'
424
+ )
425
+ raise AttributeError(msg)
426
+ self._equilibrium_length = sympify(equilibrium_length, strict=True)
427
+
428
+ def __repr__(self):
429
+ """Representation of a ``LinearSpring``."""
430
+ string = f'{self.__class__.__name__}({self.stiffness}, {self.pathway}'
431
+ if self.equilibrium_length == S.Zero:
432
+ string += ')'
433
+ else:
434
+ string += f', equilibrium_length={self.equilibrium_length})'
435
+ return string
436
+
437
+
438
+ class LinearDamper(ForceActuator):
439
+ """A damper whose force is a linear function of its extension velocity.
440
+
441
+ Explanation
442
+ ===========
443
+
444
+ Note that the "linear" in the name ``LinearDamper`` refers to the fact that
445
+ the damping force is a linear function of the damper's rate of change in
446
+ its length. I.e. for a linear damper with damping ``c`` and extension
447
+ velocity ``v``, the damping force will be ``-c*v``, which is a linear
448
+ function in ``v``. To create a damper that follows a linear, or straight,
449
+ pathway between its two ends, a ``LinearPathway`` instance needs to be
450
+ passed to the ``pathway`` parameter.
451
+
452
+ A ``LinearDamper`` is a subclass of ``ForceActuator`` and so follows the
453
+ same sign conventions for length, extension velocity, and the direction of
454
+ the forces it applies to its points of attachment on bodies. The sign
455
+ convention for the direction of forces is such that, for the case where a
456
+ linear damper is instantiated with a ``LinearPathway`` instance as its
457
+ pathway, they act to push the two ends of the damper away from one another.
458
+ Because dampers produce a force that opposes the direction of change in
459
+ length, when extension velocity is positive the scalar portions of the
460
+ forces applied at the two endpoints are negative in order to flip the sign
461
+ of the forces on the endpoints wen converted into vector quantities. When
462
+ extension velocity is negative (i.e. when the damper is shortening), the
463
+ scalar portions of the fofces applied are also negative so that the signs
464
+ cancel producing forces on the endpoints that are in the same direction as
465
+ the positive sign convention for the forces at the endpoints of the pathway
466
+ (i.e. they act to push the endpoints away from one another). The following
467
+ diagram shows the positive force sense and the distance between the
468
+ points::
469
+
470
+ P Q
471
+ o<--- F --->o
472
+ | |
473
+ |<--l(t)--->|
474
+
475
+ Examples
476
+ ========
477
+
478
+ To construct a linear damper, an expression (or symbol) must be supplied to
479
+ represent the damping coefficient of the damper (we'll use the symbol
480
+ ``c``), alongside a pathway specifying its line of action. Let's also
481
+ create a global reference frame and spatially fix one of the points in it
482
+ while setting the other to be positioned such that it can freely move in
483
+ the frame's x direction specified by the coordinate ``q``. The velocity
484
+ that the two points move away from one another can be specified by the
485
+ coordinate ``u`` where ``u`` is the first time derivative of ``q``
486
+ (i.e., ``u = Derivative(q(t), t)``).
487
+
488
+ >>> from sympy import symbols
489
+ >>> from sympy.physics.mechanics import (LinearDamper, LinearPathway,
490
+ ... Point, ReferenceFrame)
491
+ >>> from sympy.physics.vector import dynamicsymbols
492
+ >>> N = ReferenceFrame('N')
493
+ >>> q = dynamicsymbols('q')
494
+ >>> damping = symbols('c')
495
+ >>> pA, pB = Point('pA'), Point('pB')
496
+ >>> pA.set_vel(N, 0)
497
+ >>> pB.set_pos(pA, q*N.x)
498
+ >>> pB.pos_from(pA)
499
+ q(t)*N.x
500
+ >>> pB.vel(N)
501
+ Derivative(q(t), t)*N.x
502
+ >>> linear_pathway = LinearPathway(pA, pB)
503
+ >>> damper = LinearDamper(damping, linear_pathway)
504
+ >>> damper
505
+ LinearDamper(c, LinearPathway(pA, pB))
506
+
507
+ This damper will produce a force that is proportional to both its damping
508
+ coefficient and the pathway's extension length. Note that this force is
509
+ negative as SymPy's sign convention for actuators is that negative forces
510
+ are contractile and the damping force of the damper will oppose the
511
+ direction of length change.
512
+
513
+ >>> damper.force
514
+ -c*sqrt(q(t)**2)*Derivative(q(t), t)/q(t)
515
+
516
+ Parameters
517
+ ==========
518
+
519
+ damping : Expr
520
+ The damping constant.
521
+ pathway : PathwayBase
522
+ The pathway that the actuator follows. This must be an instance of a
523
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
524
+
525
+ See Also
526
+ ========
527
+
528
+ ForceActuator: force-producing actuator (superclass of ``LinearDamper``).
529
+ LinearPathway: straight-line pathway between a pair of points.
530
+
531
+ """
532
+
533
+ def __init__(self, damping, pathway):
534
+ """Initializer for ``LinearDamper``.
535
+
536
+ Parameters
537
+ ==========
538
+
539
+ damping : Expr
540
+ The damping constant.
541
+ pathway : PathwayBase
542
+ The pathway that the actuator follows. This must be an instance of
543
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
544
+
545
+ """
546
+ self.damping = damping
547
+ self.pathway = pathway
548
+
549
+ @property
550
+ def force(self):
551
+ """The damping force produced by the linear damper."""
552
+ return -self.damping*self.pathway.extension_velocity
553
+
554
+ @force.setter
555
+ def force(self, force):
556
+ raise AttributeError('Can\'t set computed attribute `force`.')
557
+
558
+ @property
559
+ def damping(self):
560
+ """The damping constant for the linear damper."""
561
+ return self._damping
562
+
563
+ @damping.setter
564
+ def damping(self, damping):
565
+ if hasattr(self, '_damping'):
566
+ msg = (
567
+ f'Can\'t set attribute `damping` to {repr(damping)} as it is '
568
+ f'immutable.'
569
+ )
570
+ raise AttributeError(msg)
571
+ self._damping = sympify(damping, strict=True)
572
+
573
+ def __repr__(self):
574
+ """Representation of a ``LinearDamper``."""
575
+ return f'{self.__class__.__name__}({self.damping}, {self.pathway})'
576
+
577
+
578
+ class TorqueActuator(ActuatorBase):
579
+ """Torque-producing actuator.
580
+
581
+ Explanation
582
+ ===========
583
+
584
+ A ``TorqueActuator`` is an actuator that produces a pair of equal and
585
+ opposite torques on a pair of bodies.
586
+
587
+ Examples
588
+ ========
589
+
590
+ To construct a torque actuator, an expression (or symbol) must be supplied
591
+ to represent the torque it can produce, alongside a vector specifying the
592
+ axis about which the torque will act, and a pair of frames on which the
593
+ torque will act.
594
+
595
+ >>> from sympy import symbols
596
+ >>> from sympy.physics.mechanics import (ReferenceFrame, RigidBody,
597
+ ... TorqueActuator)
598
+ >>> N = ReferenceFrame('N')
599
+ >>> A = ReferenceFrame('A')
600
+ >>> torque = symbols('T')
601
+ >>> axis = N.z
602
+ >>> parent = RigidBody('parent', frame=N)
603
+ >>> child = RigidBody('child', frame=A)
604
+ >>> bodies = (child, parent)
605
+ >>> actuator = TorqueActuator(torque, axis, *bodies)
606
+ >>> actuator
607
+ TorqueActuator(T, axis=N.z, target_frame=A, reaction_frame=N)
608
+
609
+ Note that because torques actually act on frames, not bodies,
610
+ ``TorqueActuator`` will extract the frame associated with a ``RigidBody``
611
+ when one is passed instead of a ``ReferenceFrame``.
612
+
613
+ Parameters
614
+ ==========
615
+
616
+ torque : Expr
617
+ The scalar expression defining the torque that the actuator produces.
618
+ axis : Vector
619
+ The axis about which the actuator applies torques.
620
+ target_frame : ReferenceFrame | RigidBody
621
+ The primary frame on which the actuator will apply the torque.
622
+ reaction_frame : ReferenceFrame | RigidBody | None
623
+ The secondary frame on which the actuator will apply the torque. Note
624
+ that the (equal and opposite) reaction torque is applied to this frame.
625
+
626
+ """
627
+
628
+ def __init__(self, torque, axis, target_frame, reaction_frame=None):
629
+ """Initializer for ``TorqueActuator``.
630
+
631
+ Parameters
632
+ ==========
633
+
634
+ torque : Expr
635
+ The scalar expression defining the torque that the actuator
636
+ produces.
637
+ axis : Vector
638
+ The axis about which the actuator applies torques.
639
+ target_frame : ReferenceFrame | RigidBody
640
+ The primary frame on which the actuator will apply the torque.
641
+ reaction_frame : ReferenceFrame | RigidBody | None
642
+ The secondary frame on which the actuator will apply the torque.
643
+ Note that the (equal and opposite) reaction torque is applied to
644
+ this frame.
645
+
646
+ """
647
+ self.torque = torque
648
+ self.axis = axis
649
+ self.target_frame = target_frame
650
+ self.reaction_frame = reaction_frame
651
+
652
+ @classmethod
653
+ def at_pin_joint(cls, torque, pin_joint):
654
+ """Alternate constructor to instantiate from a ``PinJoint`` instance.
655
+
656
+ Examples
657
+ ========
658
+
659
+ To create a pin joint the ``PinJoint`` class requires a name, parent
660
+ body, and child body to be passed to its constructor. It is also
661
+ possible to control the joint axis using the ``joint_axis`` keyword
662
+ argument. In this example let's use the parent body's reference frame's
663
+ z-axis as the joint axis.
664
+
665
+ >>> from sympy.physics.mechanics import (PinJoint, ReferenceFrame,
666
+ ... RigidBody, TorqueActuator)
667
+ >>> N = ReferenceFrame('N')
668
+ >>> A = ReferenceFrame('A')
669
+ >>> parent = RigidBody('parent', frame=N)
670
+ >>> child = RigidBody('child', frame=A)
671
+ >>> pin_joint = PinJoint(
672
+ ... 'pin',
673
+ ... parent,
674
+ ... child,
675
+ ... joint_axis=N.z,
676
+ ... )
677
+
678
+ Let's also create a symbol ``T`` that will represent the torque applied
679
+ by the torque actuator.
680
+
681
+ >>> from sympy import symbols
682
+ >>> torque = symbols('T')
683
+
684
+ To create the torque actuator from the ``torque`` and ``pin_joint``
685
+ variables previously instantiated, these can be passed to the alternate
686
+ constructor class method ``at_pin_joint`` of the ``TorqueActuator``
687
+ class. It should be noted that a positive torque will cause a positive
688
+ displacement of the joint coordinate or that the torque is applied on
689
+ the child body with a reaction torque on the parent.
690
+
691
+ >>> actuator = TorqueActuator.at_pin_joint(torque, pin_joint)
692
+ >>> actuator
693
+ TorqueActuator(T, axis=N.z, target_frame=A, reaction_frame=N)
694
+
695
+ Parameters
696
+ ==========
697
+
698
+ torque : Expr
699
+ The scalar expression defining the torque that the actuator
700
+ produces.
701
+ pin_joint : PinJoint
702
+ The pin joint, and by association the parent and child bodies, on
703
+ which the torque actuator will act. The pair of bodies acted upon
704
+ by the torque actuator are the parent and child bodies of the pin
705
+ joint, with the child acting as the reaction body. The pin joint's
706
+ axis is used as the axis about which the torque actuator will apply
707
+ its torque.
708
+
709
+ """
710
+ if not isinstance(pin_joint, PinJoint):
711
+ msg = (
712
+ f'Value {repr(pin_joint)} passed to `pin_joint` was of type '
713
+ f'{type(pin_joint)}, must be {PinJoint}.'
714
+ )
715
+ raise TypeError(msg)
716
+ return cls(
717
+ torque,
718
+ pin_joint.joint_axis,
719
+ pin_joint.child_interframe,
720
+ pin_joint.parent_interframe,
721
+ )
722
+
723
+ @property
724
+ def torque(self):
725
+ """The magnitude of the torque produced by the actuator."""
726
+ return self._torque
727
+
728
+ @torque.setter
729
+ def torque(self, torque):
730
+ if hasattr(self, '_torque'):
731
+ msg = (
732
+ f'Can\'t set attribute `torque` to {repr(torque)} as it is '
733
+ f'immutable.'
734
+ )
735
+ raise AttributeError(msg)
736
+ self._torque = sympify(torque, strict=True)
737
+
738
+ @property
739
+ def axis(self):
740
+ """The axis about which the torque acts."""
741
+ return self._axis
742
+
743
+ @axis.setter
744
+ def axis(self, axis):
745
+ if hasattr(self, '_axis'):
746
+ msg = (
747
+ f'Can\'t set attribute `axis` to {repr(axis)} as it is '
748
+ f'immutable.'
749
+ )
750
+ raise AttributeError(msg)
751
+ if not isinstance(axis, Vector):
752
+ msg = (
753
+ f'Value {repr(axis)} passed to `axis` was of type '
754
+ f'{type(axis)}, must be {Vector}.'
755
+ )
756
+ raise TypeError(msg)
757
+ self._axis = axis
758
+
759
+ @property
760
+ def target_frame(self):
761
+ """The primary reference frames on which the torque will act."""
762
+ return self._target_frame
763
+
764
+ @target_frame.setter
765
+ def target_frame(self, target_frame):
766
+ if hasattr(self, '_target_frame'):
767
+ msg = (
768
+ f'Can\'t set attribute `target_frame` to {repr(target_frame)} '
769
+ f'as it is immutable.'
770
+ )
771
+ raise AttributeError(msg)
772
+ if isinstance(target_frame, RigidBody):
773
+ target_frame = target_frame.frame
774
+ elif not isinstance(target_frame, ReferenceFrame):
775
+ msg = (
776
+ f'Value {repr(target_frame)} passed to `target_frame` was of '
777
+ f'type {type(target_frame)}, must be {ReferenceFrame}.'
778
+ )
779
+ raise TypeError(msg)
780
+ self._target_frame = target_frame
781
+
782
+ @property
783
+ def reaction_frame(self):
784
+ """The primary reference frames on which the torque will act."""
785
+ return self._reaction_frame
786
+
787
+ @reaction_frame.setter
788
+ def reaction_frame(self, reaction_frame):
789
+ if hasattr(self, '_reaction_frame'):
790
+ msg = (
791
+ f'Can\'t set attribute `reaction_frame` to '
792
+ f'{repr(reaction_frame)} as it is immutable.'
793
+ )
794
+ raise AttributeError(msg)
795
+ if isinstance(reaction_frame, RigidBody):
796
+ reaction_frame = reaction_frame.frame
797
+ elif (
798
+ not isinstance(reaction_frame, ReferenceFrame)
799
+ and reaction_frame is not None
800
+ ):
801
+ msg = (
802
+ f'Value {repr(reaction_frame)} passed to `reaction_frame` was '
803
+ f'of type {type(reaction_frame)}, must be {ReferenceFrame}.'
804
+ )
805
+ raise TypeError(msg)
806
+ self._reaction_frame = reaction_frame
807
+
808
+ def to_loads(self):
809
+ """Loads required by the equations of motion method classes.
810
+
811
+ Explanation
812
+ ===========
813
+
814
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
815
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
816
+ when constructing the equations of motion. This method acts as a
817
+ utility to produce the correctly-structred pairs of points and vectors
818
+ required so that these can be easily concatenated with other items in
819
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
820
+ loads are also in the correct form to also be passed to the other
821
+ equations of motion method classes, e.g. ``LagrangesMethod``.
822
+
823
+ Examples
824
+ ========
825
+
826
+ The below example shows how to generate the loads produced by a torque
827
+ actuator that acts on a pair of bodies attached by a pin joint.
828
+
829
+ >>> from sympy import symbols
830
+ >>> from sympy.physics.mechanics import (PinJoint, ReferenceFrame,
831
+ ... RigidBody, TorqueActuator)
832
+ >>> torque = symbols('T')
833
+ >>> N = ReferenceFrame('N')
834
+ >>> A = ReferenceFrame('A')
835
+ >>> parent = RigidBody('parent', frame=N)
836
+ >>> child = RigidBody('child', frame=A)
837
+ >>> pin_joint = PinJoint(
838
+ ... 'pin',
839
+ ... parent,
840
+ ... child,
841
+ ... joint_axis=N.z,
842
+ ... )
843
+ >>> actuator = TorqueActuator.at_pin_joint(torque, pin_joint)
844
+
845
+ The forces produces by the damper can be generated by calling the
846
+ ``to_loads`` method.
847
+
848
+ >>> actuator.to_loads()
849
+ [(A, T*N.z), (N, - T*N.z)]
850
+
851
+ Alternatively, if a torque actuator is created without a reaction frame
852
+ then the loads returned by the ``to_loads`` method will contain just
853
+ the single load acting on the target frame.
854
+
855
+ >>> actuator = TorqueActuator(torque, N.z, N)
856
+ >>> actuator.to_loads()
857
+ [(N, T*N.z)]
858
+
859
+ """
860
+ loads = [
861
+ Torque(self.target_frame, self.torque*self.axis),
862
+ ]
863
+ if self.reaction_frame is not None:
864
+ loads.append(Torque(self.reaction_frame, -self.torque*self.axis))
865
+ return loads
866
+
867
+ def __repr__(self):
868
+ """Representation of a ``TorqueActuator``."""
869
+ string = (
870
+ f'{self.__class__.__name__}({self.torque}, axis={self.axis}, '
871
+ f'target_frame={self.target_frame}'
872
+ )
873
+ if self.reaction_frame is not None:
874
+ string += f', reaction_frame={self.reaction_frame})'
875
+ else:
876
+ string += ')'
877
+ return string
878
+
879
+
880
+ class DuffingSpring(ForceActuator):
881
+ """A nonlinear spring based on the Duffing equation.
882
+
883
+ Explanation
884
+ ===========
885
+
886
+ Here, ``DuffingSpring`` represents the force exerted by a nonlinear spring based on the Duffing equation:
887
+ F = -beta*x-alpha*x**3, where x is the displacement from the equilibrium position, beta is the linear spring constant,
888
+ and alpha is the coefficient for the nonlinear cubic term.
889
+
890
+ Parameters
891
+ ==========
892
+
893
+ linear_stiffness : Expr
894
+ The linear stiffness coefficient (beta).
895
+ nonlinear_stiffness : Expr
896
+ The nonlinear stiffness coefficient (alpha).
897
+ pathway : PathwayBase
898
+ The pathway that the actuator follows.
899
+ equilibrium_length : Expr, optional
900
+ The length at which the spring is in equilibrium (x).
901
+ """
902
+
903
+ def __init__(self, linear_stiffness, nonlinear_stiffness, pathway, equilibrium_length=S.Zero):
904
+ self.linear_stiffness = sympify(linear_stiffness, strict=True)
905
+ self.nonlinear_stiffness = sympify(nonlinear_stiffness, strict=True)
906
+ self.equilibrium_length = sympify(equilibrium_length, strict=True)
907
+
908
+ if not isinstance(pathway, PathwayBase):
909
+ raise TypeError("pathway must be an instance of PathwayBase.")
910
+ self._pathway = pathway
911
+
912
+ @property
913
+ def linear_stiffness(self):
914
+ return self._linear_stiffness
915
+
916
+ @linear_stiffness.setter
917
+ def linear_stiffness(self, linear_stiffness):
918
+ if hasattr(self, '_linear_stiffness'):
919
+ msg = (
920
+ f'Can\'t set attribute `linear_stiffness` to '
921
+ f'{repr(linear_stiffness)} as it is immutable.'
922
+ )
923
+ raise AttributeError(msg)
924
+ self._linear_stiffness = sympify(linear_stiffness, strict=True)
925
+
926
+ @property
927
+ def nonlinear_stiffness(self):
928
+ return self._nonlinear_stiffness
929
+
930
+ @nonlinear_stiffness.setter
931
+ def nonlinear_stiffness(self, nonlinear_stiffness):
932
+ if hasattr(self, '_nonlinear_stiffness'):
933
+ msg = (
934
+ f'Can\'t set attribute `nonlinear_stiffness` to '
935
+ f'{repr(nonlinear_stiffness)} as it is immutable.'
936
+ )
937
+ raise AttributeError(msg)
938
+ self._nonlinear_stiffness = sympify(nonlinear_stiffness, strict=True)
939
+
940
+ @property
941
+ def pathway(self):
942
+ return self._pathway
943
+
944
+ @pathway.setter
945
+ def pathway(self, pathway):
946
+ if hasattr(self, '_pathway'):
947
+ msg = (
948
+ f'Can\'t set attribute `pathway` to {repr(pathway)} as it is '
949
+ f'immutable.'
950
+ )
951
+ raise AttributeError(msg)
952
+ if not isinstance(pathway, PathwayBase):
953
+ msg = (
954
+ f'Value {repr(pathway)} passed to `pathway` was of type '
955
+ f'{type(pathway)}, must be {PathwayBase}.'
956
+ )
957
+ raise TypeError(msg)
958
+ self._pathway = pathway
959
+
960
+ @property
961
+ def equilibrium_length(self):
962
+ return self._equilibrium_length
963
+
964
+ @equilibrium_length.setter
965
+ def equilibrium_length(self, equilibrium_length):
966
+ if hasattr(self, '_equilibrium_length'):
967
+ msg = (
968
+ f'Can\'t set attribute `equilibrium_length` to '
969
+ f'{repr(equilibrium_length)} as it is immutable.'
970
+ )
971
+ raise AttributeError(msg)
972
+ self._equilibrium_length = sympify(equilibrium_length, strict=True)
973
+
974
+ @property
975
+ def force(self):
976
+ """The force produced by the Duffing spring."""
977
+ displacement = self.pathway.length - self.equilibrium_length
978
+ return -self.linear_stiffness * displacement - self.nonlinear_stiffness * displacement**3
979
+
980
+ @force.setter
981
+ def force(self, force):
982
+ if hasattr(self, '_force'):
983
+ msg = (
984
+ f'Can\'t set attribute `force` to {repr(force)} as it is '
985
+ f'immutable.'
986
+ )
987
+ raise AttributeError(msg)
988
+ self._force = sympify(force, strict=True)
989
+
990
+ def __repr__(self):
991
+ return (f"{self.__class__.__name__}("
992
+ f"{self.linear_stiffness}, {self.nonlinear_stiffness}, {self.pathway}, "
993
+ f"equilibrium_length={self.equilibrium_length})")
994
+
995
+ class CoulombKineticFriction(ForceActuator):
996
+ r"""Coulomb kinetic friction with Stribeck and viscous effects.
997
+
998
+ Explanation
999
+ ===========
1000
+
1001
+ This represents a Coulomb kinetic friction with the Stribeck and viscous effect,
1002
+ described by the function:
1003
+
1004
+ .. math::
1005
+ F = (\mu_k f_n + (\mu_s - \mu_k) f_n e^{-(\frac{v}{v_s})^2}) \text{sign}(v) + \sigma v
1006
+
1007
+ where :math:`\mu_k` is the coefficient of kinetic friction, :math:`\mu_s` is the
1008
+ coefficient of static friction, :math:`f_n` is the normal force, :math:`v` is the
1009
+ relative velocity, :math:`v_s` is the Stribeck friction coefficient, and
1010
+ :math:`\sigma` is the viscous friction constant.
1011
+
1012
+ The default friction force is :math:`F = \mu_k f_n`.
1013
+ When specified, the actuator includes:
1014
+
1015
+ - Stribeck effect: :math:`(\mu_s - \mu_k) f_n e^{-(\frac{v}{v_s})^2}`
1016
+ - Viscous effect: :math:`\sigma v`
1017
+
1018
+ Notes
1019
+ =====
1020
+
1021
+ The actuator makes the following assumptions:
1022
+
1023
+ - The actuator assumes relative motion is non-zero.
1024
+ - The normal force is assumed to be a non-negative scalar.
1025
+ - The resultant friction force is opposite to the velocity direction.
1026
+ - Each point in the pathway is fixed within separate objects that are sliding relative to each other. In other words, these two points are fixed in the mutually sliding objects.
1027
+
1028
+ This actuator has been tested for straightforward motions, like a block sliding
1029
+ on a surface.
1030
+
1031
+ The friction force is defined to always oppose the direction of relative velocity :math:`v`.
1032
+ Specifically:
1033
+
1034
+ - The default Coulomb friction force :math:`\mu_k f_n \text{sign}(v)` is opposite to :math:`v`.
1035
+ - The Stribeck effect :math:`(\mu_s - \mu_k) f_n e^{-(\frac{v}{v_s})^2} \text{sign}(v)` is also opposite to :math:`v`.
1036
+ - The viscous friction term :math:`\sigma v` is opposite to :math:`v`.
1037
+
1038
+ Examples
1039
+ ========
1040
+
1041
+ The below example shows how to generate the loads produced by a Coulomb kinetic
1042
+ friction actuator in a mass-spring system with friction.
1043
+
1044
+ >>> import sympy as sm
1045
+ >>> from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
1046
+ ... LinearPathway, CoulombKineticFriction, LinearSpring, KanesMethod, Particle)
1047
+
1048
+ >>> x, v = dynamicsymbols('x, v', real=True)
1049
+ >>> m, g, k, mu_k, mu_s, v_s, sigma = sm.symbols('m, g, k, mu_k, mu_s, v_s, sigma')
1050
+
1051
+ >>> N = ReferenceFrame('N')
1052
+ >>> O, P = Point('O'), Point('P')
1053
+ >>> O.set_vel(N, 0)
1054
+ >>> P.set_pos(O, x*N.x)
1055
+
1056
+ >>> pathway = LinearPathway(O, P)
1057
+ >>> friction = CoulombKineticFriction(mu_k, m*g, pathway, v_s=v_s, sigma=sigma, mu_s=mu_k)
1058
+ >>> spring = LinearSpring(k, pathway)
1059
+ >>> block = Particle('block', point=P, mass=m)
1060
+
1061
+ >>> kane = KanesMethod(N, (x,), (v,), kd_eqs=(x.diff() - v,))
1062
+ >>> friction.to_loads()
1063
+ [(O, (g*m*mu_k*sign(sign(x(t))*Derivative(x(t), t)) + sigma*sign(x(t))*Derivative(x(t), t))*x(t)/Abs(x(t))*N.x), (P, (-g*m*mu_k*sign(sign(x(t))*Derivative(x(t), t)) - sigma*sign(x(t))*Derivative(x(t), t))*x(t)/Abs(x(t))*N.x)]
1064
+ >>> loads = friction.to_loads() + spring.to_loads()
1065
+ >>> fr, frstar = kane.kanes_equations([block], loads)
1066
+ >>> eom = fr + frstar
1067
+ >>> eom
1068
+ Matrix([[-k*x(t) - m*Derivative(v(t), t) + (-g*m*mu_k*sign(v(t)*sign(x(t))) - sigma*v(t)*sign(x(t)))*x(t)/Abs(x(t))]])
1069
+
1070
+ Parameters
1071
+ ==========
1072
+
1073
+ f_n : sympifiable
1074
+ The normal force between the surfaces. It should always be a non-negative scalar.
1075
+ mu_k : sympifiable
1076
+ The coefficient of kinetic friction.
1077
+ pathway : PathwayBase
1078
+ The pathway that the actuator follows.
1079
+ v_s : sympifiable, optional
1080
+ The Stribeck friction coefficient.
1081
+ sigma : sympifiable, optional
1082
+ The viscous friction coefficient.
1083
+ mu_s : sympifiable, optional
1084
+ The coefficient of static friction. Defaults to mu_k, meaning the Stribeck effect evaluates to 0 by default.
1085
+
1086
+ References
1087
+ ==========
1088
+
1089
+ .. [Moore2022] https://moorepants.github.io/learn-multibody-dynamics/loads.html#friction.
1090
+ .. [Flores2023] Paulo Flores, Jorge Ambrosio, Hamid M. Lankarani,
1091
+ "Contact-impact events with friction in multibody dynamics: Back to basics",
1092
+ Mechanism and Machine Theory, vol. 184, 2023. https://doi.org/10.1016/j.mechmachtheory.2023.105305.
1093
+ .. [Rogner2017] I. Rogner, "Friction modelling for robotic applications with planar motion",
1094
+ Chalmers University of Technology, Department of Electrical Engineering, 2017.
1095
+
1096
+ """
1097
+
1098
+ def __init__(self, mu_k, f_n, pathway, *, v_s=None, sigma=None, mu_s=None):
1099
+ self._mu_k = sympify(mu_k, strict=True) if mu_k is not None else 1
1100
+ self._mu_s = sympify(mu_s, strict=True) if mu_s is not None else self._mu_k
1101
+ self._f_n = sympify(f_n, strict=True)
1102
+ self._sigma = sympify(sigma, strict=True) if sigma is not None else 0
1103
+ self._v_s = sympify(v_s, strict=True) if v_s is not None or v_s == 0 else 0.01
1104
+ self.pathway = pathway
1105
+
1106
+ @property
1107
+ def mu_k(self):
1108
+ """The coefficient of kinetic friction."""
1109
+ return self._mu_k
1110
+
1111
+ @property
1112
+ def mu_s(self):
1113
+ """The coefficient of static friction."""
1114
+ return self._mu_s
1115
+
1116
+ @property
1117
+ def f_n(self):
1118
+ """The normal force between the surfaces."""
1119
+ return self._f_n
1120
+
1121
+ @property
1122
+ def sigma(self):
1123
+ """The viscous friction coefficient."""
1124
+ return self._sigma
1125
+
1126
+ @property
1127
+ def v_s(self):
1128
+ """The Stribeck friction coefficient."""
1129
+ return self._v_s
1130
+
1131
+ @property
1132
+ def force(self):
1133
+ v = self.pathway.extension_velocity
1134
+ f_c = self.mu_k * self.f_n
1135
+ f_max = self.mu_s * self.f_n
1136
+ stribeck_term = (f_max - f_c) * exp(-(v / self.v_s)**2) if self.v_s is not None else 0
1137
+ viscous_term = self.sigma * v if self.sigma is not None else 0
1138
+ return (f_c + stribeck_term) * -sign(v) - viscous_term
1139
+
1140
+ @force.setter
1141
+ def force(self, force):
1142
+ raise AttributeError('Can\'t set computed attribute `force`.')
1143
+
1144
+ def __repr__(self):
1145
+ return (f'{self.__class__.__name__}({self._mu_k}, {self._mu_s} '
1146
+ f'{self._f_n}, {self.pathway}, {self._v_s}, '
1147
+ f'{self._sigma})')
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/body.py ADDED
@@ -0,0 +1,710 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import Symbol
2
+ from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic
3
+ from sympy.physics.mechanics import RigidBody, Particle, Inertia
4
+ from sympy.physics.mechanics.body_base import BodyBase
5
+ from sympy.utilities.exceptions import sympy_deprecation_warning
6
+
7
+ __all__ = ['Body']
8
+
9
+
10
+ # XXX: We use type:ignore because the classes RigidBody and Particle have
11
+ # inconsistent parallel axis methods that take different numbers of arguments.
12
+ class Body(RigidBody, Particle): # type: ignore
13
+ """
14
+ Body is a common representation of either a RigidBody or a Particle SymPy
15
+ object depending on what is passed in during initialization. If a mass is
16
+ passed in and central_inertia is left as None, the Particle object is
17
+ created. Otherwise a RigidBody object will be created.
18
+
19
+ .. deprecated:: 1.13
20
+ The Body class is deprecated. Its functionality is captured by
21
+ :class:`~.RigidBody` and :class:`~.Particle`.
22
+
23
+ Explanation
24
+ ===========
25
+
26
+ The attributes that Body possesses will be the same as a Particle instance
27
+ or a Rigid Body instance depending on which was created. Additional
28
+ attributes are listed below.
29
+
30
+ Attributes
31
+ ==========
32
+
33
+ name : string
34
+ The body's name
35
+ masscenter : Point
36
+ The point which represents the center of mass of the rigid body
37
+ frame : ReferenceFrame
38
+ The reference frame which the body is fixed in
39
+ mass : Sympifyable
40
+ The body's mass
41
+ inertia : (Dyadic, Point)
42
+ The body's inertia around its center of mass. This attribute is specific
43
+ to the rigid body form of Body and is left undefined for the Particle
44
+ form
45
+ loads : iterable
46
+ This list contains information on the different loads acting on the
47
+ Body. Forces are listed as a (point, vector) tuple and torques are
48
+ listed as (reference frame, vector) tuples.
49
+
50
+ Parameters
51
+ ==========
52
+
53
+ name : String
54
+ Defines the name of the body. It is used as the base for defining
55
+ body specific properties.
56
+ masscenter : Point, optional
57
+ A point that represents the center of mass of the body or particle.
58
+ If no point is given, a point is generated.
59
+ mass : Sympifyable, optional
60
+ A Sympifyable object which represents the mass of the body. If no
61
+ mass is passed, one is generated.
62
+ frame : ReferenceFrame, optional
63
+ The ReferenceFrame that represents the reference frame of the body.
64
+ If no frame is given, a frame is generated.
65
+ central_inertia : Dyadic, optional
66
+ Central inertia dyadic of the body. If none is passed while creating
67
+ RigidBody, a default inertia is generated.
68
+
69
+ Examples
70
+ ========
71
+
72
+ As Body has been deprecated, the following examples are for illustrative
73
+ purposes only. The functionality of Body is fully captured by
74
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
75
+ warning we can use the ignore_warnings context manager.
76
+
77
+ >>> from sympy.utilities.exceptions import ignore_warnings
78
+
79
+ Default behaviour. This results in the creation of a RigidBody object for
80
+ which the mass, mass center, frame and inertia attributes are given default
81
+ values. ::
82
+
83
+ >>> from sympy.physics.mechanics import Body
84
+ >>> with ignore_warnings(DeprecationWarning):
85
+ ... body = Body('name_of_body')
86
+
87
+ This next example demonstrates the code required to specify all of the
88
+ values of the Body object. Note this will also create a RigidBody version of
89
+ the Body object. ::
90
+
91
+ >>> from sympy import Symbol
92
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia
93
+ >>> from sympy.physics.mechanics import Body
94
+ >>> mass = Symbol('mass')
95
+ >>> masscenter = Point('masscenter')
96
+ >>> frame = ReferenceFrame('frame')
97
+ >>> ixx = Symbol('ixx')
98
+ >>> body_inertia = inertia(frame, ixx, 0, 0)
99
+ >>> with ignore_warnings(DeprecationWarning):
100
+ ... body = Body('name_of_body', masscenter, mass, frame, body_inertia)
101
+
102
+ The minimal code required to create a Particle version of the Body object
103
+ involves simply passing in a name and a mass. ::
104
+
105
+ >>> from sympy import Symbol
106
+ >>> from sympy.physics.mechanics import Body
107
+ >>> mass = Symbol('mass')
108
+ >>> with ignore_warnings(DeprecationWarning):
109
+ ... body = Body('name_of_body', mass=mass)
110
+
111
+ The Particle version of the Body object can also receive a masscenter point
112
+ and a reference frame, just not an inertia.
113
+ """
114
+
115
+ def __init__(self, name, masscenter=None, mass=None, frame=None,
116
+ central_inertia=None):
117
+ sympy_deprecation_warning(
118
+ """
119
+ Support for the Body class has been removed, as its functionality is
120
+ fully captured by RigidBody and Particle.
121
+ """,
122
+ deprecated_since_version="1.13",
123
+ active_deprecations_target="deprecated-mechanics-body-class"
124
+ )
125
+
126
+ self._loads = []
127
+
128
+ if frame is None:
129
+ frame = ReferenceFrame(name + '_frame')
130
+
131
+ if masscenter is None:
132
+ masscenter = Point(name + '_masscenter')
133
+
134
+ if central_inertia is None and mass is None:
135
+ ixx = Symbol(name + '_ixx')
136
+ iyy = Symbol(name + '_iyy')
137
+ izz = Symbol(name + '_izz')
138
+ izx = Symbol(name + '_izx')
139
+ ixy = Symbol(name + '_ixy')
140
+ iyz = Symbol(name + '_iyz')
141
+ _inertia = Inertia.from_inertia_scalars(masscenter, frame, ixx, iyy,
142
+ izz, ixy, iyz, izx)
143
+ else:
144
+ _inertia = (central_inertia, masscenter)
145
+
146
+ if mass is None:
147
+ _mass = Symbol(name + '_mass')
148
+ else:
149
+ _mass = mass
150
+
151
+ masscenter.set_vel(frame, 0)
152
+
153
+ # If user passes masscenter and mass then a particle is created
154
+ # otherwise a rigidbody. As a result a body may or may not have inertia.
155
+ # Note: BodyBase.__init__ is used to prevent problems with super() calls in
156
+ # Particle and RigidBody arising due to multiple inheritance.
157
+ if central_inertia is None and mass is not None:
158
+ BodyBase.__init__(self, name, masscenter, _mass)
159
+ self.frame = frame
160
+ self._central_inertia = Dyadic(0)
161
+ else:
162
+ BodyBase.__init__(self, name, masscenter, _mass)
163
+ self.frame = frame
164
+ self.inertia = _inertia
165
+
166
+ def __repr__(self):
167
+ if self.is_rigidbody:
168
+ return RigidBody.__repr__(self)
169
+ return Particle.__repr__(self)
170
+
171
+ @property
172
+ def loads(self):
173
+ return self._loads
174
+
175
+ @property
176
+ def x(self):
177
+ """The basis Vector for the Body, in the x direction."""
178
+ return self.frame.x
179
+
180
+ @property
181
+ def y(self):
182
+ """The basis Vector for the Body, in the y direction."""
183
+ return self.frame.y
184
+
185
+ @property
186
+ def z(self):
187
+ """The basis Vector for the Body, in the z direction."""
188
+ return self.frame.z
189
+
190
+ @property
191
+ def inertia(self):
192
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
193
+ if self.is_rigidbody:
194
+ return RigidBody.inertia.fget(self)
195
+ return (self.central_inertia, self.masscenter)
196
+
197
+ @inertia.setter
198
+ def inertia(self, I):
199
+ RigidBody.inertia.fset(self, I)
200
+
201
+ @property
202
+ def is_rigidbody(self):
203
+ if hasattr(self, '_inertia'):
204
+ return True
205
+ return False
206
+
207
+ def kinetic_energy(self, frame):
208
+ """Kinetic energy of the body.
209
+
210
+ Parameters
211
+ ==========
212
+
213
+ frame : ReferenceFrame or Body
214
+ The Body's angular velocity and the velocity of it's mass
215
+ center are typically defined with respect to an inertial frame but
216
+ any relevant frame in which the velocities are known can be supplied.
217
+
218
+ Examples
219
+ ========
220
+
221
+ As Body has been deprecated, the following examples are for illustrative
222
+ purposes only. The functionality of Body is fully captured by
223
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
224
+ warning we can use the ignore_warnings context manager.
225
+
226
+ >>> from sympy.utilities.exceptions import ignore_warnings
227
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point
228
+ >>> from sympy import symbols
229
+ >>> m, v, r, omega = symbols('m v r omega')
230
+ >>> N = ReferenceFrame('N')
231
+ >>> O = Point('O')
232
+ >>> with ignore_warnings(DeprecationWarning):
233
+ ... P = Body('P', masscenter=O, mass=m)
234
+ >>> P.masscenter.set_vel(N, v * N.y)
235
+ >>> P.kinetic_energy(N)
236
+ m*v**2/2
237
+
238
+ >>> N = ReferenceFrame('N')
239
+ >>> b = ReferenceFrame('b')
240
+ >>> b.set_ang_vel(N, omega * b.x)
241
+ >>> P = Point('P')
242
+ >>> P.set_vel(N, v * N.x)
243
+ >>> with ignore_warnings(DeprecationWarning):
244
+ ... B = Body('B', masscenter=P, frame=b)
245
+ >>> B.kinetic_energy(N)
246
+ B_ixx*omega**2/2 + B_mass*v**2/2
247
+
248
+ See Also
249
+ ========
250
+
251
+ sympy.physics.mechanics : Particle, RigidBody
252
+
253
+ """
254
+ if isinstance(frame, Body):
255
+ frame = Body.frame
256
+ if self.is_rigidbody:
257
+ return RigidBody(self.name, self.masscenter, self.frame, self.mass,
258
+ (self.central_inertia, self.masscenter)).kinetic_energy(frame)
259
+ return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame)
260
+
261
+ def apply_force(self, force, point=None, reaction_body=None, reaction_point=None):
262
+ """Add force to the body(s).
263
+
264
+ Explanation
265
+ ===========
266
+
267
+ Applies the force on self or equal and opposite forces on
268
+ self and other body if both are given on the desired point on the bodies.
269
+ The force applied on other body is taken opposite of self, i.e, -force.
270
+
271
+ Parameters
272
+ ==========
273
+
274
+ force: Vector
275
+ The force to be applied.
276
+ point: Point, optional
277
+ The point on self on which force is applied.
278
+ By default self's masscenter.
279
+ reaction_body: Body, optional
280
+ Second body on which equal and opposite force
281
+ is to be applied.
282
+ reaction_point : Point, optional
283
+ The point on other body on which equal and opposite
284
+ force is applied. By default masscenter of other body.
285
+
286
+ Example
287
+ =======
288
+
289
+ As Body has been deprecated, the following examples are for illustrative
290
+ purposes only. The functionality of Body is fully captured by
291
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
292
+ warning we can use the ignore_warnings context manager.
293
+
294
+ >>> from sympy.utilities.exceptions import ignore_warnings
295
+ >>> from sympy import symbols
296
+ >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols
297
+ >>> m, g = symbols('m g')
298
+ >>> with ignore_warnings(DeprecationWarning):
299
+ ... B = Body('B')
300
+ >>> force1 = m*g*B.z
301
+ >>> B.apply_force(force1) #Applying force on B's masscenter
302
+ >>> B.loads
303
+ [(B_masscenter, g*m*B_frame.z)]
304
+
305
+ We can also remove some part of force from any point on the body by
306
+ adding the opposite force to the body on that point.
307
+
308
+ >>> f1, f2 = dynamicsymbols('f1 f2')
309
+ >>> P = Point('P') #Considering point P on body B
310
+ >>> B.apply_force(f1*B.x + f2*B.y, P)
311
+ >>> B.loads
312
+ [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)]
313
+
314
+ Let's remove f1 from point P on body B.
315
+
316
+ >>> B.apply_force(-f1*B.x, P)
317
+ >>> B.loads
318
+ [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)]
319
+
320
+ To further demonstrate the use of ``apply_force`` attribute,
321
+ consider two bodies connected through a spring.
322
+
323
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
324
+ >>> with ignore_warnings(DeprecationWarning):
325
+ ... N = Body('N') #Newtonion Frame
326
+ >>> x = dynamicsymbols('x')
327
+ >>> with ignore_warnings(DeprecationWarning):
328
+ ... B1 = Body('B1')
329
+ ... B2 = Body('B2')
330
+ >>> spring_force = x*N.x
331
+
332
+ Now let's apply equal and opposite spring force to the bodies.
333
+
334
+ >>> P1 = Point('P1')
335
+ >>> P2 = Point('P2')
336
+ >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2)
337
+
338
+ We can check the loads(forces) applied to bodies now.
339
+
340
+ >>> B1.loads
341
+ [(P1, x(t)*N_frame.x)]
342
+ >>> B2.loads
343
+ [(P2, - x(t)*N_frame.x)]
344
+
345
+ Notes
346
+ =====
347
+
348
+ If a new force is applied to a body on a point which already has some
349
+ force applied on it, then the new force is added to the already applied
350
+ force on that point.
351
+
352
+ """
353
+
354
+ if not isinstance(point, Point):
355
+ if point is None:
356
+ point = self.masscenter # masscenter
357
+ else:
358
+ raise TypeError("Force must be applied to a point on the body.")
359
+ if not isinstance(force, Vector):
360
+ raise TypeError("Force must be a vector.")
361
+
362
+ if reaction_body is not None:
363
+ reaction_body.apply_force(-force, point=reaction_point)
364
+
365
+ for load in self._loads:
366
+ if point in load:
367
+ force += load[1]
368
+ self._loads.remove(load)
369
+ break
370
+
371
+ self._loads.append((point, force))
372
+
373
+ def apply_torque(self, torque, reaction_body=None):
374
+ """Add torque to the body(s).
375
+
376
+ Explanation
377
+ ===========
378
+
379
+ Applies the torque on self or equal and opposite torques on
380
+ self and other body if both are given.
381
+ The torque applied on other body is taken opposite of self,
382
+ i.e, -torque.
383
+
384
+ Parameters
385
+ ==========
386
+
387
+ torque: Vector
388
+ The torque to be applied.
389
+ reaction_body: Body, optional
390
+ Second body on which equal and opposite torque
391
+ is to be applied.
392
+
393
+ Example
394
+ =======
395
+
396
+ As Body has been deprecated, the following examples are for illustrative
397
+ purposes only. The functionality of Body is fully captured by
398
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
399
+ warning we can use the ignore_warnings context manager.
400
+
401
+ >>> from sympy.utilities.exceptions import ignore_warnings
402
+ >>> from sympy import symbols
403
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
404
+ >>> t = symbols('t')
405
+ >>> with ignore_warnings(DeprecationWarning):
406
+ ... B = Body('B')
407
+ >>> torque1 = t*B.z
408
+ >>> B.apply_torque(torque1)
409
+ >>> B.loads
410
+ [(B_frame, t*B_frame.z)]
411
+
412
+ We can also remove some part of torque from the body by
413
+ adding the opposite torque to the body.
414
+
415
+ >>> t1, t2 = dynamicsymbols('t1 t2')
416
+ >>> B.apply_torque(t1*B.x + t2*B.y)
417
+ >>> B.loads
418
+ [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)]
419
+
420
+ Let's remove t1 from Body B.
421
+
422
+ >>> B.apply_torque(-t1*B.x)
423
+ >>> B.loads
424
+ [(B_frame, t2(t)*B_frame.y + t*B_frame.z)]
425
+
426
+ To further demonstrate the use, let us consider two bodies such that
427
+ a torque `T` is acting on one body, and `-T` on the other.
428
+
429
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
430
+ >>> with ignore_warnings(DeprecationWarning):
431
+ ... N = Body('N') #Newtonion frame
432
+ ... B1 = Body('B1')
433
+ ... B2 = Body('B2')
434
+ >>> v = dynamicsymbols('v')
435
+ >>> T = v*N.y #Torque
436
+
437
+ Now let's apply equal and opposite torque to the bodies.
438
+
439
+ >>> B1.apply_torque(T, B2)
440
+
441
+ We can check the loads (torques) applied to bodies now.
442
+
443
+ >>> B1.loads
444
+ [(B1_frame, v(t)*N_frame.y)]
445
+ >>> B2.loads
446
+ [(B2_frame, - v(t)*N_frame.y)]
447
+
448
+ Notes
449
+ =====
450
+
451
+ If a new torque is applied on body which already has some torque applied on it,
452
+ then the new torque is added to the previous torque about the body's frame.
453
+
454
+ """
455
+
456
+ if not isinstance(torque, Vector):
457
+ raise TypeError("A Vector must be supplied to add torque.")
458
+
459
+ if reaction_body is not None:
460
+ reaction_body.apply_torque(-torque)
461
+
462
+ for load in self._loads:
463
+ if self.frame in load:
464
+ torque += load[1]
465
+ self._loads.remove(load)
466
+ break
467
+ self._loads.append((self.frame, torque))
468
+
469
+ def clear_loads(self):
470
+ """
471
+ Clears the Body's loads list.
472
+
473
+ Example
474
+ =======
475
+
476
+ As Body has been deprecated, the following examples are for illustrative
477
+ purposes only. The functionality of Body is fully captured by
478
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
479
+ warning we can use the ignore_warnings context manager.
480
+
481
+ >>> from sympy.utilities.exceptions import ignore_warnings
482
+ >>> from sympy.physics.mechanics import Body
483
+ >>> with ignore_warnings(DeprecationWarning):
484
+ ... B = Body('B')
485
+ >>> force = B.x + B.y
486
+ >>> B.apply_force(force)
487
+ >>> B.loads
488
+ [(B_masscenter, B_frame.x + B_frame.y)]
489
+ >>> B.clear_loads()
490
+ >>> B.loads
491
+ []
492
+
493
+ """
494
+
495
+ self._loads = []
496
+
497
+ def remove_load(self, about=None):
498
+ """
499
+ Remove load about a point or frame.
500
+
501
+ Parameters
502
+ ==========
503
+
504
+ about : Point or ReferenceFrame, optional
505
+ The point about which force is applied,
506
+ and is to be removed.
507
+ If about is None, then the torque about
508
+ self's frame is removed.
509
+
510
+ Example
511
+ =======
512
+
513
+ As Body has been deprecated, the following examples are for illustrative
514
+ purposes only. The functionality of Body is fully captured by
515
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
516
+ warning we can use the ignore_warnings context manager.
517
+
518
+ >>> from sympy.utilities.exceptions import ignore_warnings
519
+ >>> from sympy.physics.mechanics import Body, Point
520
+ >>> with ignore_warnings(DeprecationWarning):
521
+ ... B = Body('B')
522
+ >>> P = Point('P')
523
+ >>> f1 = B.x
524
+ >>> f2 = B.y
525
+ >>> B.apply_force(f1)
526
+ >>> B.apply_force(f2, P)
527
+ >>> B.loads
528
+ [(B_masscenter, B_frame.x), (P, B_frame.y)]
529
+
530
+ >>> B.remove_load(P)
531
+ >>> B.loads
532
+ [(B_masscenter, B_frame.x)]
533
+
534
+ """
535
+
536
+ if about is not None:
537
+ if not isinstance(about, Point):
538
+ raise TypeError('Load is applied about Point or ReferenceFrame.')
539
+ else:
540
+ about = self.frame
541
+
542
+ for load in self._loads:
543
+ if about in load:
544
+ self._loads.remove(load)
545
+ break
546
+
547
+ def masscenter_vel(self, body):
548
+ """
549
+ Returns the velocity of the mass center with respect to the provided
550
+ rigid body or reference frame.
551
+
552
+ Parameters
553
+ ==========
554
+
555
+ body: Body or ReferenceFrame
556
+ The rigid body or reference frame to calculate the velocity in.
557
+
558
+ Example
559
+ =======
560
+
561
+ As Body has been deprecated, the following examples are for illustrative
562
+ purposes only. The functionality of Body is fully captured by
563
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
564
+ warning we can use the ignore_warnings context manager.
565
+
566
+ >>> from sympy.utilities.exceptions import ignore_warnings
567
+ >>> from sympy.physics.mechanics import Body
568
+ >>> with ignore_warnings(DeprecationWarning):
569
+ ... A = Body('A')
570
+ ... B = Body('B')
571
+ >>> A.masscenter.set_vel(B.frame, 5*B.frame.x)
572
+ >>> A.masscenter_vel(B)
573
+ 5*B_frame.x
574
+ >>> A.masscenter_vel(B.frame)
575
+ 5*B_frame.x
576
+
577
+ """
578
+
579
+ if isinstance(body, ReferenceFrame):
580
+ frame=body
581
+ elif isinstance(body, Body):
582
+ frame = body.frame
583
+ return self.masscenter.vel(frame)
584
+
585
+ def ang_vel_in(self, body):
586
+ """
587
+ Returns this body's angular velocity with respect to the provided
588
+ rigid body or reference frame.
589
+
590
+ Parameters
591
+ ==========
592
+
593
+ body: Body or ReferenceFrame
594
+ The rigid body or reference frame to calculate the angular velocity in.
595
+
596
+ Example
597
+ =======
598
+
599
+ As Body has been deprecated, the following examples are for illustrative
600
+ purposes only. The functionality of Body is fully captured by
601
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
602
+ warning we can use the ignore_warnings context manager.
603
+
604
+ >>> from sympy.utilities.exceptions import ignore_warnings
605
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame
606
+ >>> with ignore_warnings(DeprecationWarning):
607
+ ... A = Body('A')
608
+ >>> N = ReferenceFrame('N')
609
+ >>> with ignore_warnings(DeprecationWarning):
610
+ ... B = Body('B', frame=N)
611
+ >>> A.frame.set_ang_vel(N, 5*N.x)
612
+ >>> A.ang_vel_in(B)
613
+ 5*N.x
614
+ >>> A.ang_vel_in(N)
615
+ 5*N.x
616
+
617
+ """
618
+
619
+ if isinstance(body, ReferenceFrame):
620
+ frame=body
621
+ elif isinstance(body, Body):
622
+ frame = body.frame
623
+ return self.frame.ang_vel_in(frame)
624
+
625
+ def dcm(self, body):
626
+ """
627
+ Returns the direction cosine matrix of this body relative to the
628
+ provided rigid body or reference frame.
629
+
630
+ Parameters
631
+ ==========
632
+
633
+ body: Body or ReferenceFrame
634
+ The rigid body or reference frame to calculate the dcm.
635
+
636
+ Example
637
+ =======
638
+
639
+ As Body has been deprecated, the following examples are for illustrative
640
+ purposes only. The functionality of Body is fully captured by
641
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
642
+ warning we can use the ignore_warnings context manager.
643
+
644
+ >>> from sympy.utilities.exceptions import ignore_warnings
645
+ >>> from sympy.physics.mechanics import Body
646
+ >>> with ignore_warnings(DeprecationWarning):
647
+ ... A = Body('A')
648
+ ... B = Body('B')
649
+ >>> A.frame.orient_axis(B.frame, B.frame.x, 5)
650
+ >>> A.dcm(B)
651
+ Matrix([
652
+ [1, 0, 0],
653
+ [0, cos(5), sin(5)],
654
+ [0, -sin(5), cos(5)]])
655
+ >>> A.dcm(B.frame)
656
+ Matrix([
657
+ [1, 0, 0],
658
+ [0, cos(5), sin(5)],
659
+ [0, -sin(5), cos(5)]])
660
+
661
+ """
662
+
663
+ if isinstance(body, ReferenceFrame):
664
+ frame=body
665
+ elif isinstance(body, Body):
666
+ frame = body.frame
667
+ return self.frame.dcm(frame)
668
+
669
+ def parallel_axis(self, point, frame=None):
670
+ """Returns the inertia dyadic of the body with respect to another
671
+ point.
672
+
673
+ Parameters
674
+ ==========
675
+
676
+ point : sympy.physics.vector.Point
677
+ The point to express the inertia dyadic about.
678
+ frame : sympy.physics.vector.ReferenceFrame
679
+ The reference frame used to construct the dyadic.
680
+
681
+ Returns
682
+ =======
683
+
684
+ inertia : sympy.physics.vector.Dyadic
685
+ The inertia dyadic of the rigid body expressed about the provided
686
+ point.
687
+
688
+ Example
689
+ =======
690
+
691
+ As Body has been deprecated, the following examples are for illustrative
692
+ purposes only. The functionality of Body is fully captured by
693
+ :class:`~.RigidBody` and :class:`~.Particle`. To ignore the deprecation
694
+ warning we can use the ignore_warnings context manager.
695
+
696
+ >>> from sympy.utilities.exceptions import ignore_warnings
697
+ >>> from sympy.physics.mechanics import Body
698
+ >>> with ignore_warnings(DeprecationWarning):
699
+ ... A = Body('A')
700
+ >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y)
701
+ >>> A.parallel_axis(P).to_matrix(A.frame)
702
+ Matrix([
703
+ [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx],
704
+ [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz],
705
+ [ A_izx, A_iyz, A_izz + 34*A_mass]])
706
+
707
+ """
708
+ if self.is_rigidbody:
709
+ return RigidBody.parallel_axis(self, point, frame)
710
+ return Particle.parallel_axis(self, point, frame)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/body_base.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from sympy import Symbol, sympify
3
+ from sympy.physics.vector import Point
4
+
5
+ __all__ = ['BodyBase']
6
+
7
+
8
+ class BodyBase(ABC):
9
+ """Abstract class for body type objects."""
10
+ def __init__(self, name, masscenter=None, mass=None):
11
+ # Note: If frame=None, no auto-generated frame is created, because a
12
+ # Particle does not need to have a frame by default.
13
+ if not isinstance(name, str):
14
+ raise TypeError('Supply a valid name.')
15
+ self._name = name
16
+ if mass is None:
17
+ mass = Symbol(f'{name}_mass')
18
+ if masscenter is None:
19
+ masscenter = Point(f'{name}_masscenter')
20
+ self.mass = mass
21
+ self.masscenter = masscenter
22
+ self.potential_energy = 0
23
+ self.points = []
24
+
25
+ def __str__(self):
26
+ return self.name
27
+
28
+ def __repr__(self):
29
+ return (f'{self.__class__.__name__}({repr(self.name)}, masscenter='
30
+ f'{repr(self.masscenter)}, mass={repr(self.mass)})')
31
+
32
+ @property
33
+ def name(self):
34
+ """The name of the body."""
35
+ return self._name
36
+
37
+ @property
38
+ def masscenter(self):
39
+ """The body's center of mass."""
40
+ return self._masscenter
41
+
42
+ @masscenter.setter
43
+ def masscenter(self, point):
44
+ if not isinstance(point, Point):
45
+ raise TypeError("The body's center of mass must be a Point object.")
46
+ self._masscenter = point
47
+
48
+ @property
49
+ def mass(self):
50
+ """The body's mass."""
51
+ return self._mass
52
+
53
+ @mass.setter
54
+ def mass(self, mass):
55
+ self._mass = sympify(mass)
56
+
57
+ @property
58
+ def potential_energy(self):
59
+ """The potential energy of the body.
60
+
61
+ Examples
62
+ ========
63
+
64
+ >>> from sympy.physics.mechanics import Particle, Point
65
+ >>> from sympy import symbols
66
+ >>> m, g, h = symbols('m g h')
67
+ >>> O = Point('O')
68
+ >>> P = Particle('P', O, m)
69
+ >>> P.potential_energy = m * g * h
70
+ >>> P.potential_energy
71
+ g*h*m
72
+
73
+ """
74
+ return self._potential_energy
75
+
76
+ @potential_energy.setter
77
+ def potential_energy(self, scalar):
78
+ self._potential_energy = sympify(scalar)
79
+
80
+ @abstractmethod
81
+ def kinetic_energy(self, frame):
82
+ pass
83
+
84
+ @abstractmethod
85
+ def linear_momentum(self, frame):
86
+ pass
87
+
88
+ @abstractmethod
89
+ def angular_momentum(self, point, frame):
90
+ pass
91
+
92
+ @abstractmethod
93
+ def parallel_axis(self, point, frame):
94
+ pass
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities import dict_merge
2
+ from sympy.utilities.iterables import iterable
3
+ from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame,
4
+ Point, dynamicsymbols)
5
+ from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex,
6
+ init_vprinting)
7
+ from sympy.physics.mechanics.particle import Particle
8
+ from sympy.physics.mechanics.rigidbody import RigidBody
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy import Matrix, Mul, Derivative, sin, cos, tan, S
11
+ from sympy.core.function import AppliedUndef
12
+ from sympy.physics.mechanics.inertia import (inertia as _inertia,
13
+ inertia_of_point_mass as _inertia_of_point_mass)
14
+ from sympy.utilities.exceptions import sympy_deprecation_warning
15
+
16
+ __all__ = ['linear_momentum',
17
+ 'angular_momentum',
18
+ 'kinetic_energy',
19
+ 'potential_energy',
20
+ 'Lagrangian',
21
+ 'mechanics_printing',
22
+ 'mprint',
23
+ 'msprint',
24
+ 'mpprint',
25
+ 'mlatex',
26
+ 'msubs',
27
+ 'find_dynamicsymbols']
28
+
29
+ # These are functions that we've moved and renamed during extracting the
30
+ # basic vector calculus code from the mechanics packages.
31
+
32
+ mprint = vprint
33
+ msprint = vsprint
34
+ mpprint = vpprint
35
+ mlatex = vlatex
36
+
37
+
38
+ def mechanics_printing(**kwargs):
39
+ """
40
+ Initializes time derivative printing for all SymPy objects in
41
+ mechanics module.
42
+ """
43
+
44
+ init_vprinting(**kwargs)
45
+
46
+ mechanics_printing.__doc__ = init_vprinting.__doc__
47
+
48
+
49
+ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
50
+ sympy_deprecation_warning(
51
+ """
52
+ The inertia function has been moved.
53
+ Import it from "sympy.physics.mechanics".
54
+ """,
55
+ deprecated_since_version="1.13",
56
+ active_deprecations_target="moved-mechanics-functions"
57
+ )
58
+ return _inertia(frame, ixx, iyy, izz, ixy, iyz, izx)
59
+
60
+
61
+ def inertia_of_point_mass(mass, pos_vec, frame):
62
+ sympy_deprecation_warning(
63
+ """
64
+ The inertia_of_point_mass function has been moved.
65
+ Import it from "sympy.physics.mechanics".
66
+ """,
67
+ deprecated_since_version="1.13",
68
+ active_deprecations_target="moved-mechanics-functions"
69
+ )
70
+ return _inertia_of_point_mass(mass, pos_vec, frame)
71
+
72
+
73
+ def linear_momentum(frame, *body):
74
+ """Linear momentum of the system.
75
+
76
+ Explanation
77
+ ===========
78
+
79
+ This function returns the linear momentum of a system of Particle's and/or
80
+ RigidBody's. The linear momentum of a system is equal to the vector sum of
81
+ the linear momentum of its constituents. Consider a system, S, comprised of
82
+ a rigid body, A, and a particle, P. The linear momentum of the system, L,
83
+ is equal to the vector sum of the linear momentum of the particle, L1, and
84
+ the linear momentum of the rigid body, L2, i.e.
85
+
86
+ L = L1 + L2
87
+
88
+ Parameters
89
+ ==========
90
+
91
+ frame : ReferenceFrame
92
+ The frame in which linear momentum is desired.
93
+ body1, body2, body3... : Particle and/or RigidBody
94
+ The body (or bodies) whose linear momentum is required.
95
+
96
+ Examples
97
+ ========
98
+
99
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
100
+ >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
101
+ >>> N = ReferenceFrame('N')
102
+ >>> P = Point('P')
103
+ >>> P.set_vel(N, 10 * N.x)
104
+ >>> Pa = Particle('Pa', P, 1)
105
+ >>> Ac = Point('Ac')
106
+ >>> Ac.set_vel(N, 25 * N.y)
107
+ >>> I = outer(N.x, N.x)
108
+ >>> A = RigidBody('A', Ac, N, 20, (I, Ac))
109
+ >>> linear_momentum(N, A, Pa)
110
+ 10*N.x + 500*N.y
111
+
112
+ """
113
+
114
+ if not isinstance(frame, ReferenceFrame):
115
+ raise TypeError('Please specify a valid ReferenceFrame')
116
+ else:
117
+ linear_momentum_sys = Vector(0)
118
+ for e in body:
119
+ if isinstance(e, (RigidBody, Particle)):
120
+ linear_momentum_sys += e.linear_momentum(frame)
121
+ else:
122
+ raise TypeError('*body must have only Particle or RigidBody')
123
+ return linear_momentum_sys
124
+
125
+
126
+ def angular_momentum(point, frame, *body):
127
+ """Angular momentum of a system.
128
+
129
+ Explanation
130
+ ===========
131
+
132
+ This function returns the angular momentum of a system of Particle's and/or
133
+ RigidBody's. The angular momentum of such a system is equal to the vector
134
+ sum of the angular momentum of its constituents. Consider a system, S,
135
+ comprised of a rigid body, A, and a particle, P. The angular momentum of
136
+ the system, H, is equal to the vector sum of the angular momentum of the
137
+ particle, H1, and the angular momentum of the rigid body, H2, i.e.
138
+
139
+ H = H1 + H2
140
+
141
+ Parameters
142
+ ==========
143
+
144
+ point : Point
145
+ The point about which angular momentum of the system is desired.
146
+ frame : ReferenceFrame
147
+ The frame in which angular momentum is desired.
148
+ body1, body2, body3... : Particle and/or RigidBody
149
+ The body (or bodies) whose angular momentum is required.
150
+
151
+ Examples
152
+ ========
153
+
154
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
155
+ >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
156
+ >>> N = ReferenceFrame('N')
157
+ >>> O = Point('O')
158
+ >>> O.set_vel(N, 0 * N.x)
159
+ >>> P = O.locatenew('P', 1 * N.x)
160
+ >>> P.set_vel(N, 10 * N.x)
161
+ >>> Pa = Particle('Pa', P, 1)
162
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
163
+ >>> Ac.set_vel(N, 5 * N.y)
164
+ >>> a = ReferenceFrame('a')
165
+ >>> a.set_ang_vel(N, 10 * N.z)
166
+ >>> I = outer(N.z, N.z)
167
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
168
+ >>> angular_momentum(O, N, Pa, A)
169
+ 10*N.z
170
+
171
+ """
172
+
173
+ if not isinstance(frame, ReferenceFrame):
174
+ raise TypeError('Please enter a valid ReferenceFrame')
175
+ if not isinstance(point, Point):
176
+ raise TypeError('Please specify a valid Point')
177
+ else:
178
+ angular_momentum_sys = Vector(0)
179
+ for e in body:
180
+ if isinstance(e, (RigidBody, Particle)):
181
+ angular_momentum_sys += e.angular_momentum(point, frame)
182
+ else:
183
+ raise TypeError('*body must have only Particle or RigidBody')
184
+ return angular_momentum_sys
185
+
186
+
187
+ def kinetic_energy(frame, *body):
188
+ """Kinetic energy of a multibody system.
189
+
190
+ Explanation
191
+ ===========
192
+
193
+ This function returns the kinetic energy of a system of Particle's and/or
194
+ RigidBody's. The kinetic energy of such a system is equal to the sum of
195
+ the kinetic energies of its constituents. Consider a system, S, comprising
196
+ a rigid body, A, and a particle, P. The kinetic energy of the system, T,
197
+ is equal to the vector sum of the kinetic energy of the particle, T1, and
198
+ the kinetic energy of the rigid body, T2, i.e.
199
+
200
+ T = T1 + T2
201
+
202
+ Kinetic energy is a scalar.
203
+
204
+ Parameters
205
+ ==========
206
+
207
+ frame : ReferenceFrame
208
+ The frame in which the velocity or angular velocity of the body is
209
+ defined.
210
+ body1, body2, body3... : Particle and/or RigidBody
211
+ The body (or bodies) whose kinetic energy is required.
212
+
213
+ Examples
214
+ ========
215
+
216
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
217
+ >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
218
+ >>> N = ReferenceFrame('N')
219
+ >>> O = Point('O')
220
+ >>> O.set_vel(N, 0 * N.x)
221
+ >>> P = O.locatenew('P', 1 * N.x)
222
+ >>> P.set_vel(N, 10 * N.x)
223
+ >>> Pa = Particle('Pa', P, 1)
224
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
225
+ >>> Ac.set_vel(N, 5 * N.y)
226
+ >>> a = ReferenceFrame('a')
227
+ >>> a.set_ang_vel(N, 10 * N.z)
228
+ >>> I = outer(N.z, N.z)
229
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
230
+ >>> kinetic_energy(N, Pa, A)
231
+ 350
232
+
233
+ """
234
+
235
+ if not isinstance(frame, ReferenceFrame):
236
+ raise TypeError('Please enter a valid ReferenceFrame')
237
+ ke_sys = S.Zero
238
+ for e in body:
239
+ if isinstance(e, (RigidBody, Particle)):
240
+ ke_sys += e.kinetic_energy(frame)
241
+ else:
242
+ raise TypeError('*body must have only Particle or RigidBody')
243
+ return ke_sys
244
+
245
+
246
+ def potential_energy(*body):
247
+ """Potential energy of a multibody system.
248
+
249
+ Explanation
250
+ ===========
251
+
252
+ This function returns the potential energy of a system of Particle's and/or
253
+ RigidBody's. The potential energy of such a system is equal to the sum of
254
+ the potential energy of its constituents. Consider a system, S, comprising
255
+ a rigid body, A, and a particle, P. The potential energy of the system, V,
256
+ is equal to the vector sum of the potential energy of the particle, V1, and
257
+ the potential energy of the rigid body, V2, i.e.
258
+
259
+ V = V1 + V2
260
+
261
+ Potential energy is a scalar.
262
+
263
+ Parameters
264
+ ==========
265
+
266
+ body1, body2, body3... : Particle and/or RigidBody
267
+ The body (or bodies) whose potential energy is required.
268
+
269
+ Examples
270
+ ========
271
+
272
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
273
+ >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
274
+ >>> from sympy import symbols
275
+ >>> M, m, g, h = symbols('M m g h')
276
+ >>> N = ReferenceFrame('N')
277
+ >>> O = Point('O')
278
+ >>> O.set_vel(N, 0 * N.x)
279
+ >>> P = O.locatenew('P', 1 * N.x)
280
+ >>> Pa = Particle('Pa', P, m)
281
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
282
+ >>> a = ReferenceFrame('a')
283
+ >>> I = outer(N.z, N.z)
284
+ >>> A = RigidBody('A', Ac, a, M, (I, Ac))
285
+ >>> Pa.potential_energy = m * g * h
286
+ >>> A.potential_energy = M * g * h
287
+ >>> potential_energy(Pa, A)
288
+ M*g*h + g*h*m
289
+
290
+ """
291
+
292
+ pe_sys = S.Zero
293
+ for e in body:
294
+ if isinstance(e, (RigidBody, Particle)):
295
+ pe_sys += e.potential_energy
296
+ else:
297
+ raise TypeError('*body must have only Particle or RigidBody')
298
+ return pe_sys
299
+
300
+
301
+ def gravity(acceleration, *bodies):
302
+ from sympy.physics.mechanics.loads import gravity as _gravity
303
+ sympy_deprecation_warning(
304
+ """
305
+ The gravity function has been moved.
306
+ Import it from "sympy.physics.mechanics.loads".
307
+ """,
308
+ deprecated_since_version="1.13",
309
+ active_deprecations_target="moved-mechanics-functions"
310
+ )
311
+ return _gravity(acceleration, *bodies)
312
+
313
+
314
+ def center_of_mass(point, *bodies):
315
+ """
316
+ Returns the position vector from the given point to the center of mass
317
+ of the given bodies(particles or rigidbodies).
318
+
319
+ Example
320
+ =======
321
+
322
+ >>> from sympy import symbols, S
323
+ >>> from sympy.physics.vector import Point
324
+ >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
325
+ >>> from sympy.physics.mechanics.functions import center_of_mass
326
+ >>> a = ReferenceFrame('a')
327
+ >>> m = symbols('m', real=True)
328
+ >>> p1 = Particle('p1', Point('p1_pt'), S(1))
329
+ >>> p2 = Particle('p2', Point('p2_pt'), S(2))
330
+ >>> p3 = Particle('p3', Point('p3_pt'), S(3))
331
+ >>> p4 = Particle('p4', Point('p4_pt'), m)
332
+ >>> b_f = ReferenceFrame('b_f')
333
+ >>> b_cm = Point('b_cm')
334
+ >>> mb = symbols('mb')
335
+ >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
336
+ >>> p2.point.set_pos(p1.point, a.x)
337
+ >>> p3.point.set_pos(p1.point, a.x + a.y)
338
+ >>> p4.point.set_pos(p1.point, a.y)
339
+ >>> b.masscenter.set_pos(p1.point, a.y + a.z)
340
+ >>> point_o=Point('o')
341
+ >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
342
+ >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
343
+ >>> point_o.pos_from(p1.point)
344
+ 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
345
+
346
+ """
347
+ if not bodies:
348
+ raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
349
+
350
+ total_mass = 0
351
+ vec = Vector(0)
352
+ for i in bodies:
353
+ total_mass += i.mass
354
+
355
+ masscenter = getattr(i, 'masscenter', None)
356
+ if masscenter is None:
357
+ masscenter = i.point
358
+ vec += i.mass*masscenter.pos_from(point)
359
+
360
+ return vec/total_mass
361
+
362
+
363
+ def Lagrangian(frame, *body):
364
+ """Lagrangian of a multibody system.
365
+
366
+ Explanation
367
+ ===========
368
+
369
+ This function returns the Lagrangian of a system of Particle's and/or
370
+ RigidBody's. The Lagrangian of such a system is equal to the difference
371
+ between the kinetic energies and potential energies of its constituents. If
372
+ T and V are the kinetic and potential energies of a system then it's
373
+ Lagrangian, L, is defined as
374
+
375
+ L = T - V
376
+
377
+ The Lagrangian is a scalar.
378
+
379
+ Parameters
380
+ ==========
381
+
382
+ frame : ReferenceFrame
383
+ The frame in which the velocity or angular velocity of the body is
384
+ defined to determine the kinetic energy.
385
+
386
+ body1, body2, body3... : Particle and/or RigidBody
387
+ The body (or bodies) whose Lagrangian is required.
388
+
389
+ Examples
390
+ ========
391
+
392
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
393
+ >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
394
+ >>> from sympy import symbols
395
+ >>> M, m, g, h = symbols('M m g h')
396
+ >>> N = ReferenceFrame('N')
397
+ >>> O = Point('O')
398
+ >>> O.set_vel(N, 0 * N.x)
399
+ >>> P = O.locatenew('P', 1 * N.x)
400
+ >>> P.set_vel(N, 10 * N.x)
401
+ >>> Pa = Particle('Pa', P, 1)
402
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
403
+ >>> Ac.set_vel(N, 5 * N.y)
404
+ >>> a = ReferenceFrame('a')
405
+ >>> a.set_ang_vel(N, 10 * N.z)
406
+ >>> I = outer(N.z, N.z)
407
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
408
+ >>> Pa.potential_energy = m * g * h
409
+ >>> A.potential_energy = M * g * h
410
+ >>> Lagrangian(N, Pa, A)
411
+ -M*g*h - g*h*m + 350
412
+
413
+ """
414
+
415
+ if not isinstance(frame, ReferenceFrame):
416
+ raise TypeError('Please supply a valid ReferenceFrame')
417
+ for e in body:
418
+ if not isinstance(e, (RigidBody, Particle)):
419
+ raise TypeError('*body must have only Particle or RigidBody')
420
+ return kinetic_energy(frame, *body) - potential_energy(*body)
421
+
422
+
423
+ def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
424
+ """Find all dynamicsymbols in expression.
425
+
426
+ Explanation
427
+ ===========
428
+
429
+ If the optional ``exclude`` kwarg is used, only dynamicsymbols
430
+ not in the iterable ``exclude`` are returned.
431
+ If we intend to apply this function on a vector, the optional
432
+ ``reference_frame`` is also used to inform about the corresponding frame
433
+ with respect to which the dynamic symbols of the given vector is to be
434
+ determined.
435
+
436
+ Parameters
437
+ ==========
438
+
439
+ expression : SymPy expression
440
+
441
+ exclude : iterable of dynamicsymbols, optional
442
+
443
+ reference_frame : ReferenceFrame, optional
444
+ The frame with respect to which the dynamic symbols of the
445
+ given vector is to be determined.
446
+
447
+ Examples
448
+ ========
449
+
450
+ >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
451
+ >>> from sympy.physics.mechanics import ReferenceFrame
452
+ >>> x, y = dynamicsymbols('x, y')
453
+ >>> expr = x + x.diff()*y
454
+ >>> find_dynamicsymbols(expr)
455
+ {x(t), y(t), Derivative(x(t), t)}
456
+ >>> find_dynamicsymbols(expr, exclude=[x, y])
457
+ {Derivative(x(t), t)}
458
+ >>> a, b, c = dynamicsymbols('a, b, c')
459
+ >>> A = ReferenceFrame('A')
460
+ >>> v = a * A.x + b * A.y + c * A.z
461
+ >>> find_dynamicsymbols(v, reference_frame=A)
462
+ {a(t), b(t), c(t)}
463
+
464
+ """
465
+ t_set = {dynamicsymbols._t}
466
+ if exclude:
467
+ if iterable(exclude):
468
+ exclude_set = set(exclude)
469
+ else:
470
+ raise TypeError("exclude kwarg must be iterable")
471
+ else:
472
+ exclude_set = set()
473
+ if isinstance(expression, Vector):
474
+ if reference_frame is None:
475
+ raise ValueError("You must provide reference_frame when passing a "
476
+ "vector expression, got %s." % reference_frame)
477
+ else:
478
+ expression = expression.to_matrix(reference_frame)
479
+ return {i for i in expression.atoms(AppliedUndef, Derivative) if
480
+ i.free_symbols == t_set} - exclude_set
481
+
482
+
483
+ def msubs(expr, *sub_dicts, smart=False, **kwargs):
484
+ """A custom subs for use on expressions derived in physics.mechanics.
485
+
486
+ Traverses the expression tree once, performing the subs found in sub_dicts.
487
+ Terms inside ``Derivative`` expressions are ignored:
488
+
489
+ Examples
490
+ ========
491
+
492
+ >>> from sympy.physics.mechanics import dynamicsymbols, msubs
493
+ >>> x = dynamicsymbols('x')
494
+ >>> msubs(x.diff() + x, {x: 1})
495
+ Derivative(x(t), t) + 1
496
+
497
+ Note that sub_dicts can be a single dictionary, or several dictionaries:
498
+
499
+ >>> x, y, z = dynamicsymbols('x, y, z')
500
+ >>> sub1 = {x: 1, y: 2}
501
+ >>> sub2 = {z: 3, x.diff(): 4}
502
+ >>> msubs(x.diff() + x + y + z, sub1, sub2)
503
+ 10
504
+
505
+ If smart=True (default False), also checks for conditions that may result
506
+ in ``nan``, but if simplified would yield a valid expression. For example:
507
+
508
+ >>> from sympy import sin, tan
509
+ >>> (sin(x)/tan(x)).subs(x, 0)
510
+ nan
511
+ >>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
512
+ 1
513
+
514
+ It does this by first replacing all ``tan`` with ``sin/cos``. Then each
515
+ node is traversed. If the node is a fraction, subs is first evaluated on
516
+ the denominator. If this results in 0, simplification of the entire
517
+ fraction is attempted. Using this selective simplification, only
518
+ subexpressions that result in 1/0 are targeted, resulting in faster
519
+ performance.
520
+
521
+ """
522
+
523
+ sub_dict = dict_merge(*sub_dicts)
524
+ if smart:
525
+ func = _smart_subs
526
+ elif hasattr(expr, 'msubs'):
527
+ return expr.msubs(sub_dict)
528
+ else:
529
+ func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
530
+ if isinstance(expr, (Matrix, Vector, Dyadic)):
531
+ return expr.applyfunc(lambda x: func(x, sub_dict))
532
+ else:
533
+ return func(expr, sub_dict)
534
+
535
+
536
+ def _crawl(expr, func, *args, **kwargs):
537
+ """Crawl the expression tree, and apply func to every node."""
538
+ val = func(expr, *args, **kwargs)
539
+ if val is not None:
540
+ return val
541
+ new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
542
+ return expr.func(*new_args)
543
+
544
+
545
+ def _sub_func(expr, sub_dict):
546
+ """Perform direct matching substitution, ignoring derivatives."""
547
+ if expr in sub_dict:
548
+ return sub_dict[expr]
549
+ elif not expr.args or expr.is_Derivative:
550
+ return expr
551
+
552
+
553
+ def _tan_repl_func(expr):
554
+ """Replace tan with sin/cos."""
555
+ if isinstance(expr, tan):
556
+ return sin(*expr.args) / cos(*expr.args)
557
+ elif not expr.args or expr.is_Derivative:
558
+ return expr
559
+
560
+
561
+ def _smart_subs(expr, sub_dict):
562
+ """Performs subs, checking for conditions that may result in `nan` or
563
+ `oo`, and attempts to simplify them out.
564
+
565
+ The expression tree is traversed twice, and the following steps are
566
+ performed on each expression node:
567
+ - First traverse:
568
+ Replace all `tan` with `sin/cos`.
569
+ - Second traverse:
570
+ If node is a fraction, check if the denominator evaluates to 0.
571
+ If so, attempt to simplify it out. Then if node is in sub_dict,
572
+ sub in the corresponding value.
573
+
574
+ """
575
+ expr = _crawl(expr, _tan_repl_func)
576
+
577
+ def _recurser(expr, sub_dict):
578
+ # Decompose the expression into num, den
579
+ num, den = _fraction_decomp(expr)
580
+ if den != 1:
581
+ # If there is a non trivial denominator, we need to handle it
582
+ denom_subbed = _recurser(den, sub_dict)
583
+ if denom_subbed.evalf() == 0:
584
+ # If denom is 0 after this, attempt to simplify the bad expr
585
+ expr = simplify(expr)
586
+ else:
587
+ # Expression won't result in nan, find numerator
588
+ num_subbed = _recurser(num, sub_dict)
589
+ return num_subbed / denom_subbed
590
+ # We have to crawl the tree manually, because `expr` may have been
591
+ # modified in the simplify step. First, perform subs as normal:
592
+ val = _sub_func(expr, sub_dict)
593
+ if val is not None:
594
+ return val
595
+ new_args = (_recurser(arg, sub_dict) for arg in expr.args)
596
+ return expr.func(*new_args)
597
+ return _recurser(expr, sub_dict)
598
+
599
+
600
+ def _fraction_decomp(expr):
601
+ """Return num, den such that expr = num/den."""
602
+ if not isinstance(expr, Mul):
603
+ return expr, 1
604
+ num = []
605
+ den = []
606
+ for a in expr.args:
607
+ if a.is_Pow and a.args[1] < 0:
608
+ den.append(1 / a)
609
+ else:
610
+ num.append(a)
611
+ if not den:
612
+ return expr, 1
613
+ num = Mul(*num)
614
+ den = Mul(*den)
615
+ return num, den
616
+
617
+
618
+ def _f_list_parser(fl, ref_frame):
619
+ """Parses the provided forcelist composed of items
620
+ of the form (obj, force).
621
+ Returns a tuple containing:
622
+ vel_list: The velocity (ang_vel for Frames, vel for Points) in
623
+ the provided reference frame.
624
+ f_list: The forces.
625
+
626
+ Used internally in the KanesMethod and LagrangesMethod classes.
627
+
628
+ """
629
+ def flist_iter():
630
+ for pair in fl:
631
+ obj, force = pair
632
+ if isinstance(obj, ReferenceFrame):
633
+ yield obj.ang_vel_in(ref_frame), force
634
+ elif isinstance(obj, Point):
635
+ yield obj.vel(ref_frame), force
636
+ else:
637
+ raise TypeError('First entry in each forcelist pair must '
638
+ 'be a point or frame.')
639
+
640
+ if not fl:
641
+ vel_list, f_list = (), ()
642
+ else:
643
+ unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
644
+ vel_list, f_list = unzip(list(flist_iter()))
645
+ return vel_list, f_list
646
+
647
+
648
+ def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True,
649
+ is_dynamicsymbols=True, u_auxiliary=None):
650
+ """Validate the generalized coordinates and generalized speeds.
651
+
652
+ Parameters
653
+ ==========
654
+ coordinates : iterable, optional
655
+ Generalized coordinates to be validated.
656
+ speeds : iterable, optional
657
+ Generalized speeds to be validated.
658
+ check_duplicates : bool, optional
659
+ Checks if there are duplicates in the generalized coordinates and
660
+ generalized speeds. If so it will raise a ValueError. The default is
661
+ True.
662
+ is_dynamicsymbols : iterable, optional
663
+ Checks if all the generalized coordinates and generalized speeds are
664
+ dynamicsymbols. If any is not a dynamicsymbol, a ValueError will be
665
+ raised. The default is True.
666
+ u_auxiliary : iterable, optional
667
+ Auxiliary generalized speeds to be validated.
668
+
669
+ """
670
+ t_set = {dynamicsymbols._t}
671
+ # Convert input to iterables
672
+ if coordinates is None:
673
+ coordinates = []
674
+ elif not iterable(coordinates):
675
+ coordinates = [coordinates]
676
+ if speeds is None:
677
+ speeds = []
678
+ elif not iterable(speeds):
679
+ speeds = [speeds]
680
+ if u_auxiliary is None:
681
+ u_auxiliary = []
682
+ elif not iterable(u_auxiliary):
683
+ u_auxiliary = [u_auxiliary]
684
+
685
+ msgs = []
686
+ if check_duplicates: # Check for duplicates
687
+ seen = set()
688
+ coord_duplicates = {x for x in coordinates if x in seen or seen.add(x)}
689
+ seen = set()
690
+ speed_duplicates = {x for x in speeds if x in seen or seen.add(x)}
691
+ seen = set()
692
+ aux_duplicates = {x for x in u_auxiliary if x in seen or seen.add(x)}
693
+ overlap_coords = set(coordinates).intersection(speeds)
694
+ overlap_aux = set(coordinates).union(speeds).intersection(u_auxiliary)
695
+ if coord_duplicates:
696
+ msgs.append(f'The generalized coordinates {coord_duplicates} are '
697
+ f'duplicated, all generalized coordinates should be '
698
+ f'unique.')
699
+ if speed_duplicates:
700
+ msgs.append(f'The generalized speeds {speed_duplicates} are '
701
+ f'duplicated, all generalized speeds should be unique.')
702
+ if aux_duplicates:
703
+ msgs.append(f'The auxiliary speeds {aux_duplicates} are duplicated,'
704
+ f' all auxiliary speeds should be unique.')
705
+ if overlap_coords:
706
+ msgs.append(f'{overlap_coords} are defined as both generalized '
707
+ f'coordinates and generalized speeds.')
708
+ if overlap_aux:
709
+ msgs.append(f'The auxiliary speeds {overlap_aux} are also defined '
710
+ f'as generalized coordinates or generalized speeds.')
711
+ if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols
712
+ for coordinate in coordinates:
713
+ if not (isinstance(coordinate, (AppliedUndef, Derivative)) and
714
+ coordinate.free_symbols == t_set):
715
+ msgs.append(f'Generalized coordinate "{coordinate}" is not a '
716
+ f'dynamicsymbol.')
717
+ for speed in speeds:
718
+ if not (isinstance(speed, (AppliedUndef, Derivative)) and
719
+ speed.free_symbols == t_set):
720
+ msgs.append(
721
+ f'Generalized speed "{speed}" is not a dynamicsymbol.')
722
+ for aux in u_auxiliary:
723
+ if not (isinstance(aux, (AppliedUndef, Derivative)) and
724
+ aux.free_symbols == t_set):
725
+ msgs.append(
726
+ f'Auxiliary speed "{aux}" is not a dynamicsymbol.')
727
+ if msgs:
728
+ raise ValueError('\n'.join(msgs))
729
+
730
+
731
+ def _parse_linear_solver(linear_solver):
732
+ """Helper function to retrieve a specified linear solver."""
733
+ if callable(linear_solver):
734
+ return linear_solver
735
+ return lambda A, b: Matrix.solve(A, b, method=linear_solver)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/inertia.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import sympify
2
+ from sympy.physics.vector import Point, Dyadic, ReferenceFrame, outer
3
+ from collections import namedtuple
4
+
5
+ __all__ = ['inertia', 'inertia_of_point_mass', 'Inertia']
6
+
7
+
8
+ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
9
+ """Simple way to create inertia Dyadic object.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ Creates an inertia Dyadic based on the given tensor values and a body-fixed
15
+ reference frame.
16
+
17
+ Parameters
18
+ ==========
19
+
20
+ frame : ReferenceFrame
21
+ The frame the inertia is defined in.
22
+ ixx : Sympifyable
23
+ The xx element in the inertia dyadic.
24
+ iyy : Sympifyable
25
+ The yy element in the inertia dyadic.
26
+ izz : Sympifyable
27
+ The zz element in the inertia dyadic.
28
+ ixy : Sympifyable
29
+ The xy element in the inertia dyadic.
30
+ iyz : Sympifyable
31
+ The yz element in the inertia dyadic.
32
+ izx : Sympifyable
33
+ The zx element in the inertia dyadic.
34
+
35
+ Examples
36
+ ========
37
+
38
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia
39
+ >>> N = ReferenceFrame('N')
40
+ >>> inertia(N, 1, 2, 3)
41
+ (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
42
+
43
+ """
44
+
45
+ if not isinstance(frame, ReferenceFrame):
46
+ raise TypeError('Need to define the inertia in a frame')
47
+ ixx, iyy, izz = sympify(ixx), sympify(iyy), sympify(izz)
48
+ ixy, iyz, izx = sympify(ixy), sympify(iyz), sympify(izx)
49
+ return (ixx*outer(frame.x, frame.x) + ixy*outer(frame.x, frame.y) +
50
+ izx*outer(frame.x, frame.z) + ixy*outer(frame.y, frame.x) +
51
+ iyy*outer(frame.y, frame.y) + iyz*outer(frame.y, frame.z) +
52
+ izx*outer(frame.z, frame.x) + iyz*outer(frame.z, frame.y) +
53
+ izz*outer(frame.z, frame.z))
54
+
55
+
56
+ def inertia_of_point_mass(mass, pos_vec, frame):
57
+ """Inertia dyadic of a point mass relative to point O.
58
+
59
+ Parameters
60
+ ==========
61
+
62
+ mass : Sympifyable
63
+ Mass of the point mass
64
+ pos_vec : Vector
65
+ Position from point O to point mass
66
+ frame : ReferenceFrame
67
+ Reference frame to express the dyadic in
68
+
69
+ Examples
70
+ ========
71
+
72
+ >>> from sympy import symbols
73
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
74
+ >>> N = ReferenceFrame('N')
75
+ >>> r, m = symbols('r m')
76
+ >>> px = r * N.x
77
+ >>> inertia_of_point_mass(m, px, N)
78
+ m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
79
+
80
+ """
81
+
82
+ return mass*(
83
+ (outer(frame.x, frame.x) +
84
+ outer(frame.y, frame.y) +
85
+ outer(frame.z, frame.z)) *
86
+ (pos_vec.dot(pos_vec)) - outer(pos_vec, pos_vec))
87
+
88
+
89
+ class Inertia(namedtuple('Inertia', ['dyadic', 'point'])):
90
+ """Inertia object consisting of a Dyadic and a Point of reference.
91
+
92
+ Explanation
93
+ ===========
94
+
95
+ This is a simple class to store the Point and Dyadic, belonging to an
96
+ inertia.
97
+
98
+ Attributes
99
+ ==========
100
+
101
+ dyadic : Dyadic
102
+ The dyadic of the inertia.
103
+ point : Point
104
+ The reference point of the inertia.
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Inertia
110
+ >>> N = ReferenceFrame('N')
111
+ >>> Po = Point('Po')
112
+ >>> Inertia(N.x.outer(N.x) + N.y.outer(N.y) + N.z.outer(N.z), Po)
113
+ ((N.x|N.x) + (N.y|N.y) + (N.z|N.z), Po)
114
+
115
+ In the example above the Dyadic was created manually, one can however also
116
+ use the ``inertia`` function for this or the class method ``from_tensor`` as
117
+ shown below.
118
+
119
+ >>> Inertia.from_inertia_scalars(Po, N, 1, 1, 1)
120
+ ((N.x|N.x) + (N.y|N.y) + (N.z|N.z), Po)
121
+
122
+ """
123
+ __slots__ = ()
124
+
125
+ def __new__(cls, dyadic, point):
126
+ # Switch order if given in the wrong order
127
+ if isinstance(dyadic, Point) and isinstance(point, Dyadic):
128
+ point, dyadic = dyadic, point
129
+ if not isinstance(point, Point):
130
+ raise TypeError('Reference point should be of type Point')
131
+ if not isinstance(dyadic, Dyadic):
132
+ raise TypeError('Inertia value should be expressed as a Dyadic')
133
+ return super().__new__(cls, dyadic, point)
134
+
135
+ @classmethod
136
+ def from_inertia_scalars(cls, point, frame, ixx, iyy, izz, ixy=0, iyz=0,
137
+ izx=0):
138
+ """Simple way to create an Inertia object based on the tensor values.
139
+
140
+ Explanation
141
+ ===========
142
+
143
+ This class method uses the :func`~.inertia` to create the Dyadic based
144
+ on the tensor values.
145
+
146
+ Parameters
147
+ ==========
148
+
149
+ point : Point
150
+ The reference point of the inertia.
151
+ frame : ReferenceFrame
152
+ The frame the inertia is defined in.
153
+ ixx : Sympifyable
154
+ The xx element in the inertia dyadic.
155
+ iyy : Sympifyable
156
+ The yy element in the inertia dyadic.
157
+ izz : Sympifyable
158
+ The zz element in the inertia dyadic.
159
+ ixy : Sympifyable
160
+ The xy element in the inertia dyadic.
161
+ iyz : Sympifyable
162
+ The yz element in the inertia dyadic.
163
+ izx : Sympifyable
164
+ The zx element in the inertia dyadic.
165
+
166
+ Examples
167
+ ========
168
+
169
+ >>> from sympy import symbols
170
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Inertia
171
+ >>> ixx, iyy, izz, ixy, iyz, izx = symbols('ixx iyy izz ixy iyz izx')
172
+ >>> N = ReferenceFrame('N')
173
+ >>> P = Point('P')
174
+ >>> I = Inertia.from_inertia_scalars(P, N, ixx, iyy, izz, ixy, iyz, izx)
175
+
176
+ The tensor values can easily be seen when converting the dyadic to a
177
+ matrix.
178
+
179
+ >>> I.dyadic.to_matrix(N)
180
+ Matrix([
181
+ [ixx, ixy, izx],
182
+ [ixy, iyy, iyz],
183
+ [izx, iyz, izz]])
184
+
185
+ """
186
+ return cls(inertia(frame, ixx, iyy, izz, ixy, iyz, izx), point)
187
+
188
+ def __add__(self, other):
189
+ raise TypeError(f"unsupported operand type(s) for +: "
190
+ f"'{self.__class__.__name__}' and "
191
+ f"'{other.__class__.__name__}'")
192
+
193
+ def __mul__(self, other):
194
+ raise TypeError(f"unsupported operand type(s) for *: "
195
+ f"'{self.__class__.__name__}' and "
196
+ f"'{other.__class__.__name__}'")
197
+
198
+ __radd__ = __add__
199
+ __rmul__ = __mul__
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py ADDED
@@ -0,0 +1,2188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy import pi, Derivative, Matrix
6
+ from sympy.core.function import AppliedUndef
7
+ from sympy.physics.mechanics.body_base import BodyBase
8
+ from sympy.physics.mechanics.functions import _validate_coordinates
9
+ from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point,
10
+ ReferenceFrame)
11
+ from sympy.utilities.iterables import iterable
12
+ from sympy.utilities.exceptions import sympy_deprecation_warning
13
+
14
+ __all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint',
15
+ 'PlanarJoint', 'SphericalJoint', 'WeldJoint']
16
+
17
+
18
+ class Joint(ABC):
19
+ """Abstract base class for all specific joints.
20
+
21
+ Explanation
22
+ ===========
23
+
24
+ A joint subtracts degrees of freedom from a body. This is the base class
25
+ for all specific joints and holds all common methods acting as an interface
26
+ for all joints. Custom joint can be created by inheriting Joint class and
27
+ defining all abstract functions.
28
+
29
+ The abstract methods are:
30
+
31
+ - ``_generate_coordinates``
32
+ - ``_generate_speeds``
33
+ - ``_orient_frames``
34
+ - ``_set_angular_velocity``
35
+ - ``_set_linear_velocity``
36
+
37
+ Parameters
38
+ ==========
39
+
40
+ name : string
41
+ A unique name for the joint.
42
+ parent : Particle or RigidBody
43
+ The parent body of joint.
44
+ child : Particle or RigidBody
45
+ The child body of joint.
46
+ coordinates : iterable of dynamicsymbols, optional
47
+ Generalized coordinates of the joint.
48
+ speeds : iterable of dynamicsymbols, optional
49
+ Generalized speeds of joint.
50
+ parent_point : Point or Vector, optional
51
+ Attachment point where the joint is fixed to the parent body. If a
52
+ vector is provided, then the attachment point is computed by adding the
53
+ vector to the body's mass center. The default value is the parent's mass
54
+ center.
55
+ child_point : Point or Vector, optional
56
+ Attachment point where the joint is fixed to the child body. If a
57
+ vector is provided, then the attachment point is computed by adding the
58
+ vector to the body's mass center. The default value is the child's mass
59
+ center.
60
+ parent_axis : Vector, optional
61
+ .. deprecated:: 1.12
62
+ Axis fixed in the parent body which aligns with an axis fixed in the
63
+ child body. The default is the x axis of parent's reference frame.
64
+ For more information on this deprecation, see
65
+ :ref:`deprecated-mechanics-joint-axis`.
66
+ child_axis : Vector, optional
67
+ .. deprecated:: 1.12
68
+ Axis fixed in the child body which aligns with an axis fixed in the
69
+ parent body. The default is the x axis of child's reference frame.
70
+ For more information on this deprecation, see
71
+ :ref:`deprecated-mechanics-joint-axis`.
72
+ parent_interframe : ReferenceFrame, optional
73
+ Intermediate frame of the parent body with respect to which the joint
74
+ transformation is formulated. If a Vector is provided then an interframe
75
+ is created which aligns its X axis with the given vector. The default
76
+ value is the parent's own frame.
77
+ child_interframe : ReferenceFrame, optional
78
+ Intermediate frame of the child body with respect to which the joint
79
+ transformation is formulated. If a Vector is provided then an interframe
80
+ is created which aligns its X axis with the given vector. The default
81
+ value is the child's own frame.
82
+ parent_joint_pos : Point or Vector, optional
83
+ .. deprecated:: 1.12
84
+ This argument is replaced by parent_point and will be removed in a
85
+ future version.
86
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
87
+ child_joint_pos : Point or Vector, optional
88
+ .. deprecated:: 1.12
89
+ This argument is replaced by child_point and will be removed in a
90
+ future version.
91
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
92
+
93
+ Attributes
94
+ ==========
95
+
96
+ name : string
97
+ The joint's name.
98
+ parent : Particle or RigidBody
99
+ The joint's parent body.
100
+ child : Particle or RigidBody
101
+ The joint's child body.
102
+ coordinates : Matrix
103
+ Matrix of the joint's generalized coordinates.
104
+ speeds : Matrix
105
+ Matrix of the joint's generalized speeds.
106
+ parent_point : Point
107
+ Attachment point where the joint is fixed to the parent body.
108
+ child_point : Point
109
+ Attachment point where the joint is fixed to the child body.
110
+ parent_axis : Vector
111
+ The axis fixed in the parent frame that represents the joint.
112
+ child_axis : Vector
113
+ The axis fixed in the child frame that represents the joint.
114
+ parent_interframe : ReferenceFrame
115
+ Intermediate frame of the parent body with respect to which the joint
116
+ transformation is formulated.
117
+ child_interframe : ReferenceFrame
118
+ Intermediate frame of the child body with respect to which the joint
119
+ transformation is formulated.
120
+ kdes : Matrix
121
+ Kinematical differential equations of the joint.
122
+
123
+ Notes
124
+ =====
125
+
126
+ When providing a vector as the intermediate frame, a new intermediate frame
127
+ is created which aligns its X axis with the provided vector. This is done
128
+ with a single fixed rotation about a rotation axis. This rotation axis is
129
+ determined by taking the cross product of the ``body.x`` axis with the
130
+ provided vector. In the case where the provided vector is in the ``-body.x``
131
+ direction, the rotation is done about the ``body.y`` axis.
132
+
133
+ """
134
+
135
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
136
+ parent_point=None, child_point=None, parent_interframe=None,
137
+ child_interframe=None, parent_axis=None, child_axis=None,
138
+ parent_joint_pos=None, child_joint_pos=None):
139
+
140
+ if not isinstance(name, str):
141
+ raise TypeError('Supply a valid name.')
142
+ self._name = name
143
+
144
+ if not isinstance(parent, BodyBase):
145
+ raise TypeError('Parent must be a body.')
146
+ self._parent = parent
147
+
148
+ if not isinstance(child, BodyBase):
149
+ raise TypeError('Child must be a body.')
150
+ self._child = child
151
+
152
+ if parent_axis is not None or child_axis is not None:
153
+ sympy_deprecation_warning(
154
+ """
155
+ The parent_axis and child_axis arguments for the Joint classes
156
+ are deprecated. Instead use parent_interframe, child_interframe.
157
+ """,
158
+ deprecated_since_version="1.12",
159
+ active_deprecations_target="deprecated-mechanics-joint-axis",
160
+ stacklevel=4
161
+ )
162
+ if parent_interframe is None:
163
+ parent_interframe = parent_axis
164
+ if child_interframe is None:
165
+ child_interframe = child_axis
166
+
167
+ # Set parent and child frame attributes
168
+ if hasattr(self._parent, 'frame'):
169
+ self._parent_frame = self._parent.frame
170
+ else:
171
+ if isinstance(parent_interframe, ReferenceFrame):
172
+ self._parent_frame = parent_interframe
173
+ else:
174
+ self._parent_frame = ReferenceFrame(
175
+ f'{self.name}_{self._parent.name}_frame')
176
+ if hasattr(self._child, 'frame'):
177
+ self._child_frame = self._child.frame
178
+ else:
179
+ if isinstance(child_interframe, ReferenceFrame):
180
+ self._child_frame = child_interframe
181
+ else:
182
+ self._child_frame = ReferenceFrame(
183
+ f'{self.name}_{self._child.name}_frame')
184
+
185
+ self._parent_interframe = self._locate_joint_frame(
186
+ self._parent, parent_interframe, self._parent_frame)
187
+ self._child_interframe = self._locate_joint_frame(
188
+ self._child, child_interframe, self._child_frame)
189
+ self._parent_axis = self._axis(parent_axis, self._parent_frame)
190
+ self._child_axis = self._axis(child_axis, self._child_frame)
191
+
192
+ if parent_joint_pos is not None or child_joint_pos is not None:
193
+ sympy_deprecation_warning(
194
+ """
195
+ The parent_joint_pos and child_joint_pos arguments for the Joint
196
+ classes are deprecated. Instead use parent_point and child_point.
197
+ """,
198
+ deprecated_since_version="1.12",
199
+ active_deprecations_target="deprecated-mechanics-joint-pos",
200
+ stacklevel=4
201
+ )
202
+ if parent_point is None:
203
+ parent_point = parent_joint_pos
204
+ if child_point is None:
205
+ child_point = child_joint_pos
206
+ self._parent_point = self._locate_joint_pos(
207
+ self._parent, parent_point, self._parent_frame)
208
+ self._child_point = self._locate_joint_pos(
209
+ self._child, child_point, self._child_frame)
210
+
211
+ self._coordinates = self._generate_coordinates(coordinates)
212
+ self._speeds = self._generate_speeds(speeds)
213
+ _validate_coordinates(self.coordinates, self.speeds)
214
+ self._kdes = self._generate_kdes()
215
+
216
+ self._orient_frames()
217
+ self._set_angular_velocity()
218
+ self._set_linear_velocity()
219
+
220
+ def __str__(self):
221
+ return self.name
222
+
223
+ def __repr__(self):
224
+ return self.__str__()
225
+
226
+ @property
227
+ def name(self):
228
+ """Name of the joint."""
229
+ return self._name
230
+
231
+ @property
232
+ def parent(self):
233
+ """Parent body of Joint."""
234
+ return self._parent
235
+
236
+ @property
237
+ def child(self):
238
+ """Child body of Joint."""
239
+ return self._child
240
+
241
+ @property
242
+ def coordinates(self):
243
+ """Matrix of the joint's generalized coordinates."""
244
+ return self._coordinates
245
+
246
+ @property
247
+ def speeds(self):
248
+ """Matrix of the joint's generalized speeds."""
249
+ return self._speeds
250
+
251
+ @property
252
+ def kdes(self):
253
+ """Kinematical differential equations of the joint."""
254
+ return self._kdes
255
+
256
+ @property
257
+ def parent_axis(self):
258
+ """The axis of parent frame."""
259
+ # Will be removed with `deprecated-mechanics-joint-axis`
260
+ return self._parent_axis
261
+
262
+ @property
263
+ def child_axis(self):
264
+ """The axis of child frame."""
265
+ # Will be removed with `deprecated-mechanics-joint-axis`
266
+ return self._child_axis
267
+
268
+ @property
269
+ def parent_point(self):
270
+ """Attachment point where the joint is fixed to the parent body."""
271
+ return self._parent_point
272
+
273
+ @property
274
+ def child_point(self):
275
+ """Attachment point where the joint is fixed to the child body."""
276
+ return self._child_point
277
+
278
+ @property
279
+ def parent_interframe(self):
280
+ return self._parent_interframe
281
+
282
+ @property
283
+ def child_interframe(self):
284
+ return self._child_interframe
285
+
286
+ @abstractmethod
287
+ def _generate_coordinates(self, coordinates):
288
+ """Generate Matrix of the joint's generalized coordinates."""
289
+ pass
290
+
291
+ @abstractmethod
292
+ def _generate_speeds(self, speeds):
293
+ """Generate Matrix of the joint's generalized speeds."""
294
+ pass
295
+
296
+ @abstractmethod
297
+ def _orient_frames(self):
298
+ """Orient frames as per the joint."""
299
+ pass
300
+
301
+ @abstractmethod
302
+ def _set_angular_velocity(self):
303
+ """Set angular velocity of the joint related frames."""
304
+ pass
305
+
306
+ @abstractmethod
307
+ def _set_linear_velocity(self):
308
+ """Set velocity of related points to the joint."""
309
+ pass
310
+
311
+ @staticmethod
312
+ def _to_vector(matrix, frame):
313
+ """Converts a matrix to a vector in the given frame."""
314
+ return Vector([(matrix, frame)])
315
+
316
+ @staticmethod
317
+ def _axis(ax, *frames):
318
+ """Check whether an axis is fixed in one of the frames."""
319
+ if ax is None:
320
+ ax = frames[0].x
321
+ return ax
322
+ if not isinstance(ax, Vector):
323
+ raise TypeError("Axis must be a Vector.")
324
+ ref_frame = None # Find a body in which the axis can be expressed
325
+ for frame in frames:
326
+ try:
327
+ ax.to_matrix(frame)
328
+ except ValueError:
329
+ pass
330
+ else:
331
+ ref_frame = frame
332
+ break
333
+ if ref_frame is None:
334
+ raise ValueError("Axis cannot be expressed in one of the body's "
335
+ "frames.")
336
+ if not ax.dt(ref_frame) == 0:
337
+ raise ValueError('Axis cannot be time-varying when viewed from the '
338
+ 'associated body.')
339
+ return ax
340
+
341
+ @staticmethod
342
+ def _choose_rotation_axis(frame, axis):
343
+ components = axis.to_matrix(frame)
344
+ x, y, z = components[0], components[1], components[2]
345
+
346
+ if x != 0:
347
+ if y != 0:
348
+ if z != 0:
349
+ return cross(axis, frame.x)
350
+ if z != 0:
351
+ return frame.y
352
+ return frame.z
353
+ else:
354
+ if y != 0:
355
+ return frame.x
356
+ return frame.y
357
+
358
+ @staticmethod
359
+ def _create_aligned_interframe(frame, align_axis, frame_axis=None,
360
+ frame_name=None):
361
+ """
362
+ Returns an intermediate frame, where the ``frame_axis`` defined in
363
+ ``frame`` is aligned with ``axis``. By default this means that the X
364
+ axis will be aligned with ``axis``.
365
+
366
+ Parameters
367
+ ==========
368
+
369
+ frame : BodyBase or ReferenceFrame
370
+ The body or reference frame with respect to which the intermediate
371
+ frame is oriented.
372
+ align_axis : Vector
373
+ The vector with respect to which the intermediate frame will be
374
+ aligned.
375
+ frame_axis : Vector
376
+ The vector of the frame which should get aligned with ``axis``. The
377
+ default is the X axis of the frame.
378
+ frame_name : string
379
+ Name of the to be created intermediate frame. The default adds
380
+ "_int_frame" to the name of ``frame``.
381
+
382
+ Example
383
+ =======
384
+
385
+ An intermediate frame, where the X axis of the parent becomes aligned
386
+ with ``parent.y + parent.z`` can be created as follows:
387
+
388
+ >>> from sympy.physics.mechanics.joint import Joint
389
+ >>> from sympy.physics.mechanics import RigidBody
390
+ >>> parent = RigidBody('parent')
391
+ >>> parent_interframe = Joint._create_aligned_interframe(
392
+ ... parent, parent.y + parent.z)
393
+ >>> parent_interframe
394
+ parent_int_frame
395
+ >>> parent.frame.dcm(parent_interframe)
396
+ Matrix([
397
+ [ 0, -sqrt(2)/2, -sqrt(2)/2],
398
+ [sqrt(2)/2, 1/2, -1/2],
399
+ [sqrt(2)/2, -1/2, 1/2]])
400
+ >>> (parent.y + parent.z).express(parent_interframe)
401
+ sqrt(2)*parent_int_frame.x
402
+
403
+ Notes
404
+ =====
405
+
406
+ The direction cosine matrix between the given frame and intermediate
407
+ frame is formed using a simple rotation about an axis that is normal to
408
+ both ``align_axis`` and ``frame_axis``. In general, the normal axis is
409
+ formed by crossing the ``frame_axis`` with the ``align_axis``. The
410
+ exception is if the axes are parallel with opposite directions, in which
411
+ case the rotation vector is chosen using the rules in the following
412
+ table with the vectors expressed in the given frame:
413
+
414
+ .. list-table::
415
+ :header-rows: 1
416
+
417
+ * - ``align_axis``
418
+ - ``frame_axis``
419
+ - ``rotation_axis``
420
+ * - ``-x``
421
+ - ``x``
422
+ - ``z``
423
+ * - ``-y``
424
+ - ``y``
425
+ - ``x``
426
+ * - ``-z``
427
+ - ``z``
428
+ - ``y``
429
+ * - ``-x-y``
430
+ - ``x+y``
431
+ - ``z``
432
+ * - ``-y-z``
433
+ - ``y+z``
434
+ - ``x``
435
+ * - ``-x-z``
436
+ - ``x+z``
437
+ - ``y``
438
+ * - ``-x-y-z``
439
+ - ``x+y+z``
440
+ - ``(x+y+z) × x``
441
+
442
+ """
443
+ if isinstance(frame, BodyBase):
444
+ frame = frame.frame
445
+ if frame_axis is None:
446
+ frame_axis = frame.x
447
+ if frame_name is None:
448
+ if frame.name[-6:] == '_frame':
449
+ frame_name = f'{frame.name[:-6]}_int_frame'
450
+ else:
451
+ frame_name = f'{frame.name}_int_frame'
452
+ angle = frame_axis.angle_between(align_axis)
453
+ rotation_axis = cross(frame_axis, align_axis)
454
+ if rotation_axis == Vector(0) and angle == 0:
455
+ return frame
456
+ if angle == pi:
457
+ rotation_axis = Joint._choose_rotation_axis(frame, align_axis)
458
+
459
+ int_frame = ReferenceFrame(frame_name)
460
+ int_frame.orient_axis(frame, rotation_axis, angle)
461
+ int_frame.set_ang_vel(frame, 0 * rotation_axis)
462
+ return int_frame
463
+
464
+ def _generate_kdes(self):
465
+ """Generate kinematical differential equations."""
466
+ kdes = []
467
+ t = dynamicsymbols._t
468
+ for i in range(len(self.coordinates)):
469
+ kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
470
+ return Matrix(kdes)
471
+
472
+ def _locate_joint_pos(self, body, joint_pos, body_frame=None):
473
+ """Returns the attachment point of a body."""
474
+ if body_frame is None:
475
+ body_frame = body.frame
476
+ if joint_pos is None:
477
+ return body.masscenter
478
+ if not isinstance(joint_pos, (Point, Vector)):
479
+ raise TypeError('Attachment point must be a Point or Vector.')
480
+ if isinstance(joint_pos, Vector):
481
+ point_name = f'{self.name}_{body.name}_joint'
482
+ joint_pos = body.masscenter.locatenew(point_name, joint_pos)
483
+ if not joint_pos.pos_from(body.masscenter).dt(body_frame) == 0:
484
+ raise ValueError('Attachment point must be fixed to the associated '
485
+ 'body.')
486
+ return joint_pos
487
+
488
+ def _locate_joint_frame(self, body, interframe, body_frame=None):
489
+ """Returns the attachment frame of a body."""
490
+ if body_frame is None:
491
+ body_frame = body.frame
492
+ if interframe is None:
493
+ return body_frame
494
+ if isinstance(interframe, Vector):
495
+ interframe = Joint._create_aligned_interframe(
496
+ body_frame, interframe,
497
+ frame_name=f'{self.name}_{body.name}_int_frame')
498
+ elif not isinstance(interframe, ReferenceFrame):
499
+ raise TypeError('Interframe must be a ReferenceFrame.')
500
+ if not interframe.ang_vel_in(body_frame) == 0:
501
+ raise ValueError(f'Interframe {interframe} is not fixed to body '
502
+ f'{body}.')
503
+ body.masscenter.set_vel(interframe, 0) # Fixate interframe to body
504
+ return interframe
505
+
506
+ def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0,
507
+ number_single=False):
508
+ """Helper method for _generate_coordinates and _generate_speeds.
509
+
510
+ Parameters
511
+ ==========
512
+
513
+ coordinates : iterable
514
+ Iterable of coordinates or speeds that have been provided.
515
+ n_coords : Integer
516
+ Number of coordinates that should be returned.
517
+ label : String, optional
518
+ Coordinate type either 'q' (coordinates) or 'u' (speeds). The
519
+ Default is 'q'.
520
+ offset : Integer
521
+ Count offset when creating new dynamicsymbols. The default is 0.
522
+ number_single : Boolean
523
+ Boolean whether if n_coords == 1, number should still be used. The
524
+ default is False.
525
+
526
+ """
527
+
528
+ def create_symbol(number):
529
+ if n_coords == 1 and not number_single:
530
+ return dynamicsymbols(f'{label}_{self.name}')
531
+ return dynamicsymbols(f'{label}{number}_{self.name}')
532
+
533
+ name = 'generalized coordinate' if label == 'q' else 'generalized speed'
534
+ generated_coordinates = []
535
+ if coordinates is None:
536
+ coordinates = []
537
+ elif not iterable(coordinates):
538
+ coordinates = [coordinates]
539
+ if not (len(coordinates) == 0 or len(coordinates) == n_coords):
540
+ raise ValueError(f'Expected {n_coords} {name}s, instead got '
541
+ f'{len(coordinates)} {name}s.')
542
+ # Supports more iterables, also Matrix
543
+ for i, coord in enumerate(coordinates):
544
+ if coord is None:
545
+ generated_coordinates.append(create_symbol(i + offset))
546
+ elif isinstance(coord, (AppliedUndef, Derivative)):
547
+ generated_coordinates.append(coord)
548
+ else:
549
+ raise TypeError(f'The {name} {coord} should have been a '
550
+ f'dynamicsymbol.')
551
+ for i in range(len(coordinates) + offset, n_coords + offset):
552
+ generated_coordinates.append(create_symbol(i))
553
+ return Matrix(generated_coordinates)
554
+
555
+
556
+ class PinJoint(Joint):
557
+ """Pin (Revolute) Joint.
558
+
559
+ .. raw:: html
560
+ :file: ../../../doc/src/explanation/modules/physics/mechanics/PinJoint.svg
561
+
562
+ Explanation
563
+ ===========
564
+
565
+ A pin joint is defined such that the joint rotation axis is fixed in both
566
+ the child and parent and the location of the joint is relative to the mass
567
+ center of each body. The child rotates an angle, θ, from the parent about
568
+ the rotation axis and has a simple angular speed, ω, relative to the
569
+ parent. The direction cosine matrix between the child interframe and
570
+ parent interframe is formed using a simple rotation about the joint axis.
571
+ The page on the joints framework gives a more detailed explanation of the
572
+ intermediate frames.
573
+
574
+ Parameters
575
+ ==========
576
+
577
+ name : string
578
+ A unique name for the joint.
579
+ parent : Particle or RigidBody
580
+ The parent body of joint.
581
+ child : Particle or RigidBody
582
+ The child body of joint.
583
+ coordinates : dynamicsymbol, optional
584
+ Generalized coordinates of the joint.
585
+ speeds : dynamicsymbol, optional
586
+ Generalized speeds of joint.
587
+ parent_point : Point or Vector, optional
588
+ Attachment point where the joint is fixed to the parent body. If a
589
+ vector is provided, then the attachment point is computed by adding the
590
+ vector to the body's mass center. The default value is the parent's mass
591
+ center.
592
+ child_point : Point or Vector, optional
593
+ Attachment point where the joint is fixed to the child body. If a
594
+ vector is provided, then the attachment point is computed by adding the
595
+ vector to the body's mass center. The default value is the child's mass
596
+ center.
597
+ parent_axis : Vector, optional
598
+ .. deprecated:: 1.12
599
+ Axis fixed in the parent body which aligns with an axis fixed in the
600
+ child body. The default is the x axis of parent's reference frame.
601
+ For more information on this deprecation, see
602
+ :ref:`deprecated-mechanics-joint-axis`.
603
+ child_axis : Vector, optional
604
+ .. deprecated:: 1.12
605
+ Axis fixed in the child body which aligns with an axis fixed in the
606
+ parent body. The default is the x axis of child's reference frame.
607
+ For more information on this deprecation, see
608
+ :ref:`deprecated-mechanics-joint-axis`.
609
+ parent_interframe : ReferenceFrame, optional
610
+ Intermediate frame of the parent body with respect to which the joint
611
+ transformation is formulated. If a Vector is provided then an interframe
612
+ is created which aligns its X axis with the given vector. The default
613
+ value is the parent's own frame.
614
+ child_interframe : ReferenceFrame, optional
615
+ Intermediate frame of the child body with respect to which the joint
616
+ transformation is formulated. If a Vector is provided then an interframe
617
+ is created which aligns its X axis with the given vector. The default
618
+ value is the child's own frame.
619
+ joint_axis : Vector
620
+ The axis about which the rotation occurs. Note that the components
621
+ of this axis are the same in the parent_interframe and child_interframe.
622
+ parent_joint_pos : Point or Vector, optional
623
+ .. deprecated:: 1.12
624
+ This argument is replaced by parent_point and will be removed in a
625
+ future version.
626
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
627
+ child_joint_pos : Point or Vector, optional
628
+ .. deprecated:: 1.12
629
+ This argument is replaced by child_point and will be removed in a
630
+ future version.
631
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
632
+
633
+ Attributes
634
+ ==========
635
+
636
+ name : string
637
+ The joint's name.
638
+ parent : Particle or RigidBody
639
+ The joint's parent body.
640
+ child : Particle or RigidBody
641
+ The joint's child body.
642
+ coordinates : Matrix
643
+ Matrix of the joint's generalized coordinates. The default value is
644
+ ``dynamicsymbols(f'q_{joint.name}')``.
645
+ speeds : Matrix
646
+ Matrix of the joint's generalized speeds. The default value is
647
+ ``dynamicsymbols(f'u_{joint.name}')``.
648
+ parent_point : Point
649
+ Attachment point where the joint is fixed to the parent body.
650
+ child_point : Point
651
+ Attachment point where the joint is fixed to the child body.
652
+ parent_axis : Vector
653
+ The axis fixed in the parent frame that represents the joint.
654
+ child_axis : Vector
655
+ The axis fixed in the child frame that represents the joint.
656
+ parent_interframe : ReferenceFrame
657
+ Intermediate frame of the parent body with respect to which the joint
658
+ transformation is formulated.
659
+ child_interframe : ReferenceFrame
660
+ Intermediate frame of the child body with respect to which the joint
661
+ transformation is formulated.
662
+ joint_axis : Vector
663
+ The axis about which the rotation occurs. Note that the components of
664
+ this axis are the same in the parent_interframe and child_interframe.
665
+ kdes : Matrix
666
+ Kinematical differential equations of the joint.
667
+
668
+ Examples
669
+ =========
670
+
671
+ A single pin joint is created from two bodies and has the following basic
672
+ attributes:
673
+
674
+ >>> from sympy.physics.mechanics import RigidBody, PinJoint
675
+ >>> parent = RigidBody('P')
676
+ >>> parent
677
+ P
678
+ >>> child = RigidBody('C')
679
+ >>> child
680
+ C
681
+ >>> joint = PinJoint('PC', parent, child)
682
+ >>> joint
683
+ PinJoint: PC parent: P child: C
684
+ >>> joint.name
685
+ 'PC'
686
+ >>> joint.parent
687
+ P
688
+ >>> joint.child
689
+ C
690
+ >>> joint.parent_point
691
+ P_masscenter
692
+ >>> joint.child_point
693
+ C_masscenter
694
+ >>> joint.parent_axis
695
+ P_frame.x
696
+ >>> joint.child_axis
697
+ C_frame.x
698
+ >>> joint.coordinates
699
+ Matrix([[q_PC(t)]])
700
+ >>> joint.speeds
701
+ Matrix([[u_PC(t)]])
702
+ >>> child.frame.ang_vel_in(parent.frame)
703
+ u_PC(t)*P_frame.x
704
+ >>> child.frame.dcm(parent.frame)
705
+ Matrix([
706
+ [1, 0, 0],
707
+ [0, cos(q_PC(t)), sin(q_PC(t))],
708
+ [0, -sin(q_PC(t)), cos(q_PC(t))]])
709
+ >>> joint.child_point.pos_from(joint.parent_point)
710
+ 0
711
+
712
+ To further demonstrate the use of the pin joint, the kinematics of simple
713
+ double pendulum that rotates about the Z axis of each connected body can be
714
+ created as follows.
715
+
716
+ >>> from sympy import symbols, trigsimp
717
+ >>> from sympy.physics.mechanics import RigidBody, PinJoint
718
+ >>> l1, l2 = symbols('l1 l2')
719
+
720
+ First create bodies to represent the fixed ceiling and one to represent
721
+ each pendulum bob.
722
+
723
+ >>> ceiling = RigidBody('C')
724
+ >>> upper_bob = RigidBody('U')
725
+ >>> lower_bob = RigidBody('L')
726
+
727
+ The first joint will connect the upper bob to the ceiling by a distance of
728
+ ``l1`` and the joint axis will be about the Z axis for each body.
729
+
730
+ >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
731
+ ... child_point=-l1*upper_bob.frame.x,
732
+ ... joint_axis=ceiling.frame.z)
733
+
734
+ The second joint will connect the lower bob to the upper bob by a distance
735
+ of ``l2`` and the joint axis will also be about the Z axis for each body.
736
+
737
+ >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
738
+ ... child_point=-l2*lower_bob.frame.x,
739
+ ... joint_axis=upper_bob.frame.z)
740
+
741
+ Once the joints are established the kinematics of the connected bodies can
742
+ be accessed. First the direction cosine matrices of pendulum link relative
743
+ to the ceiling are found:
744
+
745
+ >>> upper_bob.frame.dcm(ceiling.frame)
746
+ Matrix([
747
+ [ cos(q_P1(t)), sin(q_P1(t)), 0],
748
+ [-sin(q_P1(t)), cos(q_P1(t)), 0],
749
+ [ 0, 0, 1]])
750
+ >>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
751
+ Matrix([
752
+ [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0],
753
+ [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0],
754
+ [ 0, 0, 1]])
755
+
756
+ The position of the lower bob's masscenter is found with:
757
+
758
+ >>> lower_bob.masscenter.pos_from(ceiling.masscenter)
759
+ l1*U_frame.x + l2*L_frame.x
760
+
761
+ The angular velocities of the two pendulum links can be computed with
762
+ respect to the ceiling.
763
+
764
+ >>> upper_bob.frame.ang_vel_in(ceiling.frame)
765
+ u_P1(t)*C_frame.z
766
+ >>> lower_bob.frame.ang_vel_in(ceiling.frame)
767
+ u_P1(t)*C_frame.z + u_P2(t)*U_frame.z
768
+
769
+ And finally, the linear velocities of the two pendulum bobs can be computed
770
+ with respect to the ceiling.
771
+
772
+ >>> upper_bob.masscenter.vel(ceiling.frame)
773
+ l1*u_P1(t)*U_frame.y
774
+ >>> lower_bob.masscenter.vel(ceiling.frame)
775
+ l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y
776
+
777
+ """
778
+
779
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
780
+ parent_point=None, child_point=None, parent_interframe=None,
781
+ child_interframe=None, parent_axis=None, child_axis=None,
782
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
783
+
784
+ self._joint_axis = joint_axis
785
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
786
+ child_point, parent_interframe, child_interframe,
787
+ parent_axis, child_axis, parent_joint_pos,
788
+ child_joint_pos)
789
+
790
+ def __str__(self):
791
+ return (f'PinJoint: {self.name} parent: {self.parent} '
792
+ f'child: {self.child}')
793
+
794
+ @property
795
+ def joint_axis(self):
796
+ """Axis about which the child rotates with respect to the parent."""
797
+ return self._joint_axis
798
+
799
+ def _generate_coordinates(self, coordinate):
800
+ return self._fill_coordinate_list(coordinate, 1, 'q')
801
+
802
+ def _generate_speeds(self, speed):
803
+ return self._fill_coordinate_list(speed, 1, 'u')
804
+
805
+ def _orient_frames(self):
806
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
807
+ self.child_interframe.orient_axis(
808
+ self.parent_interframe, self.joint_axis, self.coordinates[0])
809
+
810
+ def _set_angular_velocity(self):
811
+ self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[
812
+ 0] * self.joint_axis.normalize())
813
+
814
+ def _set_linear_velocity(self):
815
+ self.child_point.set_pos(self.parent_point, 0)
816
+ self.parent_point.set_vel(self._parent_frame, 0)
817
+ self.child_point.set_vel(self._child_frame, 0)
818
+ self.child.masscenter.v2pt_theory(self.parent_point,
819
+ self._parent_frame, self._child_frame)
820
+
821
+
822
+ class PrismaticJoint(Joint):
823
+ """Prismatic (Sliding) Joint.
824
+
825
+ .. image:: PrismaticJoint.svg
826
+
827
+ Explanation
828
+ ===========
829
+
830
+ It is defined such that the child body translates with respect to the parent
831
+ body along the body-fixed joint axis. The location of the joint is defined
832
+ by two points, one in each body, which coincide when the generalized
833
+ coordinate is zero. The direction cosine matrix between the
834
+ parent_interframe and child_interframe is the identity matrix. Therefore,
835
+ the direction cosine matrix between the parent and child frames is fully
836
+ defined by the definition of the intermediate frames. The page on the joints
837
+ framework gives a more detailed explanation of the intermediate frames.
838
+
839
+ Parameters
840
+ ==========
841
+
842
+ name : string
843
+ A unique name for the joint.
844
+ parent : Particle or RigidBody
845
+ The parent body of joint.
846
+ child : Particle or RigidBody
847
+ The child body of joint.
848
+ coordinates : dynamicsymbol, optional
849
+ Generalized coordinates of the joint. The default value is
850
+ ``dynamicsymbols(f'q_{joint.name}')``.
851
+ speeds : dynamicsymbol, optional
852
+ Generalized speeds of joint. The default value is
853
+ ``dynamicsymbols(f'u_{joint.name}')``.
854
+ parent_point : Point or Vector, optional
855
+ Attachment point where the joint is fixed to the parent body. If a
856
+ vector is provided, then the attachment point is computed by adding the
857
+ vector to the body's mass center. The default value is the parent's mass
858
+ center.
859
+ child_point : Point or Vector, optional
860
+ Attachment point where the joint is fixed to the child body. If a
861
+ vector is provided, then the attachment point is computed by adding the
862
+ vector to the body's mass center. The default value is the child's mass
863
+ center.
864
+ parent_axis : Vector, optional
865
+ .. deprecated:: 1.12
866
+ Axis fixed in the parent body which aligns with an axis fixed in the
867
+ child body. The default is the x axis of parent's reference frame.
868
+ For more information on this deprecation, see
869
+ :ref:`deprecated-mechanics-joint-axis`.
870
+ child_axis : Vector, optional
871
+ .. deprecated:: 1.12
872
+ Axis fixed in the child body which aligns with an axis fixed in the
873
+ parent body. The default is the x axis of child's reference frame.
874
+ For more information on this deprecation, see
875
+ :ref:`deprecated-mechanics-joint-axis`.
876
+ parent_interframe : ReferenceFrame, optional
877
+ Intermediate frame of the parent body with respect to which the joint
878
+ transformation is formulated. If a Vector is provided then an interframe
879
+ is created which aligns its X axis with the given vector. The default
880
+ value is the parent's own frame.
881
+ child_interframe : ReferenceFrame, optional
882
+ Intermediate frame of the child body with respect to which the joint
883
+ transformation is formulated. If a Vector is provided then an interframe
884
+ is created which aligns its X axis with the given vector. The default
885
+ value is the child's own frame.
886
+ joint_axis : Vector
887
+ The axis along which the translation occurs. Note that the components
888
+ of this axis are the same in the parent_interframe and child_interframe.
889
+ parent_joint_pos : Point or Vector, optional
890
+ .. deprecated:: 1.12
891
+ This argument is replaced by parent_point and will be removed in a
892
+ future version.
893
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
894
+ child_joint_pos : Point or Vector, optional
895
+ .. deprecated:: 1.12
896
+ This argument is replaced by child_point and will be removed in a
897
+ future version.
898
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
899
+
900
+ Attributes
901
+ ==========
902
+
903
+ name : string
904
+ The joint's name.
905
+ parent : Particle or RigidBody
906
+ The joint's parent body.
907
+ child : Particle or RigidBody
908
+ The joint's child body.
909
+ coordinates : Matrix
910
+ Matrix of the joint's generalized coordinates.
911
+ speeds : Matrix
912
+ Matrix of the joint's generalized speeds.
913
+ parent_point : Point
914
+ Attachment point where the joint is fixed to the parent body.
915
+ child_point : Point
916
+ Attachment point where the joint is fixed to the child body.
917
+ parent_axis : Vector
918
+ The axis fixed in the parent frame that represents the joint.
919
+ child_axis : Vector
920
+ The axis fixed in the child frame that represents the joint.
921
+ parent_interframe : ReferenceFrame
922
+ Intermediate frame of the parent body with respect to which the joint
923
+ transformation is formulated.
924
+ child_interframe : ReferenceFrame
925
+ Intermediate frame of the child body with respect to which the joint
926
+ transformation is formulated.
927
+ kdes : Matrix
928
+ Kinematical differential equations of the joint.
929
+
930
+ Examples
931
+ =========
932
+
933
+ A single prismatic joint is created from two bodies and has the following
934
+ basic attributes:
935
+
936
+ >>> from sympy.physics.mechanics import RigidBody, PrismaticJoint
937
+ >>> parent = RigidBody('P')
938
+ >>> parent
939
+ P
940
+ >>> child = RigidBody('C')
941
+ >>> child
942
+ C
943
+ >>> joint = PrismaticJoint('PC', parent, child)
944
+ >>> joint
945
+ PrismaticJoint: PC parent: P child: C
946
+ >>> joint.name
947
+ 'PC'
948
+ >>> joint.parent
949
+ P
950
+ >>> joint.child
951
+ C
952
+ >>> joint.parent_point
953
+ P_masscenter
954
+ >>> joint.child_point
955
+ C_masscenter
956
+ >>> joint.parent_axis
957
+ P_frame.x
958
+ >>> joint.child_axis
959
+ C_frame.x
960
+ >>> joint.coordinates
961
+ Matrix([[q_PC(t)]])
962
+ >>> joint.speeds
963
+ Matrix([[u_PC(t)]])
964
+ >>> child.frame.ang_vel_in(parent.frame)
965
+ 0
966
+ >>> child.frame.dcm(parent.frame)
967
+ Matrix([
968
+ [1, 0, 0],
969
+ [0, 1, 0],
970
+ [0, 0, 1]])
971
+ >>> joint.child_point.pos_from(joint.parent_point)
972
+ q_PC(t)*P_frame.x
973
+
974
+ To further demonstrate the use of the prismatic joint, the kinematics of two
975
+ masses sliding, one moving relative to a fixed body and the other relative
976
+ to the moving body. about the X axis of each connected body can be created
977
+ as follows.
978
+
979
+ >>> from sympy.physics.mechanics import PrismaticJoint, RigidBody
980
+
981
+ First create bodies to represent the fixed ceiling and one to represent
982
+ a particle.
983
+
984
+ >>> wall = RigidBody('W')
985
+ >>> Part1 = RigidBody('P1')
986
+ >>> Part2 = RigidBody('P2')
987
+
988
+ The first joint will connect the particle to the ceiling and the
989
+ joint axis will be about the X axis for each body.
990
+
991
+ >>> J1 = PrismaticJoint('J1', wall, Part1)
992
+
993
+ The second joint will connect the second particle to the first particle
994
+ and the joint axis will also be about the X axis for each body.
995
+
996
+ >>> J2 = PrismaticJoint('J2', Part1, Part2)
997
+
998
+ Once the joint is established the kinematics of the connected bodies can
999
+ be accessed. First the direction cosine matrices of Part relative
1000
+ to the ceiling are found:
1001
+
1002
+ >>> Part1.frame.dcm(wall.frame)
1003
+ Matrix([
1004
+ [1, 0, 0],
1005
+ [0, 1, 0],
1006
+ [0, 0, 1]])
1007
+
1008
+ >>> Part2.frame.dcm(wall.frame)
1009
+ Matrix([
1010
+ [1, 0, 0],
1011
+ [0, 1, 0],
1012
+ [0, 0, 1]])
1013
+
1014
+ The position of the particles' masscenter is found with:
1015
+
1016
+ >>> Part1.masscenter.pos_from(wall.masscenter)
1017
+ q_J1(t)*W_frame.x
1018
+
1019
+ >>> Part2.masscenter.pos_from(wall.masscenter)
1020
+ q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x
1021
+
1022
+ The angular velocities of the two particle links can be computed with
1023
+ respect to the ceiling.
1024
+
1025
+ >>> Part1.frame.ang_vel_in(wall.frame)
1026
+ 0
1027
+
1028
+ >>> Part2.frame.ang_vel_in(wall.frame)
1029
+ 0
1030
+
1031
+ And finally, the linear velocities of the two particles can be computed
1032
+ with respect to the ceiling.
1033
+
1034
+ >>> Part1.masscenter.vel(wall.frame)
1035
+ u_J1(t)*W_frame.x
1036
+
1037
+ >>> Part2.masscenter.vel(wall.frame)
1038
+ u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x
1039
+
1040
+ """
1041
+
1042
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1043
+ parent_point=None, child_point=None, parent_interframe=None,
1044
+ child_interframe=None, parent_axis=None, child_axis=None,
1045
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
1046
+
1047
+ self._joint_axis = joint_axis
1048
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
1049
+ child_point, parent_interframe, child_interframe,
1050
+ parent_axis, child_axis, parent_joint_pos,
1051
+ child_joint_pos)
1052
+
1053
+ def __str__(self):
1054
+ return (f'PrismaticJoint: {self.name} parent: {self.parent} '
1055
+ f'child: {self.child}')
1056
+
1057
+ @property
1058
+ def joint_axis(self):
1059
+ """Axis along which the child translates with respect to the parent."""
1060
+ return self._joint_axis
1061
+
1062
+ def _generate_coordinates(self, coordinate):
1063
+ return self._fill_coordinate_list(coordinate, 1, 'q')
1064
+
1065
+ def _generate_speeds(self, speed):
1066
+ return self._fill_coordinate_list(speed, 1, 'u')
1067
+
1068
+ def _orient_frames(self):
1069
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1070
+ self.child_interframe.orient_axis(
1071
+ self.parent_interframe, self.joint_axis, 0)
1072
+
1073
+ def _set_angular_velocity(self):
1074
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
1075
+
1076
+ def _set_linear_velocity(self):
1077
+ axis = self.joint_axis.normalize()
1078
+ self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis)
1079
+ self.parent_point.set_vel(self._parent_frame, 0)
1080
+ self.child_point.set_vel(self._child_frame, 0)
1081
+ self.child_point.set_vel(self._parent_frame, self.speeds[0] * axis)
1082
+ self.child.masscenter.set_vel(self._parent_frame, self.speeds[0] * axis)
1083
+
1084
+
1085
+ class CylindricalJoint(Joint):
1086
+ """Cylindrical Joint.
1087
+
1088
+ .. image:: CylindricalJoint.svg
1089
+ :align: center
1090
+ :width: 600
1091
+
1092
+ Explanation
1093
+ ===========
1094
+
1095
+ A cylindrical joint is defined such that the child body both rotates about
1096
+ and translates along the body-fixed joint axis with respect to the parent
1097
+ body. The joint axis is both the rotation axis and translation axis. The
1098
+ location of the joint is defined by two points, one in each body, which
1099
+ coincide when the generalized coordinate corresponding to the translation is
1100
+ zero. The direction cosine matrix between the child interframe and parent
1101
+ interframe is formed using a simple rotation about the joint axis. The page
1102
+ on the joints framework gives a more detailed explanation of the
1103
+ intermediate frames.
1104
+
1105
+ Parameters
1106
+ ==========
1107
+
1108
+ name : string
1109
+ A unique name for the joint.
1110
+ parent : Particle or RigidBody
1111
+ The parent body of joint.
1112
+ child : Particle or RigidBody
1113
+ The child body of joint.
1114
+ rotation_coordinate : dynamicsymbol, optional
1115
+ Generalized coordinate corresponding to the rotation angle. The default
1116
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1117
+ translation_coordinate : dynamicsymbol, optional
1118
+ Generalized coordinate corresponding to the translation distance. The
1119
+ default value is ``dynamicsymbols(f'q1_{joint.name}')``.
1120
+ rotation_speed : dynamicsymbol, optional
1121
+ Generalized speed corresponding to the angular velocity. The default
1122
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1123
+ translation_speed : dynamicsymbol, optional
1124
+ Generalized speed corresponding to the translation velocity. The default
1125
+ value is ``dynamicsymbols(f'u1_{joint.name}')``.
1126
+ parent_point : Point or Vector, optional
1127
+ Attachment point where the joint is fixed to the parent body. If a
1128
+ vector is provided, then the attachment point is computed by adding the
1129
+ vector to the body's mass center. The default value is the parent's mass
1130
+ center.
1131
+ child_point : Point or Vector, optional
1132
+ Attachment point where the joint is fixed to the child body. If a
1133
+ vector is provided, then the attachment point is computed by adding the
1134
+ vector to the body's mass center. The default value is the child's mass
1135
+ center.
1136
+ parent_interframe : ReferenceFrame, optional
1137
+ Intermediate frame of the parent body with respect to which the joint
1138
+ transformation is formulated. If a Vector is provided then an interframe
1139
+ is created which aligns its X axis with the given vector. The default
1140
+ value is the parent's own frame.
1141
+ child_interframe : ReferenceFrame, optional
1142
+ Intermediate frame of the child body with respect to which the joint
1143
+ transformation is formulated. If a Vector is provided then an interframe
1144
+ is created which aligns its X axis with the given vector. The default
1145
+ value is the child's own frame.
1146
+ joint_axis : Vector, optional
1147
+ The rotation as well as translation axis. Note that the components of
1148
+ this axis are the same in the parent_interframe and child_interframe.
1149
+
1150
+ Attributes
1151
+ ==========
1152
+
1153
+ name : string
1154
+ The joint's name.
1155
+ parent : Particle or RigidBody
1156
+ The joint's parent body.
1157
+ child : Particle or RigidBody
1158
+ The joint's child body.
1159
+ rotation_coordinate : dynamicsymbol
1160
+ Generalized coordinate corresponding to the rotation angle.
1161
+ translation_coordinate : dynamicsymbol
1162
+ Generalized coordinate corresponding to the translation distance.
1163
+ rotation_speed : dynamicsymbol
1164
+ Generalized speed corresponding to the angular velocity.
1165
+ translation_speed : dynamicsymbol
1166
+ Generalized speed corresponding to the translation velocity.
1167
+ coordinates : Matrix
1168
+ Matrix of the joint's generalized coordinates.
1169
+ speeds : Matrix
1170
+ Matrix of the joint's generalized speeds.
1171
+ parent_point : Point
1172
+ Attachment point where the joint is fixed to the parent body.
1173
+ child_point : Point
1174
+ Attachment point where the joint is fixed to the child body.
1175
+ parent_interframe : ReferenceFrame
1176
+ Intermediate frame of the parent body with respect to which the joint
1177
+ transformation is formulated.
1178
+ child_interframe : ReferenceFrame
1179
+ Intermediate frame of the child body with respect to which the joint
1180
+ transformation is formulated.
1181
+ kdes : Matrix
1182
+ Kinematical differential equations of the joint.
1183
+ joint_axis : Vector
1184
+ The axis of rotation and translation.
1185
+
1186
+ Examples
1187
+ =========
1188
+
1189
+ A single cylindrical joint is created between two bodies and has the
1190
+ following basic attributes:
1191
+
1192
+ >>> from sympy.physics.mechanics import RigidBody, CylindricalJoint
1193
+ >>> parent = RigidBody('P')
1194
+ >>> parent
1195
+ P
1196
+ >>> child = RigidBody('C')
1197
+ >>> child
1198
+ C
1199
+ >>> joint = CylindricalJoint('PC', parent, child)
1200
+ >>> joint
1201
+ CylindricalJoint: PC parent: P child: C
1202
+ >>> joint.name
1203
+ 'PC'
1204
+ >>> joint.parent
1205
+ P
1206
+ >>> joint.child
1207
+ C
1208
+ >>> joint.parent_point
1209
+ P_masscenter
1210
+ >>> joint.child_point
1211
+ C_masscenter
1212
+ >>> joint.parent_axis
1213
+ P_frame.x
1214
+ >>> joint.child_axis
1215
+ C_frame.x
1216
+ >>> joint.coordinates
1217
+ Matrix([
1218
+ [q0_PC(t)],
1219
+ [q1_PC(t)]])
1220
+ >>> joint.speeds
1221
+ Matrix([
1222
+ [u0_PC(t)],
1223
+ [u1_PC(t)]])
1224
+ >>> child.frame.ang_vel_in(parent.frame)
1225
+ u0_PC(t)*P_frame.x
1226
+ >>> child.frame.dcm(parent.frame)
1227
+ Matrix([
1228
+ [1, 0, 0],
1229
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1230
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1231
+ >>> joint.child_point.pos_from(joint.parent_point)
1232
+ q1_PC(t)*P_frame.x
1233
+ >>> child.masscenter.vel(parent.frame)
1234
+ u1_PC(t)*P_frame.x
1235
+
1236
+ To further demonstrate the use of the cylindrical joint, the kinematics of
1237
+ two cylindrical joints perpendicular to each other can be created as follows.
1238
+
1239
+ >>> from sympy import symbols
1240
+ >>> from sympy.physics.mechanics import RigidBody, CylindricalJoint
1241
+ >>> r, l, w = symbols('r l w')
1242
+
1243
+ First create bodies to represent the fixed floor with a fixed pole on it.
1244
+ The second body represents a freely moving tube around that pole. The third
1245
+ body represents a solid flag freely translating along and rotating around
1246
+ the Y axis of the tube.
1247
+
1248
+ >>> floor = RigidBody('floor')
1249
+ >>> tube = RigidBody('tube')
1250
+ >>> flag = RigidBody('flag')
1251
+
1252
+ The first joint will connect the first tube to the floor with it translating
1253
+ along and rotating around the Z axis of both bodies.
1254
+
1255
+ >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z)
1256
+
1257
+ The second joint will connect the tube perpendicular to the flag along the Y
1258
+ axis of both the tube and the flag, with the joint located at a distance
1259
+ ``r`` from the tube's center of mass and a combination of the distances
1260
+ ``l`` and ``w`` from the flag's center of mass.
1261
+
1262
+ >>> flag_joint = CylindricalJoint('C2', tube, flag,
1263
+ ... parent_point=r * tube.y,
1264
+ ... child_point=-w * flag.y + l * flag.z,
1265
+ ... joint_axis=tube.y)
1266
+
1267
+ Once the joints are established the kinematics of the connected bodies can
1268
+ be accessed. First the direction cosine matrices of both the body and the
1269
+ flag relative to the floor are found:
1270
+
1271
+ >>> tube.frame.dcm(floor.frame)
1272
+ Matrix([
1273
+ [ cos(q0_C1(t)), sin(q0_C1(t)), 0],
1274
+ [-sin(q0_C1(t)), cos(q0_C1(t)), 0],
1275
+ [ 0, 0, 1]])
1276
+ >>> flag.frame.dcm(floor.frame)
1277
+ Matrix([
1278
+ [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))],
1279
+ [ -sin(q0_C1(t)), cos(q0_C1(t)), 0],
1280
+ [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]])
1281
+
1282
+ The position of the flag's center of mass is found with:
1283
+
1284
+ >>> flag.masscenter.pos_from(floor.masscenter)
1285
+ q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z
1286
+
1287
+ The angular velocities of the two tubes can be computed with respect to the
1288
+ floor.
1289
+
1290
+ >>> tube.frame.ang_vel_in(floor.frame)
1291
+ u0_C1(t)*floor_frame.z
1292
+ >>> flag.frame.ang_vel_in(floor.frame)
1293
+ u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y
1294
+
1295
+ Finally, the linear velocities of the two tube centers of mass can be
1296
+ computed with respect to the floor, while expressed in the tube's frame.
1297
+
1298
+ >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame)
1299
+ Matrix([
1300
+ [ 0],
1301
+ [ 0],
1302
+ [u1_C1(t)]])
1303
+ >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify()
1304
+ Matrix([
1305
+ [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)],
1306
+ [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)],
1307
+ [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]])
1308
+
1309
+ """
1310
+
1311
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1312
+ translation_coordinate=None, rotation_speed=None,
1313
+ translation_speed=None, parent_point=None, child_point=None,
1314
+ parent_interframe=None, child_interframe=None,
1315
+ joint_axis=None):
1316
+ self._joint_axis = joint_axis
1317
+ coordinates = (rotation_coordinate, translation_coordinate)
1318
+ speeds = (rotation_speed, translation_speed)
1319
+ super().__init__(name, parent, child, coordinates, speeds,
1320
+ parent_point, child_point,
1321
+ parent_interframe=parent_interframe,
1322
+ child_interframe=child_interframe)
1323
+
1324
+ def __str__(self):
1325
+ return (f'CylindricalJoint: {self.name} parent: {self.parent} '
1326
+ f'child: {self.child}')
1327
+
1328
+ @property
1329
+ def joint_axis(self):
1330
+ """Axis about and along which the rotation and translation occurs."""
1331
+ return self._joint_axis
1332
+
1333
+ @property
1334
+ def rotation_coordinate(self):
1335
+ """Generalized coordinate corresponding to the rotation angle."""
1336
+ return self.coordinates[0]
1337
+
1338
+ @property
1339
+ def translation_coordinate(self):
1340
+ """Generalized coordinate corresponding to the translation distance."""
1341
+ return self.coordinates[1]
1342
+
1343
+ @property
1344
+ def rotation_speed(self):
1345
+ """Generalized speed corresponding to the angular velocity."""
1346
+ return self.speeds[0]
1347
+
1348
+ @property
1349
+ def translation_speed(self):
1350
+ """Generalized speed corresponding to the translation velocity."""
1351
+ return self.speeds[1]
1352
+
1353
+ def _generate_coordinates(self, coordinates):
1354
+ return self._fill_coordinate_list(coordinates, 2, 'q')
1355
+
1356
+ def _generate_speeds(self, speeds):
1357
+ return self._fill_coordinate_list(speeds, 2, 'u')
1358
+
1359
+ def _orient_frames(self):
1360
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1361
+ self.child_interframe.orient_axis(
1362
+ self.parent_interframe, self.joint_axis, self.rotation_coordinate)
1363
+
1364
+ def _set_angular_velocity(self):
1365
+ self.child_interframe.set_ang_vel(
1366
+ self.parent_interframe,
1367
+ self.rotation_speed * self.joint_axis.normalize())
1368
+
1369
+ def _set_linear_velocity(self):
1370
+ self.child_point.set_pos(
1371
+ self.parent_point,
1372
+ self.translation_coordinate * self.joint_axis.normalize())
1373
+ self.parent_point.set_vel(self._parent_frame, 0)
1374
+ self.child_point.set_vel(self._child_frame, 0)
1375
+ self.child_point.set_vel(
1376
+ self._parent_frame,
1377
+ self.translation_speed * self.joint_axis.normalize())
1378
+ self.child.masscenter.v2pt_theory(self.child_point, self._parent_frame,
1379
+ self.child_interframe)
1380
+
1381
+
1382
+ class PlanarJoint(Joint):
1383
+ """Planar Joint.
1384
+
1385
+ .. raw:: html
1386
+ :file: ../../../doc/src/modules/physics/mechanics/api/PlanarJoint.svg
1387
+
1388
+ Explanation
1389
+ ===========
1390
+
1391
+ A planar joint is defined such that the child body translates over a fixed
1392
+ plane of the parent body as well as rotate about the rotation axis, which
1393
+ is perpendicular to that plane. The origin of this plane is the
1394
+ ``parent_point`` and the plane is spanned by two nonparallel planar vectors.
1395
+ The location of the ``child_point`` is based on the planar vectors
1396
+ ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$),
1397
+ i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine
1398
+ matrix between the ``child_interframe`` and ``parent_interframe`` is formed
1399
+ using a simple rotation ($q_0$) about the rotation axis.
1400
+
1401
+ In order to simplify the definition of the ``PlanarJoint``, the
1402
+ ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of
1403
+ the ``parent_interframe`` according to the table below. This ensures that
1404
+ you can only define these vectors by creating a separate frame and supplying
1405
+ that as the interframe. If you however would only like to supply the normals
1406
+ of the plane with respect to the parent and child bodies, then you can also
1407
+ supply those to the ``parent_interframe`` and ``child_interframe``
1408
+ arguments. An example of both of these cases is in the examples section
1409
+ below and the page on the joints framework provides a more detailed
1410
+ explanation of the intermediate frames.
1411
+
1412
+ .. list-table::
1413
+
1414
+ * - ``rotation_axis``
1415
+ - ``parent_interframe.x``
1416
+ * - ``planar_vectors[0]``
1417
+ - ``parent_interframe.y``
1418
+ * - ``planar_vectors[1]``
1419
+ - ``parent_interframe.z``
1420
+
1421
+ Parameters
1422
+ ==========
1423
+
1424
+ name : string
1425
+ A unique name for the joint.
1426
+ parent : Particle or RigidBody
1427
+ The parent body of joint.
1428
+ child : Particle or RigidBody
1429
+ The child body of joint.
1430
+ rotation_coordinate : dynamicsymbol, optional
1431
+ Generalized coordinate corresponding to the rotation angle. The default
1432
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1433
+ planar_coordinates : iterable of dynamicsymbols, optional
1434
+ Two generalized coordinates used for the planar translation. The default
1435
+ value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``.
1436
+ rotation_speed : dynamicsymbol, optional
1437
+ Generalized speed corresponding to the angular velocity. The default
1438
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1439
+ planar_speeds : dynamicsymbols, optional
1440
+ Two generalized speeds used for the planar translation velocity. The
1441
+ default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``.
1442
+ parent_point : Point or Vector, optional
1443
+ Attachment point where the joint is fixed to the parent body. If a
1444
+ vector is provided, then the attachment point is computed by adding the
1445
+ vector to the body's mass center. The default value is the parent's mass
1446
+ center.
1447
+ child_point : Point or Vector, optional
1448
+ Attachment point where the joint is fixed to the child body. If a
1449
+ vector is provided, then the attachment point is computed by adding the
1450
+ vector to the body's mass center. The default value is the child's mass
1451
+ center.
1452
+ parent_interframe : ReferenceFrame, optional
1453
+ Intermediate frame of the parent body with respect to which the joint
1454
+ transformation is formulated. If a Vector is provided then an interframe
1455
+ is created which aligns its X axis with the given vector. The default
1456
+ value is the parent's own frame.
1457
+ child_interframe : ReferenceFrame, optional
1458
+ Intermediate frame of the child body with respect to which the joint
1459
+ transformation is formulated. If a Vector is provided then an interframe
1460
+ is created which aligns its X axis with the given vector. The default
1461
+ value is the child's own frame.
1462
+
1463
+ Attributes
1464
+ ==========
1465
+
1466
+ name : string
1467
+ The joint's name.
1468
+ parent : Particle or RigidBody
1469
+ The joint's parent body.
1470
+ child : Particle or RigidBody
1471
+ The joint's child body.
1472
+ rotation_coordinate : dynamicsymbol
1473
+ Generalized coordinate corresponding to the rotation angle.
1474
+ planar_coordinates : Matrix
1475
+ Two generalized coordinates used for the planar translation.
1476
+ rotation_speed : dynamicsymbol
1477
+ Generalized speed corresponding to the angular velocity.
1478
+ planar_speeds : Matrix
1479
+ Two generalized speeds used for the planar translation velocity.
1480
+ coordinates : Matrix
1481
+ Matrix of the joint's generalized coordinates.
1482
+ speeds : Matrix
1483
+ Matrix of the joint's generalized speeds.
1484
+ parent_point : Point
1485
+ Attachment point where the joint is fixed to the parent body.
1486
+ child_point : Point
1487
+ Attachment point where the joint is fixed to the child body.
1488
+ parent_interframe : ReferenceFrame
1489
+ Intermediate frame of the parent body with respect to which the joint
1490
+ transformation is formulated.
1491
+ child_interframe : ReferenceFrame
1492
+ Intermediate frame of the child body with respect to which the joint
1493
+ transformation is formulated.
1494
+ kdes : Matrix
1495
+ Kinematical differential equations of the joint.
1496
+ rotation_axis : Vector
1497
+ The axis about which the rotation occurs.
1498
+ planar_vectors : list
1499
+ The vectors that describe the planar translation directions.
1500
+
1501
+ Examples
1502
+ =========
1503
+
1504
+ A single planar joint is created between two bodies and has the following
1505
+ basic attributes:
1506
+
1507
+ >>> from sympy.physics.mechanics import RigidBody, PlanarJoint
1508
+ >>> parent = RigidBody('P')
1509
+ >>> parent
1510
+ P
1511
+ >>> child = RigidBody('C')
1512
+ >>> child
1513
+ C
1514
+ >>> joint = PlanarJoint('PC', parent, child)
1515
+ >>> joint
1516
+ PlanarJoint: PC parent: P child: C
1517
+ >>> joint.name
1518
+ 'PC'
1519
+ >>> joint.parent
1520
+ P
1521
+ >>> joint.child
1522
+ C
1523
+ >>> joint.parent_point
1524
+ P_masscenter
1525
+ >>> joint.child_point
1526
+ C_masscenter
1527
+ >>> joint.rotation_axis
1528
+ P_frame.x
1529
+ >>> joint.planar_vectors
1530
+ [P_frame.y, P_frame.z]
1531
+ >>> joint.rotation_coordinate
1532
+ q0_PC(t)
1533
+ >>> joint.planar_coordinates
1534
+ Matrix([
1535
+ [q1_PC(t)],
1536
+ [q2_PC(t)]])
1537
+ >>> joint.coordinates
1538
+ Matrix([
1539
+ [q0_PC(t)],
1540
+ [q1_PC(t)],
1541
+ [q2_PC(t)]])
1542
+ >>> joint.rotation_speed
1543
+ u0_PC(t)
1544
+ >>> joint.planar_speeds
1545
+ Matrix([
1546
+ [u1_PC(t)],
1547
+ [u2_PC(t)]])
1548
+ >>> joint.speeds
1549
+ Matrix([
1550
+ [u0_PC(t)],
1551
+ [u1_PC(t)],
1552
+ [u2_PC(t)]])
1553
+ >>> child.frame.ang_vel_in(parent.frame)
1554
+ u0_PC(t)*P_frame.x
1555
+ >>> child.frame.dcm(parent.frame)
1556
+ Matrix([
1557
+ [1, 0, 0],
1558
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1559
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1560
+ >>> joint.child_point.pos_from(joint.parent_point)
1561
+ q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z
1562
+ >>> child.masscenter.vel(parent.frame)
1563
+ u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z
1564
+
1565
+ To further demonstrate the use of the planar joint, the kinematics of a
1566
+ block sliding on a slope, can be created as follows.
1567
+
1568
+ >>> from sympy import symbols
1569
+ >>> from sympy.physics.mechanics import PlanarJoint, RigidBody, ReferenceFrame
1570
+ >>> a, d, h = symbols('a d h')
1571
+
1572
+ First create bodies to represent the slope and the block.
1573
+
1574
+ >>> ground = RigidBody('G')
1575
+ >>> block = RigidBody('B')
1576
+
1577
+ To define the slope you can either define the plane by specifying the
1578
+ ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to
1579
+ create a rotated intermediate frame, so that the ``parent_vectors`` and
1580
+ ``rotation_axis`` will be the unit vectors of this intermediate frame.
1581
+
1582
+ >>> slope = ReferenceFrame('A')
1583
+ >>> slope.orient_axis(ground.frame, ground.y, a)
1584
+
1585
+ The planar joint can be created using these bodies and intermediate frame.
1586
+ We can specify the origin of the slope to be ``d`` above the slope's center
1587
+ of mass and the block's center of mass to be a distance ``h`` above the
1588
+ slope's surface. Note that we can specify the normal of the plane using the
1589
+ rotation axis argument.
1590
+
1591
+ >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x,
1592
+ ... child_point=-h * block.x, parent_interframe=slope)
1593
+
1594
+ Once the joint is established the kinematics of the bodies can be accessed.
1595
+ First the ``rotation_axis``, which is normal to the plane and the
1596
+ ``plane_vectors``, can be found.
1597
+
1598
+ >>> joint.rotation_axis
1599
+ A.x
1600
+ >>> joint.planar_vectors
1601
+ [A.y, A.z]
1602
+
1603
+ The direction cosine matrix of the block with respect to the ground can be
1604
+ found with:
1605
+
1606
+ >>> block.frame.dcm(ground.frame)
1607
+ Matrix([
1608
+ [ cos(a), 0, -sin(a)],
1609
+ [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1610
+ [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1611
+
1612
+ The angular velocity of the block can be computed with respect to the
1613
+ ground.
1614
+
1615
+ >>> block.frame.ang_vel_in(ground.frame)
1616
+ u0_PC(t)*A.x
1617
+
1618
+ The position of the block's center of mass can be found with:
1619
+
1620
+ >>> block.masscenter.pos_from(ground.masscenter)
1621
+ d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z
1622
+
1623
+ Finally, the linear velocity of the block's center of mass can be
1624
+ computed with respect to the ground.
1625
+
1626
+ >>> block.masscenter.vel(ground.frame)
1627
+ u1_PC(t)*A.y + u2_PC(t)*A.z
1628
+
1629
+ In some cases it could be your preference to only define the normals of the
1630
+ plane with respect to both bodies. This can most easily be done by supplying
1631
+ vectors to the ``interframe`` arguments. What will happen in this case is
1632
+ that an interframe will be created with its ``x`` axis aligned with the
1633
+ provided vector. For a further explanation of how this is done see the notes
1634
+ of the ``Joint`` class. In the code below, the above example (with the block
1635
+ on the slope) is recreated by supplying vectors to the interframe arguments.
1636
+ Note that the previously described option is however more computationally
1637
+ efficient, because the algorithm now has to compute the rotation angle
1638
+ between the provided vector and the 'x' axis.
1639
+
1640
+ >>> from sympy import symbols, cos, sin
1641
+ >>> from sympy.physics.mechanics import PlanarJoint, RigidBody
1642
+ >>> a, d, h = symbols('a d h')
1643
+ >>> ground = RigidBody('G')
1644
+ >>> block = RigidBody('B')
1645
+ >>> joint = PlanarJoint(
1646
+ ... 'PC', ground, block, parent_point=d * ground.x,
1647
+ ... child_point=-h * block.x, child_interframe=block.x,
1648
+ ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z)
1649
+ >>> block.frame.dcm(ground.frame).simplify()
1650
+ Matrix([
1651
+ [ cos(a), 0, sin(a)],
1652
+ [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1653
+ [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1654
+
1655
+ """
1656
+
1657
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1658
+ planar_coordinates=None, rotation_speed=None,
1659
+ planar_speeds=None, parent_point=None, child_point=None,
1660
+ parent_interframe=None, child_interframe=None):
1661
+ # A ready to merge implementation of setting the planar_vectors and
1662
+ # rotation_axis was added and removed in PR #24046
1663
+ coordinates = (rotation_coordinate, planar_coordinates)
1664
+ speeds = (rotation_speed, planar_speeds)
1665
+ super().__init__(name, parent, child, coordinates, speeds,
1666
+ parent_point, child_point,
1667
+ parent_interframe=parent_interframe,
1668
+ child_interframe=child_interframe)
1669
+
1670
+ def __str__(self):
1671
+ return (f'PlanarJoint: {self.name} parent: {self.parent} '
1672
+ f'child: {self.child}')
1673
+
1674
+ @property
1675
+ def rotation_coordinate(self):
1676
+ """Generalized coordinate corresponding to the rotation angle."""
1677
+ return self.coordinates[0]
1678
+
1679
+ @property
1680
+ def planar_coordinates(self):
1681
+ """Two generalized coordinates used for the planar translation."""
1682
+ return self.coordinates[1:, 0]
1683
+
1684
+ @property
1685
+ def rotation_speed(self):
1686
+ """Generalized speed corresponding to the angular velocity."""
1687
+ return self.speeds[0]
1688
+
1689
+ @property
1690
+ def planar_speeds(self):
1691
+ """Two generalized speeds used for the planar translation velocity."""
1692
+ return self.speeds[1:, 0]
1693
+
1694
+ @property
1695
+ def rotation_axis(self):
1696
+ """The axis about which the rotation occurs."""
1697
+ return self.parent_interframe.x
1698
+
1699
+ @property
1700
+ def planar_vectors(self):
1701
+ """The vectors that describe the planar translation directions."""
1702
+ return [self.parent_interframe.y, self.parent_interframe.z]
1703
+
1704
+ def _generate_coordinates(self, coordinates):
1705
+ rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q',
1706
+ number_single=True)
1707
+ planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1)
1708
+ return rotation_speed.col_join(planar_speeds)
1709
+
1710
+ def _generate_speeds(self, speeds):
1711
+ rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u',
1712
+ number_single=True)
1713
+ planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1)
1714
+ return rotation_speed.col_join(planar_speeds)
1715
+
1716
+ def _orient_frames(self):
1717
+ self.child_interframe.orient_axis(
1718
+ self.parent_interframe, self.rotation_axis,
1719
+ self.rotation_coordinate)
1720
+
1721
+ def _set_angular_velocity(self):
1722
+ self.child_interframe.set_ang_vel(
1723
+ self.parent_interframe,
1724
+ self.rotation_speed * self.rotation_axis)
1725
+
1726
+ def _set_linear_velocity(self):
1727
+ self.child_point.set_pos(
1728
+ self.parent_point,
1729
+ self.planar_coordinates[0] * self.planar_vectors[0] +
1730
+ self.planar_coordinates[1] * self.planar_vectors[1])
1731
+ self.parent_point.set_vel(self.parent_interframe, 0)
1732
+ self.child_point.set_vel(self.child_interframe, 0)
1733
+ self.child_point.set_vel(
1734
+ self._parent_frame, self.planar_speeds[0] * self.planar_vectors[0] +
1735
+ self.planar_speeds[1] * self.planar_vectors[1])
1736
+ self.child.masscenter.v2pt_theory(self.child_point, self._parent_frame,
1737
+ self._child_frame)
1738
+
1739
+
1740
+ class SphericalJoint(Joint):
1741
+ """Spherical (Ball-and-Socket) Joint.
1742
+
1743
+ .. image:: SphericalJoint.svg
1744
+ :align: center
1745
+ :width: 600
1746
+
1747
+ Explanation
1748
+ ===========
1749
+
1750
+ A spherical joint is defined such that the child body is free to rotate in
1751
+ any direction, without allowing a translation of the ``child_point``. As can
1752
+ also be seen in the image, the ``parent_point`` and ``child_point`` are
1753
+ fixed on top of each other, i.e. the ``joint_point``. This rotation is
1754
+ defined using the :func:`parent_interframe.orient(child_interframe,
1755
+ rot_type, amounts, rot_order)
1756
+ <sympy.physics.vector.frame.ReferenceFrame.orient>` method. The default
1757
+ rotation consists of three relative rotations, i.e. body-fixed rotations.
1758
+ Based on the direction cosine matrix following from these rotations, the
1759
+ angular velocity is computed based on the generalized coordinates and
1760
+ generalized speeds.
1761
+
1762
+ Parameters
1763
+ ==========
1764
+
1765
+ name : string
1766
+ A unique name for the joint.
1767
+ parent : Particle or RigidBody
1768
+ The parent body of joint.
1769
+ child : Particle or RigidBody
1770
+ The child body of joint.
1771
+ coordinates: iterable of dynamicsymbols, optional
1772
+ Generalized coordinates of the joint.
1773
+ speeds : iterable of dynamicsymbols, optional
1774
+ Generalized speeds of joint.
1775
+ parent_point : Point or Vector, optional
1776
+ Attachment point where the joint is fixed to the parent body. If a
1777
+ vector is provided, then the attachment point is computed by adding the
1778
+ vector to the body's mass center. The default value is the parent's mass
1779
+ center.
1780
+ child_point : Point or Vector, optional
1781
+ Attachment point where the joint is fixed to the child body. If a
1782
+ vector is provided, then the attachment point is computed by adding the
1783
+ vector to the body's mass center. The default value is the child's mass
1784
+ center.
1785
+ parent_interframe : ReferenceFrame, optional
1786
+ Intermediate frame of the parent body with respect to which the joint
1787
+ transformation is formulated. If a Vector is provided then an interframe
1788
+ is created which aligns its X axis with the given vector. The default
1789
+ value is the parent's own frame.
1790
+ child_interframe : ReferenceFrame, optional
1791
+ Intermediate frame of the child body with respect to which the joint
1792
+ transformation is formulated. If a Vector is provided then an interframe
1793
+ is created which aligns its X axis with the given vector. The default
1794
+ value is the child's own frame.
1795
+ rot_type : str, optional
1796
+ The method used to generate the direction cosine matrix. Supported
1797
+ methods are:
1798
+
1799
+ - ``'Body'``: three successive rotations about new intermediate axes,
1800
+ also called "Euler and Tait-Bryan angles"
1801
+ - ``'Space'``: three successive rotations about the parent frames' unit
1802
+ vectors
1803
+
1804
+ The default method is ``'Body'``.
1805
+ amounts :
1806
+ Expressions defining the rotation angles or direction cosine matrix.
1807
+ These must match the ``rot_type``. See examples below for details. The
1808
+ input types are:
1809
+
1810
+ - ``'Body'``: 3-tuple of expressions, symbols, or functions
1811
+ - ``'Space'``: 3-tuple of expressions, symbols, or functions
1812
+
1813
+ The default amounts are the given ``coordinates``.
1814
+ rot_order : str or int, optional
1815
+ If applicable, the order of the successive of rotations. The string
1816
+ ``'123'`` and integer ``123`` are equivalent, for example. Required for
1817
+ ``'Body'`` and ``'Space'``. The default value is ``123``.
1818
+
1819
+ Attributes
1820
+ ==========
1821
+
1822
+ name : string
1823
+ The joint's name.
1824
+ parent : Particle or RigidBody
1825
+ The joint's parent body.
1826
+ child : Particle or RigidBody
1827
+ The joint's child body.
1828
+ coordinates : Matrix
1829
+ Matrix of the joint's generalized coordinates.
1830
+ speeds : Matrix
1831
+ Matrix of the joint's generalized speeds.
1832
+ parent_point : Point
1833
+ Attachment point where the joint is fixed to the parent body.
1834
+ child_point : Point
1835
+ Attachment point where the joint is fixed to the child body.
1836
+ parent_interframe : ReferenceFrame
1837
+ Intermediate frame of the parent body with respect to which the joint
1838
+ transformation is formulated.
1839
+ child_interframe : ReferenceFrame
1840
+ Intermediate frame of the child body with respect to which the joint
1841
+ transformation is formulated.
1842
+ kdes : Matrix
1843
+ Kinematical differential equations of the joint.
1844
+
1845
+ Examples
1846
+ =========
1847
+
1848
+ A single spherical joint is created from two bodies and has the following
1849
+ basic attributes:
1850
+
1851
+ >>> from sympy.physics.mechanics import RigidBody, SphericalJoint
1852
+ >>> parent = RigidBody('P')
1853
+ >>> parent
1854
+ P
1855
+ >>> child = RigidBody('C')
1856
+ >>> child
1857
+ C
1858
+ >>> joint = SphericalJoint('PC', parent, child)
1859
+ >>> joint
1860
+ SphericalJoint: PC parent: P child: C
1861
+ >>> joint.name
1862
+ 'PC'
1863
+ >>> joint.parent
1864
+ P
1865
+ >>> joint.child
1866
+ C
1867
+ >>> joint.parent_point
1868
+ P_masscenter
1869
+ >>> joint.child_point
1870
+ C_masscenter
1871
+ >>> joint.parent_interframe
1872
+ P_frame
1873
+ >>> joint.child_interframe
1874
+ C_frame
1875
+ >>> joint.coordinates
1876
+ Matrix([
1877
+ [q0_PC(t)],
1878
+ [q1_PC(t)],
1879
+ [q2_PC(t)]])
1880
+ >>> joint.speeds
1881
+ Matrix([
1882
+ [u0_PC(t)],
1883
+ [u1_PC(t)],
1884
+ [u2_PC(t)]])
1885
+ >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame)
1886
+ Matrix([
1887
+ [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))],
1888
+ [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))],
1889
+ [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]])
1890
+ >>> child.frame.x.to_matrix(parent.frame)
1891
+ Matrix([
1892
+ [ cos(q1_PC(t))*cos(q2_PC(t))],
1893
+ [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))],
1894
+ [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]])
1895
+ >>> joint.child_point.pos_from(joint.parent_point)
1896
+ 0
1897
+
1898
+ To further demonstrate the use of the spherical joint, the kinematics of a
1899
+ spherical joint with a ZXZ rotation can be created as follows.
1900
+
1901
+ >>> from sympy import symbols
1902
+ >>> from sympy.physics.mechanics import RigidBody, SphericalJoint
1903
+ >>> l1 = symbols('l1')
1904
+
1905
+ First create bodies to represent the fixed floor and a pendulum bob.
1906
+
1907
+ >>> floor = RigidBody('F')
1908
+ >>> bob = RigidBody('B')
1909
+
1910
+ The joint will connect the bob to the floor, with the joint located at a
1911
+ distance of ``l1`` from the child's center of mass and the rotation set to a
1912
+ body-fixed ZXZ rotation.
1913
+
1914
+ >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y,
1915
+ ... rot_type='body', rot_order='ZXZ')
1916
+
1917
+ Now that the joint is established, the kinematics of the connected body can
1918
+ be accessed.
1919
+
1920
+ The position of the bob's masscenter is found with:
1921
+
1922
+ >>> bob.masscenter.pos_from(floor.masscenter)
1923
+ - l1*B_frame.y
1924
+
1925
+ The angular velocities of the pendulum link can be computed with respect to
1926
+ the floor.
1927
+
1928
+ >>> bob.frame.ang_vel_in(floor.frame).to_matrix(
1929
+ ... floor.frame).simplify()
1930
+ Matrix([
1931
+ [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))],
1932
+ [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))],
1933
+ [ u0_S(t) + u2_S(t)*cos(q1_S(t))]])
1934
+
1935
+ Finally, the linear velocity of the bob's center of mass can be computed.
1936
+
1937
+ >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame)
1938
+ Matrix([
1939
+ [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))],
1940
+ [ 0],
1941
+ [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]])
1942
+
1943
+ """
1944
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1945
+ parent_point=None, child_point=None, parent_interframe=None,
1946
+ child_interframe=None, rot_type='BODY', amounts=None,
1947
+ rot_order=123):
1948
+ self._rot_type = rot_type
1949
+ self._amounts = amounts
1950
+ self._rot_order = rot_order
1951
+ super().__init__(name, parent, child, coordinates, speeds,
1952
+ parent_point, child_point,
1953
+ parent_interframe=parent_interframe,
1954
+ child_interframe=child_interframe)
1955
+
1956
+ def __str__(self):
1957
+ return (f'SphericalJoint: {self.name} parent: {self.parent} '
1958
+ f'child: {self.child}')
1959
+
1960
+ def _generate_coordinates(self, coordinates):
1961
+ return self._fill_coordinate_list(coordinates, 3, 'q')
1962
+
1963
+ def _generate_speeds(self, speeds):
1964
+ return self._fill_coordinate_list(speeds, len(self.coordinates), 'u')
1965
+
1966
+ def _orient_frames(self):
1967
+ supported_rot_types = ('BODY', 'SPACE')
1968
+ if self._rot_type.upper() not in supported_rot_types:
1969
+ raise NotImplementedError(
1970
+ f'Rotation type "{self._rot_type}" is not implemented. '
1971
+ f'Implemented rotation types are: {supported_rot_types}')
1972
+ amounts = self.coordinates if self._amounts is None else self._amounts
1973
+ self.child_interframe.orient(self.parent_interframe, self._rot_type,
1974
+ amounts, self._rot_order)
1975
+
1976
+ def _set_angular_velocity(self):
1977
+ t = dynamicsymbols._t
1978
+ vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace(
1979
+ {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)}
1980
+ )
1981
+ self.child_interframe.set_ang_vel(self.parent_interframe, vel)
1982
+
1983
+ def _set_linear_velocity(self):
1984
+ self.child_point.set_pos(self.parent_point, 0)
1985
+ self.parent_point.set_vel(self._parent_frame, 0)
1986
+ self.child_point.set_vel(self._child_frame, 0)
1987
+ self.child.masscenter.v2pt_theory(self.parent_point, self._parent_frame,
1988
+ self._child_frame)
1989
+
1990
+
1991
+ class WeldJoint(Joint):
1992
+ """Weld Joint.
1993
+
1994
+ .. raw:: html
1995
+ :file: ../../../doc/src/modules/physics/mechanics/api/WeldJoint.svg
1996
+
1997
+ Explanation
1998
+ ===========
1999
+
2000
+ A weld joint is defined such that there is no relative motion between the
2001
+ child and parent bodies. The direction cosine matrix between the attachment
2002
+ frame (``parent_interframe`` and ``child_interframe``) is the identity
2003
+ matrix and the attachment points (``parent_point`` and ``child_point``) are
2004
+ coincident. The page on the joints framework gives a more detailed
2005
+ explanation of the intermediate frames.
2006
+
2007
+ Parameters
2008
+ ==========
2009
+
2010
+ name : string
2011
+ A unique name for the joint.
2012
+ parent : Particle or RigidBody
2013
+ The parent body of joint.
2014
+ child : Particle or RigidBody
2015
+ The child body of joint.
2016
+ parent_point : Point or Vector, optional
2017
+ Attachment point where the joint is fixed to the parent body. If a
2018
+ vector is provided, then the attachment point is computed by adding the
2019
+ vector to the body's mass center. The default value is the parent's mass
2020
+ center.
2021
+ child_point : Point or Vector, optional
2022
+ Attachment point where the joint is fixed to the child body. If a
2023
+ vector is provided, then the attachment point is computed by adding the
2024
+ vector to the body's mass center. The default value is the child's mass
2025
+ center.
2026
+ parent_interframe : ReferenceFrame, optional
2027
+ Intermediate frame of the parent body with respect to which the joint
2028
+ transformation is formulated. If a Vector is provided then an interframe
2029
+ is created which aligns its X axis with the given vector. The default
2030
+ value is the parent's own frame.
2031
+ child_interframe : ReferenceFrame, optional
2032
+ Intermediate frame of the child body with respect to which the joint
2033
+ transformation is formulated. If a Vector is provided then an interframe
2034
+ is created which aligns its X axis with the given vector. The default
2035
+ value is the child's own frame.
2036
+
2037
+ Attributes
2038
+ ==========
2039
+
2040
+ name : string
2041
+ The joint's name.
2042
+ parent : Particle or RigidBody
2043
+ The joint's parent body.
2044
+ child : Particle or RigidBody
2045
+ The joint's child body.
2046
+ coordinates : Matrix
2047
+ Matrix of the joint's generalized coordinates. The default value is
2048
+ ``dynamicsymbols(f'q_{joint.name}')``.
2049
+ speeds : Matrix
2050
+ Matrix of the joint's generalized speeds. The default value is
2051
+ ``dynamicsymbols(f'u_{joint.name}')``.
2052
+ parent_point : Point
2053
+ Attachment point where the joint is fixed to the parent body.
2054
+ child_point : Point
2055
+ Attachment point where the joint is fixed to the child body.
2056
+ parent_interframe : ReferenceFrame
2057
+ Intermediate frame of the parent body with respect to which the joint
2058
+ transformation is formulated.
2059
+ child_interframe : ReferenceFrame
2060
+ Intermediate frame of the child body with respect to which the joint
2061
+ transformation is formulated.
2062
+ kdes : Matrix
2063
+ Kinematical differential equations of the joint.
2064
+
2065
+ Examples
2066
+ =========
2067
+
2068
+ A single weld joint is created from two bodies and has the following basic
2069
+ attributes:
2070
+
2071
+ >>> from sympy.physics.mechanics import RigidBody, WeldJoint
2072
+ >>> parent = RigidBody('P')
2073
+ >>> parent
2074
+ P
2075
+ >>> child = RigidBody('C')
2076
+ >>> child
2077
+ C
2078
+ >>> joint = WeldJoint('PC', parent, child)
2079
+ >>> joint
2080
+ WeldJoint: PC parent: P child: C
2081
+ >>> joint.name
2082
+ 'PC'
2083
+ >>> joint.parent
2084
+ P
2085
+ >>> joint.child
2086
+ C
2087
+ >>> joint.parent_point
2088
+ P_masscenter
2089
+ >>> joint.child_point
2090
+ C_masscenter
2091
+ >>> joint.coordinates
2092
+ Matrix(0, 0, [])
2093
+ >>> joint.speeds
2094
+ Matrix(0, 0, [])
2095
+ >>> child.frame.ang_vel_in(parent.frame)
2096
+ 0
2097
+ >>> child.frame.dcm(parent.frame)
2098
+ Matrix([
2099
+ [1, 0, 0],
2100
+ [0, 1, 0],
2101
+ [0, 0, 1]])
2102
+ >>> joint.child_point.pos_from(joint.parent_point)
2103
+ 0
2104
+
2105
+ To further demonstrate the use of the weld joint, two relatively-fixed
2106
+ bodies rotated by a quarter turn about the Y axis can be created as follows:
2107
+
2108
+ >>> from sympy import symbols, pi
2109
+ >>> from sympy.physics.mechanics import ReferenceFrame, RigidBody, WeldJoint
2110
+ >>> l1, l2 = symbols('l1 l2')
2111
+
2112
+ First create the bodies to represent the parent and rotated child body.
2113
+
2114
+ >>> parent = RigidBody('P')
2115
+ >>> child = RigidBody('C')
2116
+
2117
+ Next the intermediate frame specifying the fixed rotation with respect to
2118
+ the parent can be created.
2119
+
2120
+ >>> rotated_frame = ReferenceFrame('Pr')
2121
+ >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2)
2122
+
2123
+ The weld between the parent body and child body is located at a distance
2124
+ ``l1`` from the parent's center of mass in the X direction and ``l2`` from
2125
+ the child's center of mass in the child's negative X direction.
2126
+
2127
+ >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x,
2128
+ ... child_point=-l2 * child.x,
2129
+ ... parent_interframe=rotated_frame)
2130
+
2131
+ Now that the joint has been established, the kinematics of the bodies can be
2132
+ accessed. The direction cosine matrix of the child body with respect to the
2133
+ parent can be found:
2134
+
2135
+ >>> child.frame.dcm(parent.frame)
2136
+ Matrix([
2137
+ [0, 0, -1],
2138
+ [0, 1, 0],
2139
+ [1, 0, 0]])
2140
+
2141
+ As can also been seen from the direction cosine matrix, the parent X axis is
2142
+ aligned with the child's Z axis:
2143
+ >>> parent.x == child.z
2144
+ True
2145
+
2146
+ The position of the child's center of mass with respect to the parent's
2147
+ center of mass can be found with:
2148
+
2149
+ >>> child.masscenter.pos_from(parent.masscenter)
2150
+ l1*P_frame.x + l2*C_frame.x
2151
+
2152
+ The angular velocity of the child with respect to the parent is 0 as one
2153
+ would expect.
2154
+
2155
+ >>> child.frame.ang_vel_in(parent.frame)
2156
+ 0
2157
+
2158
+ """
2159
+
2160
+ def __init__(self, name, parent, child, parent_point=None, child_point=None,
2161
+ parent_interframe=None, child_interframe=None):
2162
+ super().__init__(name, parent, child, [], [], parent_point,
2163
+ child_point, parent_interframe=parent_interframe,
2164
+ child_interframe=child_interframe)
2165
+ self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770
2166
+
2167
+ def __str__(self):
2168
+ return (f'WeldJoint: {self.name} parent: {self.parent} '
2169
+ f'child: {self.child}')
2170
+
2171
+ def _generate_coordinates(self, coordinate):
2172
+ return Matrix()
2173
+
2174
+ def _generate_speeds(self, speed):
2175
+ return Matrix()
2176
+
2177
+ def _orient_frames(self):
2178
+ self.child_interframe.orient_axis(self.parent_interframe,
2179
+ self.parent_interframe.x, 0)
2180
+
2181
+ def _set_angular_velocity(self):
2182
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
2183
+
2184
+ def _set_linear_velocity(self):
2185
+ self.child_point.set_pos(self.parent_point, 0)
2186
+ self.parent_point.set_vel(self._parent_frame, 0)
2187
+ self.child_point.set_vel(self._child_frame, 0)
2188
+ self.child.masscenter.set_vel(self._parent_frame, 0)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
2
+ RigidBody, Particle)
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.mechanics.method import _Methods
5
+ from sympy import Matrix
6
+ from sympy.utilities.exceptions import sympy_deprecation_warning
7
+
8
+ __all__ = ['JointsMethod']
9
+
10
+
11
+ class JointsMethod(_Methods):
12
+ """Method for formulating the equations of motion using a set of interconnected bodies with joints.
13
+
14
+ .. deprecated:: 1.13
15
+ The JointsMethod class is deprecated. Its functionality has been
16
+ replaced by the new :class:`~.System` class.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ newtonion : Body or ReferenceFrame
22
+ The newtonion(inertial) frame.
23
+ *joints : Joint
24
+ The joints in the system
25
+
26
+ Attributes
27
+ ==========
28
+
29
+ q, u : iterable
30
+ Iterable of the generalized coordinates and speeds
31
+ bodies : iterable
32
+ Iterable of Body objects in the system.
33
+ loads : iterable
34
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
35
+ describing the forces on the system.
36
+ mass_matrix : Matrix, shape(n, n)
37
+ The system's mass matrix
38
+ forcing : Matrix, shape(n, 1)
39
+ The system's forcing vector
40
+ mass_matrix_full : Matrix, shape(2*n, 2*n)
41
+ The "mass matrix" for the u's and q's
42
+ forcing_full : Matrix, shape(2*n, 1)
43
+ The "forcing vector" for the u's and q's
44
+ method : KanesMethod or Lagrange's method
45
+ Method's object.
46
+ kdes : iterable
47
+ Iterable of kde in they system.
48
+
49
+ Examples
50
+ ========
51
+
52
+ As Body and JointsMethod have been deprecated, the following examples are
53
+ for illustrative purposes only. The functionality of Body is fully captured
54
+ by :class:`~.RigidBody` and :class:`~.Particle` and the functionality of
55
+ JointsMethod is fully captured by :class:`~.System`. To ignore the
56
+ deprecation warning we can use the ignore_warnings context manager.
57
+
58
+ >>> from sympy.utilities.exceptions import ignore_warnings
59
+
60
+ This is a simple example for a one degree of freedom translational
61
+ spring-mass-damper.
62
+
63
+ >>> from sympy import symbols
64
+ >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
65
+ >>> from sympy.physics.vector import dynamicsymbols
66
+ >>> c, k = symbols('c k')
67
+ >>> x, v = dynamicsymbols('x v')
68
+ >>> with ignore_warnings(DeprecationWarning):
69
+ ... wall = Body('W')
70
+ ... body = Body('B')
71
+ >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
72
+ >>> wall.apply_force(c*v*wall.x, reaction_body=body)
73
+ >>> wall.apply_force(k*x*wall.x, reaction_body=body)
74
+ >>> with ignore_warnings(DeprecationWarning):
75
+ ... method = JointsMethod(wall, J)
76
+ >>> method.form_eoms()
77
+ Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
78
+ >>> M = method.mass_matrix_full
79
+ >>> F = method.forcing_full
80
+ >>> rhs = M.LUsolve(F)
81
+ >>> rhs
82
+ Matrix([
83
+ [ v(t)],
84
+ [(-c*v(t) - k*x(t))/B_mass]])
85
+
86
+ Notes
87
+ =====
88
+
89
+ ``JointsMethod`` currently only works with systems that do not have any
90
+ configuration or motion constraints.
91
+
92
+ """
93
+
94
+ def __init__(self, newtonion, *joints):
95
+ sympy_deprecation_warning(
96
+ """
97
+ The JointsMethod class is deprecated.
98
+ Its functionality has been replaced by the new System class.
99
+ """,
100
+ deprecated_since_version="1.13",
101
+ active_deprecations_target="deprecated-mechanics-jointsmethod"
102
+ )
103
+ if isinstance(newtonion, BodyBase):
104
+ self.frame = newtonion.frame
105
+ else:
106
+ self.frame = newtonion
107
+
108
+ self._joints = joints
109
+ self._bodies = self._generate_bodylist()
110
+ self._loads = self._generate_loadlist()
111
+ self._q = self._generate_q()
112
+ self._u = self._generate_u()
113
+ self._kdes = self._generate_kdes()
114
+
115
+ self._method = None
116
+
117
+ @property
118
+ def bodies(self):
119
+ """List of bodies in they system."""
120
+ return self._bodies
121
+
122
+ @property
123
+ def loads(self):
124
+ """List of loads on the system."""
125
+ return self._loads
126
+
127
+ @property
128
+ def q(self):
129
+ """List of the generalized coordinates."""
130
+ return self._q
131
+
132
+ @property
133
+ def u(self):
134
+ """List of the generalized speeds."""
135
+ return self._u
136
+
137
+ @property
138
+ def kdes(self):
139
+ """List of the generalized coordinates."""
140
+ return self._kdes
141
+
142
+ @property
143
+ def forcing_full(self):
144
+ """The "forcing vector" for the u's and q's."""
145
+ return self.method.forcing_full
146
+
147
+ @property
148
+ def mass_matrix_full(self):
149
+ """The "mass matrix" for the u's and q's."""
150
+ return self.method.mass_matrix_full
151
+
152
+ @property
153
+ def mass_matrix(self):
154
+ """The system's mass matrix."""
155
+ return self.method.mass_matrix
156
+
157
+ @property
158
+ def forcing(self):
159
+ """The system's forcing vector."""
160
+ return self.method.forcing
161
+
162
+ @property
163
+ def method(self):
164
+ """Object of method used to form equations of systems."""
165
+ return self._method
166
+
167
+ def _generate_bodylist(self):
168
+ bodies = []
169
+ for joint in self._joints:
170
+ if joint.child not in bodies:
171
+ bodies.append(joint.child)
172
+ if joint.parent not in bodies:
173
+ bodies.append(joint.parent)
174
+ return bodies
175
+
176
+ def _generate_loadlist(self):
177
+ load_list = []
178
+ for body in self.bodies:
179
+ if isinstance(body, Body):
180
+ load_list.extend(body.loads)
181
+ return load_list
182
+
183
+ def _generate_q(self):
184
+ q_ind = []
185
+ for joint in self._joints:
186
+ for coordinate in joint.coordinates:
187
+ if coordinate in q_ind:
188
+ raise ValueError('Coordinates of joints should be unique.')
189
+ q_ind.append(coordinate)
190
+ return Matrix(q_ind)
191
+
192
+ def _generate_u(self):
193
+ u_ind = []
194
+ for joint in self._joints:
195
+ for speed in joint.speeds:
196
+ if speed in u_ind:
197
+ raise ValueError('Speeds of joints should be unique.')
198
+ u_ind.append(speed)
199
+ return Matrix(u_ind)
200
+
201
+ def _generate_kdes(self):
202
+ kd_ind = Matrix(1, 0, []).T
203
+ for joint in self._joints:
204
+ kd_ind = kd_ind.col_join(joint.kdes)
205
+ return kd_ind
206
+
207
+ def _convert_bodies(self):
208
+ # Convert `Body` to `Particle` and `RigidBody`
209
+ bodylist = []
210
+ for body in self.bodies:
211
+ if not isinstance(body, Body):
212
+ bodylist.append(body)
213
+ continue
214
+ if body.is_rigidbody:
215
+ rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
216
+ (body.central_inertia, body.masscenter))
217
+ rb.potential_energy = body.potential_energy
218
+ bodylist.append(rb)
219
+ else:
220
+ part = Particle(body.name, body.masscenter, body.mass)
221
+ part.potential_energy = body.potential_energy
222
+ bodylist.append(part)
223
+ return bodylist
224
+
225
+ def form_eoms(self, method=KanesMethod):
226
+ """Method to form system's equation of motions.
227
+
228
+ Parameters
229
+ ==========
230
+
231
+ method : Class
232
+ Class name of method.
233
+
234
+ Returns
235
+ ========
236
+
237
+ Matrix
238
+ Vector of equations of motions.
239
+
240
+ Examples
241
+ ========
242
+
243
+ As Body and JointsMethod have been deprecated, the following examples
244
+ are for illustrative purposes only. The functionality of Body is fully
245
+ captured by :class:`~.RigidBody` and :class:`~.Particle` and the
246
+ functionality of JointsMethod is fully captured by :class:`~.System`. To
247
+ ignore the deprecation warning we can use the ignore_warnings context
248
+ manager.
249
+
250
+ >>> from sympy.utilities.exceptions import ignore_warnings
251
+
252
+ This is a simple example for a one degree of freedom translational
253
+ spring-mass-damper.
254
+
255
+ >>> from sympy import S, symbols
256
+ >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
257
+ >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
258
+ >>> q = dynamicsymbols('q')
259
+ >>> qd = dynamicsymbols('q', 1)
260
+ >>> m, k, b = symbols('m k b')
261
+ >>> with ignore_warnings(DeprecationWarning):
262
+ ... wall = Body('W')
263
+ ... part = Body('P', mass=m)
264
+ >>> part.potential_energy = k * q**2 / S(2)
265
+ >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
266
+ >>> wall.apply_force(b * qd * wall.x, reaction_body=part)
267
+ >>> with ignore_warnings(DeprecationWarning):
268
+ ... method = JointsMethod(wall, J)
269
+ >>> method.form_eoms(LagrangesMethod)
270
+ Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
271
+
272
+ We can also solve for the states using the 'rhs' method.
273
+
274
+ >>> method.rhs()
275
+ Matrix([
276
+ [ Derivative(q(t), t)],
277
+ [(-b*Derivative(q(t), t) - k*q(t))/m]])
278
+
279
+ """
280
+
281
+ bodylist = self._convert_bodies()
282
+ if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
283
+ L = Lagrangian(self.frame, *bodylist)
284
+ self._method = method(L, self.q, self.loads, bodylist, self.frame)
285
+ else: #KanesMethod or similar
286
+ self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
287
+ forcelist=self.loads, bodies=bodylist)
288
+ soln = self.method._form_eoms()
289
+ return soln
290
+
291
+ def rhs(self, inv_method=None):
292
+ """Returns equations that can be solved numerically.
293
+
294
+ Parameters
295
+ ==========
296
+
297
+ inv_method : str
298
+ The specific sympy inverse matrix calculation method to use. For a
299
+ list of valid methods, see
300
+ :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
301
+
302
+ Returns
303
+ ========
304
+
305
+ Matrix
306
+ Numerically solvable equations.
307
+
308
+ See Also
309
+ ========
310
+
311
+ sympy.physics.mechanics.kane.KanesMethod.rhs:
312
+ KanesMethod's rhs function.
313
+ sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
314
+ LagrangesMethod's rhs function.
315
+
316
+ """
317
+
318
+ return self.method.rhs(inv_method=inv_method)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py ADDED
@@ -0,0 +1,859 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import zeros, Matrix, diff, eye, linear_eq_to_matrix
2
+ from sympy.core.sorting import default_sort_key
3
+ from sympy.physics.vector import (ReferenceFrame, dynamicsymbols,
4
+ partial_velocity)
5
+ from sympy.physics.mechanics.method import _Methods
6
+ from sympy.physics.mechanics.particle import Particle
7
+ from sympy.physics.mechanics.rigidbody import RigidBody
8
+ from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols,
9
+ _f_list_parser,
10
+ _validate_coordinates,
11
+ _parse_linear_solver)
12
+ from sympy.physics.mechanics.linearize import Linearizer
13
+ from sympy.utilities.iterables import iterable
14
+
15
+
16
+ __all__ = ['KanesMethod']
17
+
18
+
19
+ class KanesMethod(_Methods):
20
+ r"""Kane's method object.
21
+
22
+ Explanation
23
+ ===========
24
+
25
+ This object is used to do the "book-keeping" as you go through and form
26
+ equations of motion in the way Kane presents in:
27
+ Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
28
+
29
+ The attributes are for equations in the form [M] udot = forcing.
30
+
31
+ Attributes
32
+ ==========
33
+
34
+ q, u : Matrix
35
+ Matrices of the generalized coordinates and speeds
36
+ bodies : iterable
37
+ Iterable of Particle and RigidBody objects in the system.
38
+ loads : iterable
39
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
40
+ describing the forces on the system.
41
+ auxiliary_eqs : Matrix
42
+ If applicable, the set of auxiliary Kane's
43
+ equations used to solve for non-contributing
44
+ forces.
45
+ mass_matrix : Matrix
46
+ The system's dynamics mass matrix: [k_d; k_dnh]
47
+ forcing : Matrix
48
+ The system's dynamics forcing vector: -[f_d; f_dnh]
49
+ mass_matrix_kin : Matrix
50
+ The "mass matrix" for kinematic differential equations: k_kqdot
51
+ forcing_kin : Matrix
52
+ The forcing vector for kinematic differential equations: -(k_ku*u + f_k)
53
+ mass_matrix_full : Matrix
54
+ The "mass matrix" for the u's and q's with dynamics and kinematics
55
+ forcing_full : Matrix
56
+ The "forcing vector" for the u's and q's with dynamics and kinematics
57
+
58
+ Parameters
59
+ ==========
60
+
61
+ frame : ReferenceFrame
62
+ The inertial reference frame for the system.
63
+ q_ind : iterable of dynamicsymbols
64
+ Independent generalized coordinates.
65
+ u_ind : iterable of dynamicsymbols
66
+ Independent generalized speeds.
67
+ kd_eqs : iterable of Expr, optional
68
+ Kinematic differential equations, which linearly relate the generalized
69
+ speeds to the time-derivatives of the generalized coordinates.
70
+ q_dependent : iterable of dynamicsymbols, optional
71
+ Dependent generalized coordinates.
72
+ configuration_constraints : iterable of Expr, optional
73
+ Constraints on the system's configuration, i.e. holonomic constraints.
74
+ u_dependent : iterable of dynamicsymbols, optional
75
+ Dependent generalized speeds.
76
+ velocity_constraints : iterable of Expr, optional
77
+ Constraints on the system's velocity, i.e. the combination of the
78
+ nonholonomic constraints and the time-derivative of the holonomic
79
+ constraints.
80
+ acceleration_constraints : iterable of Expr, optional
81
+ Constraints on the system's acceleration, by default these are the
82
+ time-derivative of the velocity constraints.
83
+ u_auxiliary : iterable of dynamicsymbols, optional
84
+ Auxiliary generalized speeds.
85
+ bodies : iterable of Particle and/or RigidBody, optional
86
+ The particles and rigid bodies in the system.
87
+ forcelist : iterable of tuple[Point | ReferenceFrame, Vector], optional
88
+ Forces and torques applied on the system.
89
+ explicit_kinematics : bool
90
+ Boolean whether the mass matrices and forcing vectors should use the
91
+ explicit form (default) or implicit form for kinematics.
92
+ See the notes for more details.
93
+ kd_eqs_solver : str, callable
94
+ Method used to solve the kinematic differential equations. If a string
95
+ is supplied, it should be a valid method that can be used with the
96
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
97
+ supplied, it should have the format ``f(A, rhs)``, where it solves the
98
+ equations and returns the solution. The default utilizes LU solve. See
99
+ the notes for more information.
100
+ constraint_solver : str, callable
101
+ Method used to solve the velocity constraints. If a string is
102
+ supplied, it should be a valid method that can be used with the
103
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
104
+ supplied, it should have the format ``f(A, rhs)``, where it solves the
105
+ equations and returns the solution. The default utilizes LU solve. See
106
+ the notes for more information.
107
+
108
+ Notes
109
+ =====
110
+
111
+ The mass matrices and forcing vectors related to kinematic equations
112
+ are given in the explicit form by default. In other words, the kinematic
113
+ mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$.
114
+ In order to get the implicit form of those matrices/vectors, you can set the
115
+ ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$
116
+ is not necessarily an identity matrix. This can provide more compact
117
+ equations for non-simple kinematics.
118
+
119
+ Two linear solvers can be supplied to ``KanesMethod``: one for solving the
120
+ kinematic differential equations and one to solve the velocity constraints.
121
+ Both of these sets of equations can be expressed as a linear system ``Ax = rhs``,
122
+ which have to be solved in order to obtain the equations of motion.
123
+
124
+ The default solver ``'LU'``, which stands for LU solve, results relatively low
125
+ number of operations. The weakness of this method is that it can result in zero
126
+ division errors.
127
+
128
+ If zero divisions are encountered, a possible solver which may solve the problem
129
+ is ``"CRAMER"``. This method uses Cramer's rule to solve the system. This method
130
+ is slower and results in more operations than the default solver. However it only
131
+ uses a single division by default per entry of the solution.
132
+
133
+ While a valid list of solvers can be found at
134
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`, it is also possible to supply a
135
+ `callable`. This way it is possible to use a different solver routine. If the
136
+ kinematic differential equations are not too complex it can be worth it to simplify
137
+ the solution by using ``lambda A, b: simplify(Matrix.LUsolve(A, b))``. Another
138
+ option solver one may use is :func:`sympy.solvers.solveset.linsolve`. This can be
139
+ done using `lambda A, b: tuple(linsolve((A, b)))[0]`, where we select the first
140
+ solution as our system should have only one unique solution.
141
+
142
+ Examples
143
+ ========
144
+
145
+ This is a simple example for a one degree of freedom translational
146
+ spring-mass-damper.
147
+
148
+ In this example, we first need to do the kinematics.
149
+ This involves creating generalized speeds and coordinates and their
150
+ derivatives.
151
+ Then we create a point and set its velocity in a frame.
152
+
153
+ >>> from sympy import symbols
154
+ >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame
155
+ >>> from sympy.physics.mechanics import Point, Particle, KanesMethod
156
+ >>> q, u = dynamicsymbols('q u')
157
+ >>> qd, ud = dynamicsymbols('q u', 1)
158
+ >>> m, c, k = symbols('m c k')
159
+ >>> N = ReferenceFrame('N')
160
+ >>> P = Point('P')
161
+ >>> P.set_vel(N, u * N.x)
162
+
163
+ Next we need to arrange/store information in the way that KanesMethod
164
+ requires. The kinematic differential equations should be an iterable of
165
+ expressions. A list of forces/torques must be constructed, where each entry
166
+ in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where
167
+ the Vectors represent the Force or Torque.
168
+ Next a particle needs to be created, and it needs to have a point and mass
169
+ assigned to it.
170
+ Finally, a list of all bodies and particles needs to be created.
171
+
172
+ >>> kd = [qd - u]
173
+ >>> FL = [(P, (-k * q - c * u) * N.x)]
174
+ >>> pa = Particle('pa', P, m)
175
+ >>> BL = [pa]
176
+
177
+ Finally we can generate the equations of motion.
178
+ First we create the KanesMethod object and supply an inertial frame,
179
+ coordinates, generalized speeds, and the kinematic differential equations.
180
+ Additional quantities such as configuration and motion constraints,
181
+ dependent coordinates and speeds, and auxiliary speeds are also supplied
182
+ here (see the online documentation).
183
+ Next we form FR* and FR to complete: Fr + Fr* = 0.
184
+ We have the equations of motion at this point.
185
+ It makes sense to rearrange them though, so we calculate the mass matrix and
186
+ the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is
187
+ the mass matrix, udot is a vector of the time derivatives of the
188
+ generalized speeds, and forcing is a vector representing "forcing" terms.
189
+
190
+ >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd)
191
+ >>> (fr, frstar) = KM.kanes_equations(BL, FL)
192
+ >>> MM = KM.mass_matrix
193
+ >>> forcing = KM.forcing
194
+ >>> rhs = MM.inv() * forcing
195
+ >>> rhs
196
+ Matrix([[(-c*u(t) - k*q(t))/m]])
197
+ >>> KM.linearize(A_and_B=True)[0]
198
+ Matrix([
199
+ [ 0, 1],
200
+ [-k/m, -c/m]])
201
+
202
+ Please look at the documentation pages for more information on how to
203
+ perform linearization and how to deal with dependent coordinates & speeds,
204
+ and how do deal with bringing non-contributing forces into evidence.
205
+
206
+ """
207
+
208
+ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
209
+ configuration_constraints=None, u_dependent=None,
210
+ velocity_constraints=None, acceleration_constraints=None,
211
+ u_auxiliary=None, bodies=None, forcelist=None,
212
+ explicit_kinematics=True, kd_eqs_solver='LU',
213
+ constraint_solver='LU'):
214
+
215
+ """Please read the online documentation. """
216
+ if not q_ind:
217
+ q_ind = [dynamicsymbols('dummy_q')]
218
+ kd_eqs = [dynamicsymbols('dummy_kd')]
219
+
220
+ if not isinstance(frame, ReferenceFrame):
221
+ raise TypeError('An inertial ReferenceFrame must be supplied')
222
+ self._inertial = frame
223
+
224
+ self._fr = None
225
+ self._frstar = None
226
+
227
+ self._forcelist = forcelist
228
+ self._bodylist = bodies
229
+
230
+ self.explicit_kinematics = explicit_kinematics
231
+ self._constraint_solver = constraint_solver
232
+ self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
233
+ u_auxiliary)
234
+ _validate_coordinates(self.q, self.u)
235
+ self._initialize_kindiffeq_matrices(kd_eqs, kd_eqs_solver)
236
+ self._initialize_constraint_matrices(
237
+ configuration_constraints, velocity_constraints,
238
+ acceleration_constraints, constraint_solver)
239
+
240
+ def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
241
+ """Initialize the coordinate and speed vectors."""
242
+
243
+ none_handler = lambda x: Matrix(x) if x else Matrix()
244
+
245
+ # Initialize generalized coordinates
246
+ q_dep = none_handler(q_dep)
247
+ if not iterable(q_ind):
248
+ raise TypeError('Generalized coordinates must be an iterable.')
249
+ if not iterable(q_dep):
250
+ raise TypeError('Dependent coordinates must be an iterable.')
251
+ q_ind = Matrix(q_ind)
252
+ self._qdep = q_dep
253
+ self._q = Matrix([q_ind, q_dep])
254
+ self._qdot = self.q.diff(dynamicsymbols._t)
255
+
256
+ # Initialize generalized speeds
257
+ u_dep = none_handler(u_dep)
258
+ if not iterable(u_ind):
259
+ raise TypeError('Generalized speeds must be an iterable.')
260
+ if not iterable(u_dep):
261
+ raise TypeError('Dependent speeds must be an iterable.')
262
+ u_ind = Matrix(u_ind)
263
+ self._udep = u_dep
264
+ self._u = Matrix([u_ind, u_dep])
265
+ self._udot = self.u.diff(dynamicsymbols._t)
266
+ self._uaux = none_handler(u_aux)
267
+
268
+ def _initialize_constraint_matrices(self, config, vel, acc, linear_solver='LU'):
269
+ """Initializes constraint matrices."""
270
+ linear_solver = _parse_linear_solver(linear_solver)
271
+ # Define vector dimensions
272
+ o = len(self.u)
273
+ m = len(self._udep)
274
+ p = o - m
275
+ none_handler = lambda x: Matrix(x) if x else Matrix()
276
+
277
+ # Initialize configuration constraints
278
+ config = none_handler(config)
279
+ if len(self._qdep) != len(config):
280
+ raise ValueError('There must be an equal number of dependent '
281
+ 'coordinates and configuration constraints.')
282
+ self._f_h = none_handler(config)
283
+
284
+ # Initialize velocity and acceleration constraints
285
+ vel = none_handler(vel)
286
+ acc = none_handler(acc)
287
+ if len(vel) != m:
288
+ raise ValueError('There must be an equal number of dependent '
289
+ 'speeds and velocity constraints.')
290
+ if acc and (len(acc) != m):
291
+ raise ValueError('There must be an equal number of dependent '
292
+ 'speeds and acceleration constraints.')
293
+ if vel:
294
+
295
+ # When calling kanes_equations, another class instance will be
296
+ # created if auxiliary u's are present. In this case, the
297
+ # computation of kinetic differential equation matrices will be
298
+ # skipped as this was computed during the original KanesMethod
299
+ # object, and the qd_u_map will not be available.
300
+ if self._qdot_u_map is not None:
301
+ vel = msubs(vel, self._qdot_u_map)
302
+ self._k_nh, f_nh_neg = linear_eq_to_matrix(vel, self.u[:])
303
+ self._f_nh = -f_nh_neg
304
+
305
+ # If no acceleration constraints given, calculate them.
306
+ if not acc:
307
+ _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u +
308
+ self._f_nh.diff(dynamicsymbols._t))
309
+ if self._qdot_u_map is not None:
310
+ _f_dnh = msubs(_f_dnh, self._qdot_u_map)
311
+ self._f_dnh = _f_dnh
312
+ self._k_dnh = self._k_nh
313
+ else:
314
+ if self._qdot_u_map is not None:
315
+ acc = msubs(acc, self._qdot_u_map)
316
+
317
+ self._k_dnh, f_dnh_neg = linear_eq_to_matrix(acc, self._udot[:])
318
+ self._f_dnh = -f_dnh_neg
319
+ # Form of non-holonomic constraints is B*u + C = 0.
320
+ # We partition B into independent and dependent columns:
321
+ # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds
322
+ # to independent speeds as: udep = Ars*uind, neglecting the C term.
323
+ B_ind = self._k_nh[:, :p]
324
+ B_dep = self._k_nh[:, p:o]
325
+ self._Ars = -linear_solver(B_dep, B_ind)
326
+ else:
327
+ self._f_nh = Matrix()
328
+ self._k_nh = Matrix()
329
+ self._f_dnh = Matrix()
330
+ self._k_dnh = Matrix()
331
+ self._Ars = Matrix()
332
+
333
+ def _initialize_kindiffeq_matrices(self, kdeqs, linear_solver='LU'):
334
+ """Initialize the kinematic differential equation matrices.
335
+
336
+ Parameters
337
+ ==========
338
+ kdeqs : sequence of sympy expressions
339
+ Kinematic differential equations in the form of f(u,q',q,t) where
340
+ f() = 0. The equations have to be linear in the time-derivatives of
341
+ the generalized coordinates and in the generalized speeds.
342
+
343
+ """
344
+ linear_solver = _parse_linear_solver(linear_solver)
345
+ if kdeqs:
346
+ if len(self.q) != len(kdeqs):
347
+ raise ValueError('There must be an equal number of kinematic '
348
+ 'differential equations and coordinates.')
349
+
350
+ u = self.u
351
+ qdot = self._qdot
352
+
353
+ kdeqs = Matrix(kdeqs)
354
+
355
+ u_zero = dict.fromkeys(u, 0)
356
+ uaux_zero = dict.fromkeys(self._uaux, 0)
357
+ qdot_zero = dict.fromkeys(qdot, 0)
358
+
359
+ # Extract the linear coefficient matrices as per the following
360
+ # equation:
361
+ #
362
+ # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0
363
+ #
364
+ k_ku = kdeqs.jacobian(u)
365
+ k_kqdot = kdeqs.jacobian(qdot)
366
+ f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero)
367
+
368
+ # The kinematic differential equations should be linear in both q'
369
+ # and u so check for u and q' in the components.
370
+ dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k))
371
+ nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms]
372
+ if nonlin_vars:
373
+ msg = ('The provided kinematic differential equations are '
374
+ 'nonlinear in {}. They must be linear in the '
375
+ 'generalized speeds and derivatives of the generalized '
376
+ 'coordinates.')
377
+ raise ValueError(msg.format(nonlin_vars))
378
+
379
+ self._f_k_implicit = f_k.xreplace(uaux_zero)
380
+ self._k_ku_implicit = k_ku.xreplace(uaux_zero)
381
+ self._k_kqdot_implicit = k_kqdot
382
+
383
+ # Solve for q'(t) such that the coefficient matrices are now in
384
+ # this form:
385
+ #
386
+ # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0
387
+ #
388
+ # NOTE : Solving the kinematic differential equations here is not
389
+ # necessary and prevents the equations from being provided in fully
390
+ # implicit form.
391
+ f_k_explicit = linear_solver(k_kqdot, f_k)
392
+ k_ku_explicit = linear_solver(k_kqdot, k_ku)
393
+ self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit)))
394
+
395
+ self._f_k = f_k_explicit.xreplace(uaux_zero)
396
+ self._k_ku = k_ku_explicit.xreplace(uaux_zero)
397
+ self._k_kqdot = eye(len(qdot))
398
+
399
+ else:
400
+ self._qdot_u_map = None
401
+ self._f_k_implicit = self._f_k = Matrix()
402
+ self._k_ku_implicit = self._k_ku = Matrix()
403
+ self._k_kqdot_implicit = self._k_kqdot = Matrix()
404
+
405
+ def _form_fr(self, fl):
406
+ """Form the generalized active force."""
407
+ if fl is not None and (len(fl) == 0 or not iterable(fl)):
408
+ raise ValueError('Force pairs must be supplied in an '
409
+ 'non-empty iterable or None.')
410
+
411
+ N = self._inertial
412
+ # pull out relevant velocities for constructing partial velocities
413
+ vel_list, f_list = _f_list_parser(fl, N)
414
+ vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
415
+ f_list = [msubs(i, self._qdot_u_map) for i in f_list]
416
+
417
+ # Fill Fr with dot product of partial velocities and forces
418
+ o = len(self.u)
419
+ b = len(f_list)
420
+ FR = zeros(o, 1)
421
+ partials = partial_velocity(vel_list, self.u, N)
422
+ for i in range(o):
423
+ FR[i] = sum(partials[j][i].dot(f_list[j]) for j in range(b))
424
+
425
+ # In case there are dependent speeds
426
+ if self._udep:
427
+ p = o - len(self._udep)
428
+ FRtilde = FR[:p, 0]
429
+ FRold = FR[p:o, 0]
430
+ FRtilde += self._Ars.T * FRold
431
+ FR = FRtilde
432
+
433
+ self._forcelist = fl
434
+ self._fr = FR
435
+ return FR
436
+
437
+ def _form_frstar(self, bl):
438
+ """Form the generalized inertia force."""
439
+
440
+ if not iterable(bl):
441
+ raise TypeError('Bodies must be supplied in an iterable.')
442
+
443
+ t = dynamicsymbols._t
444
+ N = self._inertial
445
+ # Dicts setting things to zero
446
+ udot_zero = dict.fromkeys(self._udot, 0)
447
+ uaux_zero = dict.fromkeys(self._uaux, 0)
448
+ uauxdot = [diff(i, t) for i in self._uaux]
449
+ uauxdot_zero = dict.fromkeys(uauxdot, 0)
450
+ # Dictionary of q' and q'' to u and u'
451
+ q_ddot_u_map = {k.diff(t): v.diff(t).xreplace(
452
+ self._qdot_u_map) for (k, v) in self._qdot_u_map.items()}
453
+ q_ddot_u_map.update(self._qdot_u_map)
454
+
455
+ # Fill up the list of partials: format is a list with num elements
456
+ # equal to number of entries in body list. Each of these elements is a
457
+ # list - either of length 1 for the translational components of
458
+ # particles or of length 2 for the translational and rotational
459
+ # components of rigid bodies. The inner most list is the list of
460
+ # partial velocities.
461
+ def get_partial_velocity(body):
462
+ if isinstance(body, RigidBody):
463
+ vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)]
464
+ elif isinstance(body, Particle):
465
+ vlist = [body.point.vel(N),]
466
+ else:
467
+ raise TypeError('The body list may only contain either '
468
+ 'RigidBody or Particle as list elements.')
469
+ v = [msubs(vel, self._qdot_u_map) for vel in vlist]
470
+ return partial_velocity(v, self.u, N)
471
+ partials = [get_partial_velocity(body) for body in bl]
472
+
473
+ # Compute fr_star in two components:
474
+ # fr_star = -(MM*u' + nonMM)
475
+ o = len(self.u)
476
+ MM = zeros(o, o)
477
+ nonMM = zeros(o, 1)
478
+ zero_uaux = lambda expr: msubs(expr, uaux_zero)
479
+ zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero)
480
+ for i, body in enumerate(bl):
481
+ if isinstance(body, RigidBody):
482
+ M = zero_uaux(body.mass)
483
+ I = zero_uaux(body.central_inertia)
484
+ vel = zero_uaux(body.masscenter.vel(N))
485
+ omega = zero_uaux(body.frame.ang_vel_in(N))
486
+ acc = zero_udot_uaux(body.masscenter.acc(N))
487
+ inertial_force = (M.diff(t) * vel + M * acc)
488
+ inertial_torque = zero_uaux((I.dt(body.frame).dot(omega)) +
489
+ msubs(I.dot(body.frame.ang_acc_in(N)), udot_zero) +
490
+ (omega.cross(I.dot(omega))))
491
+ for j in range(o):
492
+ tmp_vel = zero_uaux(partials[i][0][j])
493
+ tmp_ang = zero_uaux(I.dot(partials[i][1][j]))
494
+ for k in range(o):
495
+ # translational
496
+ MM[j, k] += M*tmp_vel.dot(partials[i][0][k])
497
+ # rotational
498
+ MM[j, k] += tmp_ang.dot(partials[i][1][k])
499
+ nonMM[j] += inertial_force.dot(partials[i][0][j])
500
+ nonMM[j] += inertial_torque.dot(partials[i][1][j])
501
+ else:
502
+ M = zero_uaux(body.mass)
503
+ vel = zero_uaux(body.point.vel(N))
504
+ acc = zero_udot_uaux(body.point.acc(N))
505
+ inertial_force = (M.diff(t) * vel + M * acc)
506
+ for j in range(o):
507
+ temp = zero_uaux(partials[i][0][j])
508
+ for k in range(o):
509
+ MM[j, k] += M*temp.dot(partials[i][0][k])
510
+ nonMM[j] += inertial_force.dot(partials[i][0][j])
511
+ # Compose fr_star out of MM and nonMM
512
+ MM = zero_uaux(msubs(MM, q_ddot_u_map))
513
+ nonMM = msubs(msubs(nonMM, q_ddot_u_map),
514
+ udot_zero, uauxdot_zero, uaux_zero)
515
+ fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM)
516
+
517
+ # If there are dependent speeds, we need to find fr_star_tilde
518
+ if self._udep:
519
+ p = o - len(self._udep)
520
+ fr_star_ind = fr_star[:p, 0]
521
+ fr_star_dep = fr_star[p:o, 0]
522
+ fr_star = fr_star_ind + (self._Ars.T * fr_star_dep)
523
+ # Apply the same to MM
524
+ MMi = MM[:p, :]
525
+ MMd = MM[p:o, :]
526
+ MM = MMi + (self._Ars.T * MMd)
527
+ # Apply the same to nonMM
528
+ nonMM = nonMM[:p, :] + (self._Ars.T * nonMM[p:o, :])
529
+
530
+ self._bodylist = bl
531
+ self._frstar = fr_star
532
+ self._k_d = MM
533
+ self._f_d = -(self._fr - nonMM)
534
+ return fr_star
535
+
536
+ def to_linearizer(self, linear_solver='LU'):
537
+ """Returns an instance of the Linearizer class, initiated from the
538
+ data in the KanesMethod class. This may be more desirable than using
539
+ the linearize class method, as the Linearizer object will allow more
540
+ efficient recalculation (i.e. about varying operating points).
541
+
542
+ Parameters
543
+ ==========
544
+ linear_solver : str, callable
545
+ Method used to solve the several symbolic linear systems of the
546
+ form ``A*x=b`` in the linearization process. If a string is
547
+ supplied, it should be a valid method that can be used with the
548
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
549
+ supplied, it should have the format ``x = f(A, b)``, where it
550
+ solves the equations and returns the solution. The default is
551
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
552
+ ``LUsolve()`` is fast to compute but will often result in
553
+ divide-by-zero and thus ``nan`` results.
554
+
555
+ Returns
556
+ =======
557
+ Linearizer
558
+ An instantiated
559
+ :class:`sympy.physics.mechanics.linearize.Linearizer`.
560
+
561
+ """
562
+
563
+ if (self._fr is None) or (self._frstar is None):
564
+ raise ValueError('Need to compute Fr, Fr* first.')
565
+
566
+ # Get required equation components. The Kane's method class breaks
567
+ # these into pieces. Need to reassemble
568
+ f_c = self._f_h
569
+ if self._f_nh and self._k_nh:
570
+ f_v = self._f_nh + self._k_nh*Matrix(self.u)
571
+ else:
572
+ f_v = Matrix()
573
+ if self._f_dnh and self._k_dnh:
574
+ f_a = self._f_dnh + self._k_dnh*Matrix(self._udot)
575
+ else:
576
+ f_a = Matrix()
577
+ # Dicts to sub to zero, for splitting up expressions
578
+ u_zero = dict.fromkeys(self.u, 0)
579
+ ud_zero = dict.fromkeys(self._udot, 0)
580
+ qd_zero = dict.fromkeys(self._qdot, 0)
581
+ qd_u_zero = dict.fromkeys(Matrix([self._qdot, self.u]), 0)
582
+ # Break the kinematic differential eqs apart into f_0 and f_1
583
+ f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot)
584
+ f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u)
585
+ # Break the dynamic differential eqs into f_2 and f_3
586
+ f_2 = msubs(self._frstar, qd_u_zero)
587
+ f_3 = msubs(self._frstar, ud_zero) + self._fr
588
+ f_4 = zeros(len(f_2), 1)
589
+
590
+ # Get the required vector components
591
+ q = self.q
592
+ u = self.u
593
+ if self._qdep:
594
+ q_i = q[:-len(self._qdep)]
595
+ else:
596
+ q_i = q
597
+ q_d = self._qdep
598
+ if self._udep:
599
+ u_i = u[:-len(self._udep)]
600
+ else:
601
+ u_i = u
602
+ u_d = self._udep
603
+
604
+ # Form dictionary to set auxiliary speeds & their derivatives to 0.
605
+ uaux = self._uaux
606
+ uauxdot = uaux.diff(dynamicsymbols._t)
607
+ uaux_zero = dict.fromkeys(Matrix([uaux, uauxdot]), 0)
608
+
609
+ # Checking for dynamic symbols outside the dynamic differential
610
+ # equations; throws error if there is.
611
+ sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot]))
612
+ if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot,
613
+ self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]):
614
+ raise ValueError('Cannot have dynamicsymbols outside dynamic \
615
+ forcing vector.')
616
+
617
+ # Find all other dynamic symbols, forming the forcing vector r.
618
+ # Sort r to make it canonical.
619
+ r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list))
620
+ r.sort(key=default_sort_key)
621
+
622
+ # Check for any derivatives of variables in r that are also found in r.
623
+ for i in r:
624
+ if diff(i, dynamicsymbols._t) in r:
625
+ raise ValueError('Cannot have derivatives of specified \
626
+ quantities when linearizing forcing terms.')
627
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
628
+ q_d, u_i, u_d, r, linear_solver=linear_solver)
629
+
630
+ # TODO : Remove `new_method` after 1.1 has been released.
631
+ def linearize(self, *, new_method=None, linear_solver='LU', **kwargs):
632
+ """ Linearize the equations of motion about a symbolic operating point.
633
+
634
+ Parameters
635
+ ==========
636
+ new_method
637
+ Deprecated, does nothing and will be removed.
638
+ linear_solver : str, callable
639
+ Method used to solve the several symbolic linear systems of the
640
+ form ``A*x=b`` in the linearization process. If a string is
641
+ supplied, it should be a valid method that can be used with the
642
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
643
+ supplied, it should have the format ``x = f(A, b)``, where it
644
+ solves the equations and returns the solution. The default is
645
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
646
+ ``LUsolve()`` is fast to compute but will often result in
647
+ divide-by-zero and thus ``nan`` results.
648
+ **kwargs
649
+ Extra keyword arguments are passed to
650
+ :meth:`sympy.physics.mechanics.linearize.Linearizer.linearize`.
651
+
652
+ Explanation
653
+ ===========
654
+
655
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
656
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
657
+
658
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
659
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
660
+ computationally intensive if there are many symbolic parameters. For
661
+ this reason, it may be more desirable to use the default A_and_B=False,
662
+ returning M, A, and B. Values may then be substituted in to these
663
+ matrices, and the state space form found as
664
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
665
+
666
+ In both cases, r is found as all dynamicsymbols in the equations of
667
+ motion that are not part of q, u, q', or u'. They are sorted in
668
+ canonical form.
669
+
670
+ The operating points may be also entered using the ``op_point`` kwarg.
671
+ This takes a dictionary of {symbol: value}, or a an iterable of such
672
+ dictionaries. The values may be numeric or symbolic. The more values
673
+ you can specify beforehand, the faster this computation will run.
674
+
675
+ For more documentation, please see the ``Linearizer`` class.
676
+
677
+ """
678
+
679
+ linearizer = self.to_linearizer(linear_solver=linear_solver)
680
+ result = linearizer.linearize(**kwargs)
681
+ return result + (linearizer.r,)
682
+
683
+ def kanes_equations(self, bodies=None, loads=None):
684
+ """ Method to form Kane's equations, Fr + Fr* = 0.
685
+
686
+ Explanation
687
+ ===========
688
+
689
+ Returns (Fr, Fr*). In the case where auxiliary generalized speeds are
690
+ present (say, s auxiliary speeds, o generalized speeds, and m motion
691
+ constraints) the length of the returned vectors will be o - m + s in
692
+ length. The first o - m equations will be the constrained Kane's
693
+ equations, then the s auxiliary Kane's equations. These auxiliary
694
+ equations can be accessed with the auxiliary_eqs property.
695
+
696
+ Parameters
697
+ ==========
698
+
699
+ bodies : iterable
700
+ An iterable of all RigidBody's and Particle's in the system.
701
+ A system must have at least one body.
702
+ loads : iterable
703
+ Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector)
704
+ tuples which represent the force at a point or torque on a frame.
705
+ Must be either a non-empty iterable of tuples or None which corresponds
706
+ to a system with no constraints.
707
+ """
708
+ if bodies is None:
709
+ bodies = self.bodies
710
+ if loads is None and self._forcelist is not None:
711
+ loads = self._forcelist
712
+ if loads == []:
713
+ loads = None
714
+ if not self._k_kqdot:
715
+ raise AttributeError('Create an instance of KanesMethod with '
716
+ 'kinematic differential equations to use this method.')
717
+ fr = self._form_fr(loads)
718
+ frstar = self._form_frstar(bodies)
719
+ if self._uaux:
720
+ if not self._udep:
721
+ km = KanesMethod(self._inertial, self.q, self._uaux,
722
+ u_auxiliary=self._uaux, constraint_solver=self._constraint_solver)
723
+ else:
724
+ km = KanesMethod(self._inertial, self.q, self._uaux,
725
+ u_auxiliary=self._uaux, u_dependent=self._udep,
726
+ velocity_constraints=(self._k_nh * self.u +
727
+ self._f_nh),
728
+ acceleration_constraints=(self._k_dnh * self._udot +
729
+ self._f_dnh),
730
+ constraint_solver=self._constraint_solver
731
+ )
732
+ km._qdot_u_map = self._qdot_u_map
733
+ self._km = km
734
+ fraux = km._form_fr(loads)
735
+ frstaraux = km._form_frstar(bodies)
736
+ self._aux_eq = fraux + frstaraux
737
+ self._fr = fr.col_join(fraux)
738
+ self._frstar = frstar.col_join(frstaraux)
739
+ return (self._fr, self._frstar)
740
+
741
+ def _form_eoms(self):
742
+ fr, frstar = self.kanes_equations(self.bodylist, self.forcelist)
743
+ return fr + frstar
744
+
745
+ def rhs(self, inv_method=None):
746
+ """Returns the system's equations of motion in first order form. The
747
+ output is the right hand side of::
748
+
749
+ x' = |q'| =: f(q, u, r, p, t)
750
+ |u'|
751
+
752
+ The right hand side is what is needed by most numerical ODE
753
+ integrators.
754
+
755
+ Parameters
756
+ ==========
757
+
758
+ inv_method : str
759
+ The specific sympy inverse matrix calculation method to use. For a
760
+ list of valid methods, see
761
+ :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
762
+
763
+ """
764
+ rhs = zeros(len(self.q) + len(self.u), 1)
765
+ kdes = self.kindiffdict()
766
+ for i, q_i in enumerate(self.q):
767
+ rhs[i] = kdes[q_i.diff()]
768
+
769
+ if inv_method is None:
770
+ rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing)
771
+ else:
772
+ rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method,
773
+ try_block_diag=True) *
774
+ self.forcing)
775
+
776
+ return rhs
777
+
778
+ def kindiffdict(self):
779
+ """Returns a dictionary mapping q' to u."""
780
+ if not self._qdot_u_map:
781
+ raise AttributeError('Create an instance of KanesMethod with '
782
+ 'kinematic differential equations to use this method.')
783
+ return self._qdot_u_map
784
+
785
+ @property
786
+ def auxiliary_eqs(self):
787
+ """A matrix containing the auxiliary equations."""
788
+ if not self._fr or not self._frstar:
789
+ raise ValueError('Need to compute Fr, Fr* first.')
790
+ if not self._uaux:
791
+ raise ValueError('No auxiliary speeds have been declared.')
792
+ return self._aux_eq
793
+
794
+ @property
795
+ def mass_matrix_kin(self):
796
+ r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system."""
797
+ return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit
798
+
799
+ @property
800
+ def forcing_kin(self):
801
+ """The kinematic "forcing vector" of the system."""
802
+ if self.explicit_kinematics:
803
+ return -(self._k_ku * Matrix(self.u) + self._f_k)
804
+ else:
805
+ return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit)
806
+
807
+ @property
808
+ def mass_matrix(self):
809
+ """The mass matrix of the system."""
810
+ if not self._fr or not self._frstar:
811
+ raise ValueError('Need to compute Fr, Fr* first.')
812
+ return Matrix([self._k_d, self._k_dnh])
813
+
814
+ @property
815
+ def forcing(self):
816
+ """The forcing vector of the system."""
817
+ if not self._fr or not self._frstar:
818
+ raise ValueError('Need to compute Fr, Fr* first.')
819
+ return -Matrix([self._f_d, self._f_dnh])
820
+
821
+ @property
822
+ def mass_matrix_full(self):
823
+ """The mass matrix of the system, augmented by the kinematic
824
+ differential equations in explicit or implicit form."""
825
+ if not self._fr or not self._frstar:
826
+ raise ValueError('Need to compute Fr, Fr* first.')
827
+ o, n = len(self.u), len(self.q)
828
+ return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join(
829
+ zeros(o, n).row_join(self.mass_matrix))
830
+
831
+ @property
832
+ def forcing_full(self):
833
+ """The forcing vector of the system, augmented by the kinematic
834
+ differential equations in explicit or implicit form."""
835
+ return Matrix([self.forcing_kin, self.forcing])
836
+
837
+ @property
838
+ def q(self):
839
+ return self._q
840
+
841
+ @property
842
+ def u(self):
843
+ return self._u
844
+
845
+ @property
846
+ def bodylist(self):
847
+ return self._bodylist
848
+
849
+ @property
850
+ def forcelist(self):
851
+ return self._forcelist
852
+
853
+ @property
854
+ def bodies(self):
855
+ return self._bodylist
856
+
857
+ @property
858
+ def loads(self):
859
+ return self._forcelist
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import diff, zeros, Matrix, eye, sympify
2
+ from sympy.core.sorting import default_sort_key
3
+ from sympy.physics.vector import dynamicsymbols, ReferenceFrame
4
+ from sympy.physics.mechanics.method import _Methods
5
+ from sympy.physics.mechanics.functions import (
6
+ find_dynamicsymbols, msubs, _f_list_parser, _validate_coordinates)
7
+ from sympy.physics.mechanics.linearize import Linearizer
8
+ from sympy.utilities.iterables import iterable
9
+
10
+ __all__ = ['LagrangesMethod']
11
+
12
+
13
+ class LagrangesMethod(_Methods):
14
+ """Lagrange's method object.
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ This object generates the equations of motion in a two step procedure. The
20
+ first step involves the initialization of LagrangesMethod by supplying the
21
+ Lagrangian and the generalized coordinates, at the bare minimum. If there
22
+ are any constraint equations, they can be supplied as keyword arguments.
23
+ The Lagrange multipliers are automatically generated and are equal in
24
+ number to the constraint equations. Similarly any non-conservative forces
25
+ can be supplied in an iterable (as described below and also shown in the
26
+ example) along with a ReferenceFrame. This is also discussed further in the
27
+ __init__ method.
28
+
29
+ Attributes
30
+ ==========
31
+
32
+ q, u : Matrix
33
+ Matrices of the generalized coordinates and speeds
34
+ loads : iterable
35
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
36
+ describing the forces on the system.
37
+ bodies : iterable
38
+ Iterable containing the rigid bodies and particles of the system.
39
+ mass_matrix : Matrix
40
+ The system's mass matrix
41
+ forcing : Matrix
42
+ The system's forcing vector
43
+ mass_matrix_full : Matrix
44
+ The "mass matrix" for the qdot's, qdoubledot's, and the
45
+ lagrange multipliers (lam)
46
+ forcing_full : Matrix
47
+ The forcing vector for the qdot's, qdoubledot's and
48
+ lagrange multipliers (lam)
49
+
50
+ Examples
51
+ ========
52
+
53
+ This is a simple example for a one degree of freedom translational
54
+ spring-mass-damper.
55
+
56
+ In this example, we first need to do the kinematics.
57
+ This involves creating generalized coordinates and their derivatives.
58
+ Then we create a point and set its velocity in a frame.
59
+
60
+ >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian
61
+ >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point
62
+ >>> from sympy.physics.mechanics import dynamicsymbols
63
+ >>> from sympy import symbols
64
+ >>> q = dynamicsymbols('q')
65
+ >>> qd = dynamicsymbols('q', 1)
66
+ >>> m, k, b = symbols('m k b')
67
+ >>> N = ReferenceFrame('N')
68
+ >>> P = Point('P')
69
+ >>> P.set_vel(N, qd * N.x)
70
+
71
+ We need to then prepare the information as required by LagrangesMethod to
72
+ generate equations of motion.
73
+ First we create the Particle, which has a point attached to it.
74
+ Following this the lagrangian is created from the kinetic and potential
75
+ energies.
76
+ Then, an iterable of nonconservative forces/torques must be constructed,
77
+ where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple,
78
+ with the Vectors representing the nonconservative forces or torques.
79
+
80
+ >>> Pa = Particle('Pa', P, m)
81
+ >>> Pa.potential_energy = k * q**2 / 2.0
82
+ >>> L = Lagrangian(N, Pa)
83
+ >>> fl = [(P, -b * qd * N.x)]
84
+
85
+ Finally we can generate the equations of motion.
86
+ First we create the LagrangesMethod object. To do this one must supply
87
+ the Lagrangian, and the generalized coordinates. The constraint equations,
88
+ the forcelist, and the inertial frame may also be provided, if relevant.
89
+ Next we generate Lagrange's equations of motion, such that:
90
+ Lagrange's equations of motion = 0.
91
+ We have the equations of motion at this point.
92
+
93
+ >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N)
94
+ >>> print(l.form_lagranges_equations())
95
+ Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]])
96
+
97
+ We can also solve for the states using the 'rhs' method.
98
+
99
+ >>> print(l.rhs())
100
+ Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]])
101
+
102
+ Please refer to the docstrings on each method for more details.
103
+ """
104
+
105
+ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None,
106
+ hol_coneqs=None, nonhol_coneqs=None):
107
+ """Supply the following for the initialization of LagrangesMethod.
108
+
109
+ Lagrangian : Sympifyable
110
+
111
+ qs : array_like
112
+ The generalized coordinates
113
+
114
+ hol_coneqs : array_like, optional
115
+ The holonomic constraint equations
116
+
117
+ nonhol_coneqs : array_like, optional
118
+ The nonholonomic constraint equations
119
+
120
+ forcelist : iterable, optional
121
+ Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector)
122
+ tuples which represent the force at a point or torque on a frame.
123
+ This feature is primarily to account for the nonconservative forces
124
+ and/or moments.
125
+
126
+ bodies : iterable, optional
127
+ Takes an iterable containing the rigid bodies and particles of the
128
+ system.
129
+
130
+ frame : ReferenceFrame, optional
131
+ Supply the inertial frame. This is used to determine the
132
+ generalized forces due to non-conservative forces.
133
+ """
134
+
135
+ self._L = Matrix([sympify(Lagrangian)])
136
+ self.eom = None
137
+ self._m_cd = Matrix() # Mass Matrix of differentiated coneqs
138
+ self._m_d = Matrix() # Mass Matrix of dynamic equations
139
+ self._f_cd = Matrix() # Forcing part of the diff coneqs
140
+ self._f_d = Matrix() # Forcing part of the dynamic equations
141
+ self.lam_coeffs = Matrix() # The coeffecients of the multipliers
142
+
143
+ forcelist = forcelist if forcelist else []
144
+ if not iterable(forcelist):
145
+ raise TypeError('Force pairs must be supplied in an iterable.')
146
+ self._forcelist = forcelist
147
+ if frame and not isinstance(frame, ReferenceFrame):
148
+ raise TypeError('frame must be a valid ReferenceFrame')
149
+ self._bodies = bodies
150
+ self.inertial = frame
151
+
152
+ self.lam_vec = Matrix()
153
+
154
+ self._term1 = Matrix()
155
+ self._term2 = Matrix()
156
+ self._term3 = Matrix()
157
+ self._term4 = Matrix()
158
+
159
+ # Creating the qs, qdots and qdoubledots
160
+ if not iterable(qs):
161
+ raise TypeError('Generalized coordinates must be an iterable')
162
+ self._q = Matrix(qs)
163
+ self._qdots = self.q.diff(dynamicsymbols._t)
164
+ self._qdoubledots = self._qdots.diff(dynamicsymbols._t)
165
+ _validate_coordinates(self.q)
166
+
167
+ mat_build = lambda x: Matrix(x) if x else Matrix()
168
+ hol_coneqs = mat_build(hol_coneqs)
169
+ nonhol_coneqs = mat_build(nonhol_coneqs)
170
+ self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t),
171
+ nonhol_coneqs])
172
+ self._hol_coneqs = hol_coneqs
173
+
174
+ def form_lagranges_equations(self):
175
+ """Method to form Lagrange's equations of motion.
176
+
177
+ Returns a vector of equations of motion using Lagrange's equations of
178
+ the second kind.
179
+ """
180
+
181
+ qds = self._qdots
182
+ qdd_zero = dict.fromkeys(self._qdoubledots, 0)
183
+ n = len(self.q)
184
+
185
+ # Internally we represent the EOM as four terms:
186
+ # EOM = term1 - term2 - term3 - term4 = 0
187
+
188
+ # First term
189
+ self._term1 = self._L.jacobian(qds)
190
+ self._term1 = self._term1.diff(dynamicsymbols._t).T
191
+
192
+ # Second term
193
+ self._term2 = self._L.jacobian(self.q).T
194
+
195
+ # Third term
196
+ if self.coneqs:
197
+ coneqs = self.coneqs
198
+ m = len(coneqs)
199
+ # Creating the multipliers
200
+ self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1)))
201
+ self.lam_coeffs = -coneqs.jacobian(qds)
202
+ self._term3 = self.lam_coeffs.T * self.lam_vec
203
+ # Extracting the coeffecients of the qdds from the diff coneqs
204
+ diffconeqs = coneqs.diff(dynamicsymbols._t)
205
+ self._m_cd = diffconeqs.jacobian(self._qdoubledots)
206
+ # The remaining terms i.e. the 'forcing' terms in diff coneqs
207
+ self._f_cd = -diffconeqs.subs(qdd_zero)
208
+ else:
209
+ self._term3 = zeros(n, 1)
210
+
211
+ # Fourth term
212
+ if self.forcelist:
213
+ N = self.inertial
214
+ self._term4 = zeros(n, 1)
215
+ for i, qd in enumerate(qds):
216
+ flist = zip(*_f_list_parser(self.forcelist, N))
217
+ self._term4[i] = sum(v.diff(qd, N).dot(f) for (v, f) in flist)
218
+ else:
219
+ self._term4 = zeros(n, 1)
220
+
221
+ # Form the dynamic mass and forcing matrices
222
+ without_lam = self._term1 - self._term2 - self._term4
223
+ self._m_d = without_lam.jacobian(self._qdoubledots)
224
+ self._f_d = -without_lam.subs(qdd_zero)
225
+
226
+ # Form the EOM
227
+ self.eom = without_lam - self._term3
228
+ return self.eom
229
+
230
+ def _form_eoms(self):
231
+ return self.form_lagranges_equations()
232
+
233
+ @property
234
+ def mass_matrix(self):
235
+ """Returns the mass matrix, which is augmented by the Lagrange
236
+ multipliers, if necessary.
237
+
238
+ Explanation
239
+ ===========
240
+
241
+ If the system is described by 'n' generalized coordinates and there are
242
+ no constraint equations then an n X n matrix is returned.
243
+
244
+ If there are 'n' generalized coordinates and 'm' constraint equations
245
+ have been supplied during initialization then an n X (n+m) matrix is
246
+ returned. The (n + m - 1)th and (n + m)th columns contain the
247
+ coefficients of the Lagrange multipliers.
248
+ """
249
+
250
+ if self.eom is None:
251
+ raise ValueError('Need to compute the equations of motion first')
252
+ if self.coneqs:
253
+ return (self._m_d).row_join(self.lam_coeffs.T)
254
+ else:
255
+ return self._m_d
256
+
257
+ @property
258
+ def mass_matrix_full(self):
259
+ """Augments the coefficients of qdots to the mass_matrix."""
260
+
261
+ if self.eom is None:
262
+ raise ValueError('Need to compute the equations of motion first')
263
+ n = len(self.q)
264
+ m = len(self.coneqs)
265
+ row1 = eye(n).row_join(zeros(n, n + m))
266
+ row2 = zeros(n, n).row_join(self.mass_matrix)
267
+ if self.coneqs:
268
+ row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m))
269
+ return row1.col_join(row2).col_join(row3)
270
+ else:
271
+ return row1.col_join(row2)
272
+
273
+ @property
274
+ def forcing(self):
275
+ """Returns the forcing vector from 'lagranges_equations' method."""
276
+
277
+ if self.eom is None:
278
+ raise ValueError('Need to compute the equations of motion first')
279
+ return self._f_d
280
+
281
+ @property
282
+ def forcing_full(self):
283
+ """Augments qdots to the forcing vector above."""
284
+
285
+ if self.eom is None:
286
+ raise ValueError('Need to compute the equations of motion first')
287
+ if self.coneqs:
288
+ return self._qdots.col_join(self.forcing).col_join(self._f_cd)
289
+ else:
290
+ return self._qdots.col_join(self.forcing)
291
+
292
+ def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None,
293
+ linear_solver='LU'):
294
+ """Returns an instance of the Linearizer class, initiated from the data
295
+ in the LagrangesMethod class. This may be more desirable than using the
296
+ linearize class method, as the Linearizer object will allow more
297
+ efficient recalculation (i.e. about varying operating points).
298
+
299
+ Parameters
300
+ ==========
301
+
302
+ q_ind, qd_ind : array_like, optional
303
+ The independent generalized coordinates and speeds.
304
+ q_dep, qd_dep : array_like, optional
305
+ The dependent generalized coordinates and speeds.
306
+ linear_solver : str, callable
307
+ Method used to solve the several symbolic linear systems of the
308
+ form ``A*x=b`` in the linearization process. If a string is
309
+ supplied, it should be a valid method that can be used with the
310
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
311
+ supplied, it should have the format ``x = f(A, b)``, where it
312
+ solves the equations and returns the solution. The default is
313
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
314
+ ``LUsolve()`` is fast to compute but will often result in
315
+ divide-by-zero and thus ``nan`` results.
316
+
317
+ Returns
318
+ =======
319
+ Linearizer
320
+ An instantiated
321
+ :class:`sympy.physics.mechanics.linearize.Linearizer`.
322
+
323
+ """
324
+
325
+ # Compose vectors
326
+ t = dynamicsymbols._t
327
+ q = self.q
328
+ u = self._qdots
329
+ ud = u.diff(t)
330
+ # Get vector of lagrange multipliers
331
+ lams = self.lam_vec
332
+
333
+ mat_build = lambda x: Matrix(x) if x else Matrix()
334
+ q_i = mat_build(q_ind)
335
+ q_d = mat_build(q_dep)
336
+ u_i = mat_build(qd_ind)
337
+ u_d = mat_build(qd_dep)
338
+
339
+ # Compose general form equations
340
+ f_c = self._hol_coneqs
341
+ f_v = self.coneqs
342
+ f_a = f_v.diff(t)
343
+ f_0 = u
344
+ f_1 = -u
345
+ f_2 = self._term1
346
+ f_3 = -(self._term2 + self._term4)
347
+ f_4 = -self._term3
348
+
349
+ # Check that there are an appropriate number of independent and
350
+ # dependent coordinates
351
+ if len(q_d) != len(f_c) or len(u_d) != len(f_v):
352
+ raise ValueError(("Must supply {:} dependent coordinates, and " +
353
+ "{:} dependent speeds").format(len(f_c), len(f_v)))
354
+ if set(Matrix([q_i, q_d])) != set(q):
355
+ raise ValueError("Must partition q into q_ind and q_dep, with " +
356
+ "no extra or missing symbols.")
357
+ if set(Matrix([u_i, u_d])) != set(u):
358
+ raise ValueError("Must partition qd into qd_ind and qd_dep, " +
359
+ "with no extra or missing symbols.")
360
+
361
+ # Find all other dynamic symbols, forming the forcing vector r.
362
+ # Sort r to make it canonical.
363
+ insyms = set(Matrix([q, u, ud, lams]))
364
+ r = list(find_dynamicsymbols(f_3, insyms))
365
+ r.sort(key=default_sort_key)
366
+ # Check for any derivatives of variables in r that are also found in r.
367
+ for i in r:
368
+ if diff(i, dynamicsymbols._t) in r:
369
+ raise ValueError('Cannot have derivatives of specified \
370
+ quantities when linearizing forcing terms.')
371
+
372
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
373
+ q_d, u_i, u_d, r, lams, linear_solver=linear_solver)
374
+
375
+ def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None,
376
+ linear_solver='LU', **kwargs):
377
+ """Linearize the equations of motion about a symbolic operating point.
378
+
379
+ Parameters
380
+ ==========
381
+ linear_solver : str, callable
382
+ Method used to solve the several symbolic linear systems of the
383
+ form ``A*x=b`` in the linearization process. If a string is
384
+ supplied, it should be a valid method that can be used with the
385
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
386
+ supplied, it should have the format ``x = f(A, b)``, where it
387
+ solves the equations and returns the solution. The default is
388
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
389
+ ``LUsolve()`` is fast to compute but will often result in
390
+ divide-by-zero and thus ``nan`` results.
391
+ **kwargs
392
+ Extra keyword arguments are passed to
393
+ :meth:`sympy.physics.mechanics.linearize.Linearizer.linearize`.
394
+
395
+ Explanation
396
+ ===========
397
+
398
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
399
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
400
+
401
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
402
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
403
+ computationally intensive if there are many symbolic parameters. For
404
+ this reason, it may be more desirable to use the default A_and_B=False,
405
+ returning M, A, and B. Values may then be substituted in to these
406
+ matrices, and the state space form found as
407
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
408
+
409
+ In both cases, r is found as all dynamicsymbols in the equations of
410
+ motion that are not part of q, u, q', or u'. They are sorted in
411
+ canonical form.
412
+
413
+ The operating points may be also entered using the ``op_point`` kwarg.
414
+ This takes a dictionary of {symbol: value}, or a an iterable of such
415
+ dictionaries. The values may be numeric or symbolic. The more values
416
+ you can specify beforehand, the faster this computation will run.
417
+
418
+ For more documentation, please see the ``Linearizer`` class."""
419
+
420
+ linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep,
421
+ linear_solver=linear_solver)
422
+ result = linearizer.linearize(**kwargs)
423
+ return result + (linearizer.r,)
424
+
425
+ def solve_multipliers(self, op_point=None, sol_type='dict'):
426
+ """Solves for the values of the lagrange multipliers symbolically at
427
+ the specified operating point.
428
+
429
+ Parameters
430
+ ==========
431
+
432
+ op_point : dict or iterable of dicts, optional
433
+ Point at which to solve at. The operating point is specified as
434
+ a dictionary or iterable of dictionaries of {symbol: value}. The
435
+ value may be numeric or symbolic itself.
436
+
437
+ sol_type : str, optional
438
+ Solution return type. Valid options are:
439
+ - 'dict': A dict of {symbol : value} (default)
440
+ - 'Matrix': An ordered column matrix of the solution
441
+ """
442
+
443
+ # Determine number of multipliers
444
+ k = len(self.lam_vec)
445
+ if k == 0:
446
+ raise ValueError("System has no lagrange multipliers to solve for.")
447
+ # Compose dict of operating conditions
448
+ if isinstance(op_point, dict):
449
+ op_point_dict = op_point
450
+ elif iterable(op_point):
451
+ op_point_dict = {}
452
+ for op in op_point:
453
+ op_point_dict.update(op)
454
+ elif op_point is None:
455
+ op_point_dict = {}
456
+ else:
457
+ raise TypeError("op_point must be either a dictionary or an "
458
+ "iterable of dictionaries.")
459
+ # Compose the system to be solved
460
+ mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join(
461
+ zeros(k, k)))
462
+ force_matrix = self.forcing.col_join(self._f_cd)
463
+ # Sub in the operating point
464
+ mass_matrix = msubs(mass_matrix, op_point_dict)
465
+ force_matrix = msubs(force_matrix, op_point_dict)
466
+ # Solve for the multipliers
467
+ sol_list = mass_matrix.LUsolve(-force_matrix)[-k:]
468
+ if sol_type == 'dict':
469
+ return dict(zip(self.lam_vec, sol_list))
470
+ elif sol_type == 'Matrix':
471
+ return Matrix(sol_list)
472
+ else:
473
+ raise ValueError("Unknown sol_type {:}.".format(sol_type))
474
+
475
+ def rhs(self, inv_method=None, **kwargs):
476
+ """Returns equations that can be solved numerically.
477
+
478
+ Parameters
479
+ ==========
480
+
481
+ inv_method : str
482
+ The specific sympy inverse matrix calculation method to use. For a
483
+ list of valid methods, see
484
+ :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
485
+ """
486
+
487
+ if inv_method is None:
488
+ self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full)
489
+ else:
490
+ self._rhs = (self.mass_matrix_full.inv(inv_method,
491
+ try_block_diag=True) * self.forcing_full)
492
+ return self._rhs
493
+
494
+ @property
495
+ def q(self):
496
+ return self._q
497
+
498
+ @property
499
+ def u(self):
500
+ return self._qdots
501
+
502
+ @property
503
+ def bodies(self):
504
+ return self._bodies
505
+
506
+ @property
507
+ def forcelist(self):
508
+ return self._forcelist
509
+
510
+ @property
511
+ def loads(self):
512
+ return self._forcelist
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['Linearizer']
2
+
3
+ from sympy import Matrix, eye, zeros
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.utilities.iterables import flatten
6
+ from sympy.physics.vector import dynamicsymbols
7
+ from sympy.physics.mechanics.functions import msubs, _parse_linear_solver
8
+
9
+ from collections import namedtuple
10
+ from collections.abc import Iterable
11
+
12
+
13
+ class Linearizer:
14
+ """This object holds the general model form for a dynamic system. This
15
+ model is used for computing the linearized form of the system, while
16
+ properly dealing with constraints leading to dependent coordinates and
17
+ speeds. The notation and method is described in [1]_.
18
+
19
+ Attributes
20
+ ==========
21
+
22
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
23
+ Matrices holding the general system form.
24
+ q, u, r : Matrix
25
+ Matrices holding the generalized coordinates, speeds, and
26
+ input vectors.
27
+ q_i, u_i : Matrix
28
+ Matrices of the independent generalized coordinates and speeds.
29
+ q_d, u_d : Matrix
30
+ Matrices of the dependent generalized coordinates and speeds.
31
+ perm_mat : Matrix
32
+ Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
33
+
34
+ References
35
+ ==========
36
+
37
+ .. [1] D. L. Peterson, G. Gede, and M. Hubbard, "Symbolic linearization of
38
+ equations of motion of constrained multibody systems," Multibody
39
+ Syst Dyn, vol. 33, no. 2, pp. 143-161, Feb. 2015, doi:
40
+ 10.1007/s11044-014-9436-5.
41
+
42
+ """
43
+
44
+ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None,
45
+ q_d=None, u_i=None, u_d=None, r=None, lams=None,
46
+ linear_solver='LU'):
47
+ """
48
+ Parameters
49
+ ==========
50
+
51
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
52
+ System of equations holding the general system form.
53
+ Supply empty array or Matrix if the parameter
54
+ does not exist.
55
+ q : array_like
56
+ The generalized coordinates.
57
+ u : array_like
58
+ The generalized speeds
59
+ q_i, u_i : array_like, optional
60
+ The independent generalized coordinates and speeds.
61
+ q_d, u_d : array_like, optional
62
+ The dependent generalized coordinates and speeds.
63
+ r : array_like, optional
64
+ The input variables.
65
+ lams : array_like, optional
66
+ The lagrange multipliers
67
+ linear_solver : str, callable
68
+ Method used to solve the several symbolic linear systems of the
69
+ form ``A*x=b`` in the linearization process. If a string is
70
+ supplied, it should be a valid method that can be used with the
71
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
72
+ supplied, it should have the format ``x = f(A, b)``, where it
73
+ solves the equations and returns the solution. The default is
74
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
75
+ ``LUsolve()`` is fast to compute but will often result in
76
+ divide-by-zero and thus ``nan`` results.
77
+
78
+ """
79
+ self.linear_solver = _parse_linear_solver(linear_solver)
80
+
81
+ # Generalized equation form
82
+ self.f_0 = Matrix(f_0)
83
+ self.f_1 = Matrix(f_1)
84
+ self.f_2 = Matrix(f_2)
85
+ self.f_3 = Matrix(f_3)
86
+ self.f_4 = Matrix(f_4)
87
+ self.f_c = Matrix(f_c)
88
+ self.f_v = Matrix(f_v)
89
+ self.f_a = Matrix(f_a)
90
+
91
+ # Generalized equation variables
92
+ self.q = Matrix(q)
93
+ self.u = Matrix(u)
94
+ none_handler = lambda x: Matrix(x) if x else Matrix()
95
+ self.q_i = none_handler(q_i)
96
+ self.q_d = none_handler(q_d)
97
+ self.u_i = none_handler(u_i)
98
+ self.u_d = none_handler(u_d)
99
+ self.r = none_handler(r)
100
+ self.lams = none_handler(lams)
101
+
102
+ # Derivatives of generalized equation variables
103
+ self._qd = self.q.diff(dynamicsymbols._t)
104
+ self._ud = self.u.diff(dynamicsymbols._t)
105
+ # If the user doesn't actually use generalized variables, and the
106
+ # qd and u vectors have any intersecting variables, this can cause
107
+ # problems. We'll fix this with some hackery, and Dummy variables
108
+ dup_vars = set(self._qd).intersection(self.u)
109
+ self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var
110
+ in self._qd])
111
+
112
+ # Derive dimension terms
113
+ l = len(self.f_c)
114
+ m = len(self.f_v)
115
+ n = len(self.q)
116
+ o = len(self.u)
117
+ s = len(self.r)
118
+ k = len(self.lams)
119
+ dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
120
+ self._dims = dims(l, m, n, o, s, k)
121
+
122
+ self._Pq = None
123
+ self._Pqi = None
124
+ self._Pqd = None
125
+ self._Pu = None
126
+ self._Pui = None
127
+ self._Pud = None
128
+ self._C_0 = None
129
+ self._C_1 = None
130
+ self._C_2 = None
131
+ self.perm_mat = None
132
+
133
+ self._setup_done = False
134
+
135
+ def _setup(self):
136
+ # Calculations here only need to be run once. They are moved out of
137
+ # the __init__ method to increase the speed of Linearizer creation.
138
+ self._form_permutation_matrices()
139
+ self._form_block_matrices()
140
+ self._form_coefficient_matrices()
141
+ self._setup_done = True
142
+
143
+ def _form_permutation_matrices(self):
144
+ """Form the permutation matrices Pq and Pu."""
145
+
146
+ # Extract dimension variables
147
+ l, m, n, o, s, k = self._dims
148
+ # Compute permutation matrices
149
+ if n != 0:
150
+ self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
151
+ if l > 0:
152
+ self._Pqi = self._Pq[:, :-l]
153
+ self._Pqd = self._Pq[:, -l:]
154
+ else:
155
+ self._Pqi = self._Pq
156
+ self._Pqd = Matrix()
157
+ if o != 0:
158
+ self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
159
+ if m > 0:
160
+ self._Pui = self._Pu[:, :-m]
161
+ self._Pud = self._Pu[:, -m:]
162
+ else:
163
+ self._Pui = self._Pu
164
+ self._Pud = Matrix()
165
+ # Compute combination permutation matrix for computing A and B
166
+ P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
167
+ P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
168
+ if P_col1:
169
+ if P_col2:
170
+ self.perm_mat = P_col1.row_join(P_col2)
171
+ else:
172
+ self.perm_mat = P_col1
173
+ else:
174
+ self.perm_mat = P_col2
175
+
176
+ def _form_coefficient_matrices(self):
177
+ """Form the coefficient matrices C_0, C_1, and C_2."""
178
+
179
+ # Extract dimension variables
180
+ l, m, n, o, s, k = self._dims
181
+ # Build up the coefficient matrices C_0, C_1, and C_2
182
+ # If there are configuration constraints (l > 0), form C_0 as normal.
183
+ # If not, C_0 is I_(nxn). Note that this works even if n=0
184
+ if l > 0:
185
+ f_c_jac_q = self.f_c.jacobian(self.q)
186
+ self._C_0 = (eye(n) - self._Pqd *
187
+ self.linear_solver(f_c_jac_q*self._Pqd,
188
+ f_c_jac_q))*self._Pqi
189
+ else:
190
+ self._C_0 = eye(n)
191
+ # If there are motion constraints (m > 0), form C_1 and C_2 as normal.
192
+ # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
193
+ # o = 0.
194
+ if m > 0:
195
+ f_v_jac_u = self.f_v.jacobian(self.u)
196
+ temp = f_v_jac_u * self._Pud
197
+ if n != 0:
198
+ f_v_jac_q = self.f_v.jacobian(self.q)
199
+ self._C_1 = -self._Pud * self.linear_solver(temp, f_v_jac_q)
200
+ else:
201
+ self._C_1 = zeros(o, n)
202
+ self._C_2 = (eye(o) - self._Pud *
203
+ self.linear_solver(temp, f_v_jac_u))*self._Pui
204
+ else:
205
+ self._C_1 = zeros(o, n)
206
+ self._C_2 = eye(o)
207
+
208
+ def _form_block_matrices(self):
209
+ """Form the block matrices for composing M, A, and B."""
210
+
211
+ # Extract dimension variables
212
+ l, m, n, o, s, k = self._dims
213
+ # Block Matrix Definitions. These are only defined if under certain
214
+ # conditions. If undefined, an empty matrix is used instead
215
+ if n != 0:
216
+ self._M_qq = self.f_0.jacobian(self._qd)
217
+ self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
218
+ else:
219
+ self._M_qq = Matrix()
220
+ self._A_qq = Matrix()
221
+ if n != 0 and m != 0:
222
+ self._M_uqc = self.f_a.jacobian(self._qd_dup)
223
+ self._A_uqc = -self.f_a.jacobian(self.q)
224
+ else:
225
+ self._M_uqc = Matrix()
226
+ self._A_uqc = Matrix()
227
+ if n != 0 and o - m + k != 0:
228
+ self._M_uqd = self.f_3.jacobian(self._qd_dup)
229
+ self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
230
+ else:
231
+ self._M_uqd = Matrix()
232
+ self._A_uqd = Matrix()
233
+ if o != 0 and m != 0:
234
+ self._M_uuc = self.f_a.jacobian(self._ud)
235
+ self._A_uuc = -self.f_a.jacobian(self.u)
236
+ else:
237
+ self._M_uuc = Matrix()
238
+ self._A_uuc = Matrix()
239
+ if o != 0 and o - m + k != 0:
240
+ self._M_uud = self.f_2.jacobian(self._ud)
241
+ self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
242
+ else:
243
+ self._M_uud = Matrix()
244
+ self._A_uud = Matrix()
245
+ if o != 0 and n != 0:
246
+ self._A_qu = -self.f_1.jacobian(self.u)
247
+ else:
248
+ self._A_qu = Matrix()
249
+ if k != 0 and o - m + k != 0:
250
+ self._M_uld = self.f_4.jacobian(self.lams)
251
+ else:
252
+ self._M_uld = Matrix()
253
+ if s != 0 and o - m + k != 0:
254
+ self._B_u = -self.f_3.jacobian(self.r)
255
+ else:
256
+ self._B_u = Matrix()
257
+
258
+ def linearize(self, op_point=None, A_and_B=False, simplify=False):
259
+ """Linearize the system about the operating point. Note that
260
+ q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
261
+ These may be either symbolic or numeric.
262
+
263
+ Parameters
264
+ ==========
265
+ op_point : dict or iterable of dicts, optional
266
+ Dictionary or iterable of dictionaries containing the operating
267
+ point conditions for all or a subset of the generalized
268
+ coordinates, generalized speeds, and time derivatives of the
269
+ generalized speeds. These will be substituted into the linearized
270
+ system before the linearization is complete. Leave set to ``None``
271
+ if you want the operating point to be an arbitrary set of symbols.
272
+ Note that any reduction in symbols (whether substituted for numbers
273
+ or expressions with a common parameter) will result in faster
274
+ runtime.
275
+ A_and_B : bool, optional
276
+ If A_and_B=False (default), (M, A, B) is returned and of
277
+ A_and_B=True, (A, B) is returned. See below.
278
+ simplify : bool, optional
279
+ Determines if returned values are simplified before return.
280
+ For large expressions this may be time consuming. Default is False.
281
+
282
+ Returns
283
+ =======
284
+ M, A, B : Matrices, ``A_and_B=False``
285
+ Matrices from the implicit form:
286
+ ``[M]*[q', u']^T = [A]*[q_ind, u_ind]^T + [B]*r``
287
+ A, B : Matrices, ``A_and_B=True``
288
+ Matrices from the explicit form:
289
+ ``[q_ind', u_ind']^T = [A]*[q_ind, u_ind]^T + [B]*r``
290
+
291
+ Notes
292
+ =====
293
+
294
+ Note that the process of solving with A_and_B=True is computationally
295
+ intensive if there are many symbolic parameters. For this reason, it
296
+ may be more desirable to use the default A_and_B=False, returning M, A,
297
+ and B. More values may then be substituted in to these matrices later
298
+ on. The state space form can then be found as A = P.T*M.LUsolve(A), B =
299
+ P.T*M.LUsolve(B), where P = Linearizer.perm_mat.
300
+
301
+ """
302
+
303
+ # Run the setup if needed:
304
+ if not self._setup_done:
305
+ self._setup()
306
+
307
+ # Compose dict of operating conditions
308
+ if isinstance(op_point, dict):
309
+ op_point_dict = op_point
310
+ elif isinstance(op_point, Iterable):
311
+ op_point_dict = {}
312
+ for op in op_point:
313
+ op_point_dict.update(op)
314
+ else:
315
+ op_point_dict = {}
316
+
317
+ # Extract dimension variables
318
+ l, m, n, o, s, k = self._dims
319
+
320
+ # Rename terms to shorten expressions
321
+ M_qq = self._M_qq
322
+ M_uqc = self._M_uqc
323
+ M_uqd = self._M_uqd
324
+ M_uuc = self._M_uuc
325
+ M_uud = self._M_uud
326
+ M_uld = self._M_uld
327
+ A_qq = self._A_qq
328
+ A_uqc = self._A_uqc
329
+ A_uqd = self._A_uqd
330
+ A_qu = self._A_qu
331
+ A_uuc = self._A_uuc
332
+ A_uud = self._A_uud
333
+ B_u = self._B_u
334
+ C_0 = self._C_0
335
+ C_1 = self._C_1
336
+ C_2 = self._C_2
337
+
338
+ # Build up Mass Matrix
339
+ # |M_qq 0_nxo 0_nxk|
340
+ # M = |M_uqc M_uuc 0_mxk|
341
+ # |M_uqd M_uud M_uld|
342
+ if o != 0:
343
+ col2 = Matrix([zeros(n, o), M_uuc, M_uud])
344
+ if k != 0:
345
+ col3 = Matrix([zeros(n + m, k), M_uld])
346
+ if n != 0:
347
+ col1 = Matrix([M_qq, M_uqc, M_uqd])
348
+ if o != 0 and k != 0:
349
+ M = col1.row_join(col2).row_join(col3)
350
+ elif o != 0:
351
+ M = col1.row_join(col2)
352
+ else:
353
+ M = col1
354
+ elif k != 0:
355
+ M = col2.row_join(col3)
356
+ else:
357
+ M = col2
358
+ M_eq = msubs(M, op_point_dict)
359
+
360
+ # Build up state coefficient matrix A
361
+ # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
362
+ # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
363
+ # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
364
+ # Col 1 is only defined if n != 0
365
+ if n != 0:
366
+ r1c1 = A_qq
367
+ if o != 0:
368
+ r1c1 += (A_qu * C_1)
369
+ r1c1 = r1c1 * C_0
370
+ if m != 0:
371
+ r2c1 = A_uqc
372
+ if o != 0:
373
+ r2c1 += (A_uuc * C_1)
374
+ r2c1 = r2c1 * C_0
375
+ else:
376
+ r2c1 = Matrix()
377
+ if o - m + k != 0:
378
+ r3c1 = A_uqd
379
+ if o != 0:
380
+ r3c1 += (A_uud * C_1)
381
+ r3c1 = r3c1 * C_0
382
+ else:
383
+ r3c1 = Matrix()
384
+ col1 = Matrix([r1c1, r2c1, r3c1])
385
+ else:
386
+ col1 = Matrix()
387
+ # Col 2 is only defined if o != 0
388
+ if o != 0:
389
+ if n != 0:
390
+ r1c2 = A_qu * C_2
391
+ else:
392
+ r1c2 = Matrix()
393
+ if m != 0:
394
+ r2c2 = A_uuc * C_2
395
+ else:
396
+ r2c2 = Matrix()
397
+ if o - m + k != 0:
398
+ r3c2 = A_uud * C_2
399
+ else:
400
+ r3c2 = Matrix()
401
+ col2 = Matrix([r1c2, r2c2, r3c2])
402
+ else:
403
+ col2 = Matrix()
404
+ if col1:
405
+ if col2:
406
+ Amat = col1.row_join(col2)
407
+ else:
408
+ Amat = col1
409
+ else:
410
+ Amat = col2
411
+ Amat_eq = msubs(Amat, op_point_dict)
412
+
413
+ # Build up the B matrix if there are forcing variables
414
+ # |0_(n + m)xs|
415
+ # B = |B_u |
416
+ if s != 0 and o - m + k != 0:
417
+ Bmat = zeros(n + m, s).col_join(B_u)
418
+ Bmat_eq = msubs(Bmat, op_point_dict)
419
+ else:
420
+ Bmat_eq = Matrix()
421
+
422
+ # kwarg A_and_B indicates to return A, B for forming the equation
423
+ # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
424
+ if A_and_B:
425
+ A_cont = self.perm_mat.T * self.linear_solver(M_eq, Amat_eq)
426
+ if Bmat_eq:
427
+ B_cont = self.perm_mat.T * self.linear_solver(M_eq, Bmat_eq)
428
+ else:
429
+ # Bmat = Matrix([]), so no need to sub
430
+ B_cont = Bmat_eq
431
+ if simplify:
432
+ A_cont.simplify()
433
+ B_cont.simplify()
434
+ return A_cont, B_cont
435
+ # Otherwise return M, A, B for forming the equation
436
+ # [M]dx = [A]x + [B]r, where x = [q, u]^T
437
+ else:
438
+ if simplify:
439
+ M_eq.simplify()
440
+ Amat_eq.simplify()
441
+ Bmat_eq.simplify()
442
+ return M_eq, Amat_eq, Bmat_eq
443
+
444
+
445
+ def permutation_matrix(orig_vec, per_vec):
446
+ """Compute the permutation matrix to change order of
447
+ orig_vec into order of per_vec.
448
+
449
+ Parameters
450
+ ==========
451
+
452
+ orig_vec : array_like
453
+ Symbols in original ordering.
454
+ per_vec : array_like
455
+ Symbols in new ordering.
456
+
457
+ Returns
458
+ =======
459
+
460
+ p_matrix : Matrix
461
+ Permutation matrix such that orig_vec == (p_matrix * per_vec).
462
+ """
463
+ if not isinstance(orig_vec, (list, tuple)):
464
+ orig_vec = flatten(orig_vec)
465
+ if not isinstance(per_vec, (list, tuple)):
466
+ per_vec = flatten(per_vec)
467
+ if set(orig_vec) != set(per_vec):
468
+ raise ValueError("orig_vec and per_vec must be the same length, "
469
+ "and contain the same symbols.")
470
+ ind_list = [orig_vec.index(i) for i in per_vec]
471
+ p_matrix = zeros(len(orig_vec))
472
+ for i, j in enumerate(ind_list):
473
+ p_matrix[i, j] = 1
474
+ return p_matrix
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/loads.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+ from collections import namedtuple
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.vector import Vector, ReferenceFrame, Point
5
+
6
+ __all__ = ['LoadBase', 'Force', 'Torque']
7
+
8
+
9
+ class LoadBase(ABC, namedtuple('LoadBase', ['location', 'vector'])):
10
+ """Abstract base class for the various loading types."""
11
+
12
+ def __add__(self, other):
13
+ raise TypeError(f"unsupported operand type(s) for +: "
14
+ f"'{self.__class__.__name__}' and "
15
+ f"'{other.__class__.__name__}'")
16
+
17
+ def __mul__(self, other):
18
+ raise TypeError(f"unsupported operand type(s) for *: "
19
+ f"'{self.__class__.__name__}' and "
20
+ f"'{other.__class__.__name__}'")
21
+
22
+ __radd__ = __add__
23
+ __rmul__ = __mul__
24
+
25
+
26
+ class Force(LoadBase):
27
+ """Force acting upon a point.
28
+
29
+ Explanation
30
+ ===========
31
+
32
+ A force is a vector that is bound to a line of action. This class stores
33
+ both a point, which lies on the line of action, and the vector. A tuple can
34
+ also be used, with the location as the first entry and the vector as second
35
+ entry.
36
+
37
+ Examples
38
+ ========
39
+
40
+ A force of magnitude 2 along N.x acting on a point Po can be created as
41
+ follows:
42
+
43
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, Force
44
+ >>> N = ReferenceFrame('N')
45
+ >>> Po = Point('Po')
46
+ >>> Force(Po, 2 * N.x)
47
+ (Po, 2*N.x)
48
+
49
+ If a body is supplied, then the center of mass of that body is used.
50
+
51
+ >>> from sympy.physics.mechanics import Particle
52
+ >>> P = Particle('P', point=Po)
53
+ >>> Force(P, 2 * N.x)
54
+ (Po, 2*N.x)
55
+
56
+ """
57
+
58
+ def __new__(cls, point, force):
59
+ if isinstance(point, BodyBase):
60
+ point = point.masscenter
61
+ if not isinstance(point, Point):
62
+ raise TypeError('Force location should be a Point.')
63
+ if not isinstance(force, Vector):
64
+ raise TypeError('Force vector should be a Vector.')
65
+ return super().__new__(cls, point, force)
66
+
67
+ def __repr__(self):
68
+ return (f'{self.__class__.__name__}(point={self.point}, '
69
+ f'force={self.force})')
70
+
71
+ @property
72
+ def point(self):
73
+ return self.location
74
+
75
+ @property
76
+ def force(self):
77
+ return self.vector
78
+
79
+
80
+ class Torque(LoadBase):
81
+ """Torque acting upon a frame.
82
+
83
+ Explanation
84
+ ===========
85
+
86
+ A torque is a free vector that is acting on a reference frame, which is
87
+ associated with a rigid body. This class stores both the frame and the
88
+ vector. A tuple can also be used, with the location as the first item and
89
+ the vector as second item.
90
+
91
+ Examples
92
+ ========
93
+
94
+ A torque of magnitude 2 about N.x acting on a frame N can be created as
95
+ follows:
96
+
97
+ >>> from sympy.physics.mechanics import ReferenceFrame, Torque
98
+ >>> N = ReferenceFrame('N')
99
+ >>> Torque(N, 2 * N.x)
100
+ (N, 2*N.x)
101
+
102
+ If a body is supplied, then the frame fixed to that body is used.
103
+
104
+ >>> from sympy.physics.mechanics import RigidBody
105
+ >>> rb = RigidBody('rb', frame=N)
106
+ >>> Torque(rb, 2 * N.x)
107
+ (N, 2*N.x)
108
+
109
+ """
110
+
111
+ def __new__(cls, frame, torque):
112
+ if isinstance(frame, BodyBase):
113
+ frame = frame.frame
114
+ if not isinstance(frame, ReferenceFrame):
115
+ raise TypeError('Torque location should be a ReferenceFrame.')
116
+ if not isinstance(torque, Vector):
117
+ raise TypeError('Torque vector should be a Vector.')
118
+ return super().__new__(cls, frame, torque)
119
+
120
+ def __repr__(self):
121
+ return (f'{self.__class__.__name__}(frame={self.frame}, '
122
+ f'torque={self.torque})')
123
+
124
+ @property
125
+ def frame(self):
126
+ return self.location
127
+
128
+ @property
129
+ def torque(self):
130
+ return self.vector
131
+
132
+
133
+ def gravity(acceleration, *bodies):
134
+ """
135
+ Returns a list of gravity forces given the acceleration
136
+ due to gravity and any number of particles or rigidbodies.
137
+
138
+ Example
139
+ =======
140
+
141
+ >>> from sympy.physics.mechanics import ReferenceFrame, Particle, RigidBody
142
+ >>> from sympy.physics.mechanics.loads import gravity
143
+ >>> from sympy import symbols
144
+ >>> N = ReferenceFrame('N')
145
+ >>> g = symbols('g')
146
+ >>> P = Particle('P')
147
+ >>> B = RigidBody('B')
148
+ >>> gravity(g*N.y, P, B)
149
+ [(P_masscenter, P_mass*g*N.y),
150
+ (B_masscenter, B_mass*g*N.y)]
151
+
152
+ """
153
+
154
+ gravity_force = []
155
+ for body in bodies:
156
+ if not isinstance(body, BodyBase):
157
+ raise TypeError(f'{type(body)} is not a body type')
158
+ gravity_force.append(Force(body.masscenter, body.mass * acceleration))
159
+ return gravity_force
160
+
161
+
162
+ def _parse_load(load):
163
+ """Helper function to parse loads and convert tuples to load objects."""
164
+ if isinstance(load, LoadBase):
165
+ return load
166
+ elif isinstance(load, tuple):
167
+ if len(load) != 2:
168
+ raise ValueError(f'Load {load} should have a length of 2.')
169
+ if isinstance(load[0], Point):
170
+ return Force(load[0], load[1])
171
+ elif isinstance(load[0], ReferenceFrame):
172
+ return Torque(load[0], load[1])
173
+ else:
174
+ raise ValueError(f'Load not recognized. The load location {load[0]}'
175
+ f' should either be a Point or a ReferenceFrame.')
176
+ raise TypeError(f'Load type {type(load)} not recognized as a load. It '
177
+ f'should be a Force, Torque or tuple.')
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/physics/mechanics/method.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ class _Methods(ABC):
4
+ """Abstract Base Class for all methods."""
5
+
6
+ @abstractmethod
7
+ def q(self):
8
+ pass
9
+
10
+ @abstractmethod
11
+ def u(self):
12
+ pass
13
+
14
+ @abstractmethod
15
+ def bodies(self):
16
+ pass
17
+
18
+ @abstractmethod
19
+ def loads(self):
20
+ pass
21
+
22
+ @abstractmethod
23
+ def mass_matrix(self):
24
+ pass
25
+
26
+ @abstractmethod
27
+ def forcing(self):
28
+ pass
29
+
30
+ @abstractmethod
31
+ def mass_matrix_full(self):
32
+ pass
33
+
34
+ @abstractmethod
35
+ def forcing_full(self):
36
+ pass
37
+
38
+ def _form_eoms(self):
39
+ raise NotImplementedError("Subclasses must implement this.")