applied-ai-018 commited on
Commit
8ba0881
·
verified ·
1 Parent(s): eec31b7

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. ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step120/zero/16.input_layernorm.weight/exp_avg.pt +3 -0
  4. ckpts/universal/global_step120/zero/3.attention.dense.weight/exp_avg_sq.pt +3 -0
  5. ckpts/universal/global_step80/mp_rank_06_model_states.pt +3 -0
  6. ckpts/universal/global_step80/mp_rank_07_model_states.pt +3 -0
  7. venv/lib/python3.10/site-packages/sympy/physics/__init__.py +12 -0
  8. venv/lib/python3.10/site-packages/sympy/physics/hep/__init__.py +0 -0
  9. venv/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc +0 -0
  10. venv/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/sympy/physics/hep/gamma_matrices.py +716 -0
  12. venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py +0 -0
  13. venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/sympy/physics/hep/tests/test_gamma_matrices.py +427 -0
  16. venv/lib/python3.10/site-packages/sympy/physics/hydrogen.py +265 -0
  17. venv/lib/python3.10/site-packages/sympy/physics/matrices.py +176 -0
  18. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py +66 -0
  19. venv/lib/python3.10/site-packages/sympy/physics/mechanics/body.py +611 -0
  20. venv/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py +779 -0
  21. venv/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py +2163 -0
  22. venv/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py +279 -0
  23. venv/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py +741 -0
  24. venv/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py +477 -0
  25. venv/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py +443 -0
  26. venv/lib/python3.10/site-packages/sympy/physics/mechanics/method.py +39 -0
  27. venv/lib/python3.10/site-packages/sympy/physics/mechanics/models.py +230 -0
  28. venv/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py +281 -0
  29. venv/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py +366 -0
  30. venv/lib/python3.10/site-packages/sympy/physics/mechanics/system.py +445 -0
  31. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py +0 -0
  32. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_method.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_body.py +319 -0
  42. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py +292 -0
  43. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py +1144 -0
  44. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py +212 -0
  45. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py +532 -0
  46. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane2.py +462 -0
  47. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane3.py +293 -0
  48. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py +115 -0
  49. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange.py +247 -0
  50. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py +46 -0
ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3375851ae9cc2b48e232b073a27afe8ba09a5578db5ad47cf9f306a89c4a875d
3
+ size 50332828
ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1be4a15b2977133ef38bf34ee9895127a662f819fdcb79d23d0dfc8559010bde
3
+ size 50332843
ckpts/universal/global_step120/zero/16.input_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7af30be403aa91780f386a68b33ce33198efeacc72d5748c5a80561aee3caec8
3
+ size 9372
ckpts/universal/global_step120/zero/3.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ff2188d09042d534180e1100034c3d121d291457bcb1cc18898cd0133cd6ec9
3
+ size 16778411
ckpts/universal/global_step80/mp_rank_06_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c63a0ffdc3354c06ac43f69a873b51aeb3d80562ef5d8d3b339be80af010745
3
+ size 4230084
ckpts/universal/global_step80/mp_rank_07_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74055ebc8e077321bdb4577d270ca867236033d1ffac996bd0d00d7ba42b94fe
3
+ size 4230084
venv/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
+ ]
venv/lib/python3.10/site-packages/sympy/physics/hep/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/hep/__pycache__/gamma_matrices.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
venv/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
venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/hep/tests/__pycache__/test_gamma_matrices.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
venv/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
venv/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
venv/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()
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum',
16
+ 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing',
17
+ 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols',
18
+
19
+ 'Particle',
20
+
21
+ 'LagrangesMethod',
22
+
23
+ 'Linearizer',
24
+
25
+ 'Body',
26
+
27
+ 'SymbolicSystem',
28
+
29
+ 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint',
30
+ 'SphericalJoint', 'WeldJoint',
31
+
32
+ 'JointsMethod'
33
+ ]
34
+
35
+ from sympy.physics import vector
36
+
37
+ from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point,
38
+ cross, dot, express, time_derivative, outer, kinematic_equations,
39
+ get_motion_params, partial_velocity, dynamicsymbols, vprint,
40
+ vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence,
41
+ gradient, is_conservative, is_solenoidal, scalar_potential,
42
+ scalar_potential_difference)
43
+
44
+ from .kane import KanesMethod
45
+
46
+ from .rigidbody import RigidBody
47
+
48
+ from .functions import (inertia, inertia_of_point_mass, linear_momentum,
49
+ angular_momentum, kinetic_energy, potential_energy, Lagrangian,
50
+ mechanics_printing, mprint, msprint, mpprint, mlatex, msubs,
51
+ find_dynamicsymbols)
52
+
53
+ from .particle import Particle
54
+
55
+ from .lagrange import LagrangesMethod
56
+
57
+ from .linearize import Linearizer
58
+
59
+ from .body import Body
60
+
61
+ from .system import SymbolicSystem
62
+
63
+ from .jointsmethod import JointsMethod
64
+
65
+ from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint,
66
+ SphericalJoint, WeldJoint)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/body.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import Symbol
2
+ from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic
3
+ from sympy.physics.mechanics import RigidBody, Particle, inertia
4
+
5
+ __all__ = ['Body']
6
+
7
+
8
+ # XXX: We use type:ignore because the classes RigidBody and Particle have
9
+ # inconsistent parallel axis methods that take different numbers of arguments.
10
+ class Body(RigidBody, Particle): # type: ignore
11
+ """
12
+ Body is a common representation of either a RigidBody or a Particle SymPy
13
+ object depending on what is passed in during initialization. If a mass is
14
+ passed in and central_inertia is left as None, the Particle object is
15
+ created. Otherwise a RigidBody object will be created.
16
+
17
+ Explanation
18
+ ===========
19
+
20
+ The attributes that Body possesses will be the same as a Particle instance
21
+ or a Rigid Body instance depending on which was created. Additional
22
+ attributes are listed below.
23
+
24
+ Attributes
25
+ ==========
26
+
27
+ name : string
28
+ The body's name
29
+ masscenter : Point
30
+ The point which represents the center of mass of the rigid body
31
+ frame : ReferenceFrame
32
+ The reference frame which the body is fixed in
33
+ mass : Sympifyable
34
+ The body's mass
35
+ inertia : (Dyadic, Point)
36
+ The body's inertia around its center of mass. This attribute is specific
37
+ to the rigid body form of Body and is left undefined for the Particle
38
+ form
39
+ loads : iterable
40
+ This list contains information on the different loads acting on the
41
+ Body. Forces are listed as a (point, vector) tuple and torques are
42
+ listed as (reference frame, vector) tuples.
43
+
44
+ Parameters
45
+ ==========
46
+
47
+ name : String
48
+ Defines the name of the body. It is used as the base for defining
49
+ body specific properties.
50
+ masscenter : Point, optional
51
+ A point that represents the center of mass of the body or particle.
52
+ If no point is given, a point is generated.
53
+ mass : Sympifyable, optional
54
+ A Sympifyable object which represents the mass of the body. If no
55
+ mass is passed, one is generated.
56
+ frame : ReferenceFrame, optional
57
+ The ReferenceFrame that represents the reference frame of the body.
58
+ If no frame is given, a frame is generated.
59
+ central_inertia : Dyadic, optional
60
+ Central inertia dyadic of the body. If none is passed while creating
61
+ RigidBody, a default inertia is generated.
62
+
63
+ Examples
64
+ ========
65
+
66
+ Default behaviour. This results in the creation of a RigidBody object for
67
+ which the mass, mass center, frame and inertia attributes are given default
68
+ values. ::
69
+
70
+ >>> from sympy.physics.mechanics import Body
71
+ >>> body = Body('name_of_body')
72
+
73
+ This next example demonstrates the code required to specify all of the
74
+ values of the Body object. Note this will also create a RigidBody version of
75
+ the Body object. ::
76
+
77
+ >>> from sympy import Symbol
78
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia
79
+ >>> from sympy.physics.mechanics import Body
80
+ >>> mass = Symbol('mass')
81
+ >>> masscenter = Point('masscenter')
82
+ >>> frame = ReferenceFrame('frame')
83
+ >>> ixx = Symbol('ixx')
84
+ >>> body_inertia = inertia(frame, ixx, 0, 0)
85
+ >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia)
86
+
87
+ The minimal code required to create a Particle version of the Body object
88
+ involves simply passing in a name and a mass. ::
89
+
90
+ >>> from sympy import Symbol
91
+ >>> from sympy.physics.mechanics import Body
92
+ >>> mass = Symbol('mass')
93
+ >>> body = Body('name_of_body', mass=mass)
94
+
95
+ The Particle version of the Body object can also receive a masscenter point
96
+ and a reference frame, just not an inertia.
97
+ """
98
+
99
+ def __init__(self, name, masscenter=None, mass=None, frame=None,
100
+ central_inertia=None):
101
+
102
+ self.name = name
103
+ self._loads = []
104
+
105
+ if frame is None:
106
+ frame = ReferenceFrame(name + '_frame')
107
+
108
+ if masscenter is None:
109
+ masscenter = Point(name + '_masscenter')
110
+
111
+ if central_inertia is None and mass is None:
112
+ ixx = Symbol(name + '_ixx')
113
+ iyy = Symbol(name + '_iyy')
114
+ izz = Symbol(name + '_izz')
115
+ izx = Symbol(name + '_izx')
116
+ ixy = Symbol(name + '_ixy')
117
+ iyz = Symbol(name + '_iyz')
118
+ _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx),
119
+ masscenter)
120
+ else:
121
+ _inertia = (central_inertia, masscenter)
122
+
123
+ if mass is None:
124
+ _mass = Symbol(name + '_mass')
125
+ else:
126
+ _mass = mass
127
+
128
+ masscenter.set_vel(frame, 0)
129
+
130
+ # If user passes masscenter and mass then a particle is created
131
+ # otherwise a rigidbody. As a result a body may or may not have inertia.
132
+ if central_inertia is None and mass is not None:
133
+ self.frame = frame
134
+ self.masscenter = masscenter
135
+ Particle.__init__(self, name, masscenter, _mass)
136
+ self._central_inertia = Dyadic(0)
137
+ else:
138
+ RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia)
139
+
140
+ @property
141
+ def loads(self):
142
+ return self._loads
143
+
144
+ @property
145
+ def x(self):
146
+ """The basis Vector for the Body, in the x direction."""
147
+ return self.frame.x
148
+
149
+ @property
150
+ def y(self):
151
+ """The basis Vector for the Body, in the y direction."""
152
+ return self.frame.y
153
+
154
+ @property
155
+ def z(self):
156
+ """The basis Vector for the Body, in the z direction."""
157
+ return self.frame.z
158
+
159
+ @property
160
+ def inertia(self):
161
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
162
+ if self.is_rigidbody:
163
+ return RigidBody.inertia.fget(self)
164
+ return (self.central_inertia, self.masscenter)
165
+
166
+ @inertia.setter
167
+ def inertia(self, I):
168
+ RigidBody.inertia.fset(self, I)
169
+
170
+ @property
171
+ def is_rigidbody(self):
172
+ if hasattr(self, '_inertia'):
173
+ return True
174
+ return False
175
+
176
+ def kinetic_energy(self, frame):
177
+ """Kinetic energy of the body.
178
+
179
+ Parameters
180
+ ==========
181
+
182
+ frame : ReferenceFrame or Body
183
+ The Body's angular velocity and the velocity of it's mass
184
+ center are typically defined with respect to an inertial frame but
185
+ any relevant frame in which the velocities are known can be supplied.
186
+
187
+ Examples
188
+ ========
189
+
190
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point
191
+ >>> from sympy import symbols
192
+ >>> m, v, r, omega = symbols('m v r omega')
193
+ >>> N = ReferenceFrame('N')
194
+ >>> O = Point('O')
195
+ >>> P = Body('P', masscenter=O, mass=m)
196
+ >>> P.masscenter.set_vel(N, v * N.y)
197
+ >>> P.kinetic_energy(N)
198
+ m*v**2/2
199
+
200
+ >>> N = ReferenceFrame('N')
201
+ >>> b = ReferenceFrame('b')
202
+ >>> b.set_ang_vel(N, omega * b.x)
203
+ >>> P = Point('P')
204
+ >>> P.set_vel(N, v * N.x)
205
+ >>> B = Body('B', masscenter=P, frame=b)
206
+ >>> B.kinetic_energy(N)
207
+ B_ixx*omega**2/2 + B_mass*v**2/2
208
+
209
+ See Also
210
+ ========
211
+
212
+ sympy.physics.mechanics : Particle, RigidBody
213
+
214
+ """
215
+ if isinstance(frame, Body):
216
+ frame = Body.frame
217
+ if self.is_rigidbody:
218
+ return RigidBody(self.name, self.masscenter, self.frame, self.mass,
219
+ (self.central_inertia, self.masscenter)).kinetic_energy(frame)
220
+ return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame)
221
+
222
+ def apply_force(self, force, point=None, reaction_body=None, reaction_point=None):
223
+ """Add force to the body(s).
224
+
225
+ Explanation
226
+ ===========
227
+
228
+ Applies the force on self or equal and oppposite forces on
229
+ self and other body if both are given on the desried point on the bodies.
230
+ The force applied on other body is taken opposite of self, i.e, -force.
231
+
232
+ Parameters
233
+ ==========
234
+
235
+ force: Vector
236
+ The force to be applied.
237
+ point: Point, optional
238
+ The point on self on which force is applied.
239
+ By default self's masscenter.
240
+ reaction_body: Body, optional
241
+ Second body on which equal and opposite force
242
+ is to be applied.
243
+ reaction_point : Point, optional
244
+ The point on other body on which equal and opposite
245
+ force is applied. By default masscenter of other body.
246
+
247
+ Example
248
+ =======
249
+
250
+ >>> from sympy import symbols
251
+ >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols
252
+ >>> m, g = symbols('m g')
253
+ >>> B = Body('B')
254
+ >>> force1 = m*g*B.z
255
+ >>> B.apply_force(force1) #Applying force on B's masscenter
256
+ >>> B.loads
257
+ [(B_masscenter, g*m*B_frame.z)]
258
+
259
+ We can also remove some part of force from any point on the body by
260
+ adding the opposite force to the body on that point.
261
+
262
+ >>> f1, f2 = dynamicsymbols('f1 f2')
263
+ >>> P = Point('P') #Considering point P on body B
264
+ >>> B.apply_force(f1*B.x + f2*B.y, P)
265
+ >>> B.loads
266
+ [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)]
267
+
268
+ Let's remove f1 from point P on body B.
269
+
270
+ >>> B.apply_force(-f1*B.x, P)
271
+ >>> B.loads
272
+ [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)]
273
+
274
+ To further demonstrate the use of ``apply_force`` attribute,
275
+ consider two bodies connected through a spring.
276
+
277
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
278
+ >>> N = Body('N') #Newtonion Frame
279
+ >>> x = dynamicsymbols('x')
280
+ >>> B1 = Body('B1')
281
+ >>> B2 = Body('B2')
282
+ >>> spring_force = x*N.x
283
+
284
+ Now let's apply equal and opposite spring force to the bodies.
285
+
286
+ >>> P1 = Point('P1')
287
+ >>> P2 = Point('P2')
288
+ >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2)
289
+
290
+ We can check the loads(forces) applied to bodies now.
291
+
292
+ >>> B1.loads
293
+ [(P1, x(t)*N_frame.x)]
294
+ >>> B2.loads
295
+ [(P2, - x(t)*N_frame.x)]
296
+
297
+ Notes
298
+ =====
299
+
300
+ If a new force is applied to a body on a point which already has some
301
+ force applied on it, then the new force is added to the already applied
302
+ force on that point.
303
+
304
+ """
305
+
306
+ if not isinstance(point, Point):
307
+ if point is None:
308
+ point = self.masscenter # masscenter
309
+ else:
310
+ raise TypeError("Force must be applied to a point on the body.")
311
+ if not isinstance(force, Vector):
312
+ raise TypeError("Force must be a vector.")
313
+
314
+ if reaction_body is not None:
315
+ reaction_body.apply_force(-force, point=reaction_point)
316
+
317
+ for load in self._loads:
318
+ if point in load:
319
+ force += load[1]
320
+ self._loads.remove(load)
321
+ break
322
+
323
+ self._loads.append((point, force))
324
+
325
+ def apply_torque(self, torque, reaction_body=None):
326
+ """Add torque to the body(s).
327
+
328
+ Explanation
329
+ ===========
330
+
331
+ Applies the torque on self or equal and oppposite torquess on
332
+ self and other body if both are given.
333
+ The torque applied on other body is taken opposite of self,
334
+ i.e, -torque.
335
+
336
+ Parameters
337
+ ==========
338
+
339
+ torque: Vector
340
+ The torque to be applied.
341
+ reaction_body: Body, optional
342
+ Second body on which equal and opposite torque
343
+ is to be applied.
344
+
345
+ Example
346
+ =======
347
+
348
+ >>> from sympy import symbols
349
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
350
+ >>> t = symbols('t')
351
+ >>> B = Body('B')
352
+ >>> torque1 = t*B.z
353
+ >>> B.apply_torque(torque1)
354
+ >>> B.loads
355
+ [(B_frame, t*B_frame.z)]
356
+
357
+ We can also remove some part of torque from the body by
358
+ adding the opposite torque to the body.
359
+
360
+ >>> t1, t2 = dynamicsymbols('t1 t2')
361
+ >>> B.apply_torque(t1*B.x + t2*B.y)
362
+ >>> B.loads
363
+ [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)]
364
+
365
+ Let's remove t1 from Body B.
366
+
367
+ >>> B.apply_torque(-t1*B.x)
368
+ >>> B.loads
369
+ [(B_frame, t2(t)*B_frame.y + t*B_frame.z)]
370
+
371
+ To further demonstrate the use, let us consider two bodies such that
372
+ a torque `T` is acting on one body, and `-T` on the other.
373
+
374
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
375
+ >>> N = Body('N') #Newtonion frame
376
+ >>> B1 = Body('B1')
377
+ >>> B2 = Body('B2')
378
+ >>> v = dynamicsymbols('v')
379
+ >>> T = v*N.y #Torque
380
+
381
+ Now let's apply equal and opposite torque to the bodies.
382
+
383
+ >>> B1.apply_torque(T, B2)
384
+
385
+ We can check the loads (torques) applied to bodies now.
386
+
387
+ >>> B1.loads
388
+ [(B1_frame, v(t)*N_frame.y)]
389
+ >>> B2.loads
390
+ [(B2_frame, - v(t)*N_frame.y)]
391
+
392
+ Notes
393
+ =====
394
+
395
+ If a new torque is applied on body which already has some torque applied on it,
396
+ then the new torque is added to the previous torque about the body's frame.
397
+
398
+ """
399
+
400
+ if not isinstance(torque, Vector):
401
+ raise TypeError("A Vector must be supplied to add torque.")
402
+
403
+ if reaction_body is not None:
404
+ reaction_body.apply_torque(-torque)
405
+
406
+ for load in self._loads:
407
+ if self.frame in load:
408
+ torque += load[1]
409
+ self._loads.remove(load)
410
+ break
411
+ self._loads.append((self.frame, torque))
412
+
413
+ def clear_loads(self):
414
+ """
415
+ Clears the Body's loads list.
416
+
417
+ Example
418
+ =======
419
+
420
+ >>> from sympy.physics.mechanics import Body
421
+ >>> B = Body('B')
422
+ >>> force = B.x + B.y
423
+ >>> B.apply_force(force)
424
+ >>> B.loads
425
+ [(B_masscenter, B_frame.x + B_frame.y)]
426
+ >>> B.clear_loads()
427
+ >>> B.loads
428
+ []
429
+
430
+ """
431
+
432
+ self._loads = []
433
+
434
+ def remove_load(self, about=None):
435
+ """
436
+ Remove load about a point or frame.
437
+
438
+ Parameters
439
+ ==========
440
+
441
+ about : Point or ReferenceFrame, optional
442
+ The point about which force is applied,
443
+ and is to be removed.
444
+ If about is None, then the torque about
445
+ self's frame is removed.
446
+
447
+ Example
448
+ =======
449
+
450
+ >>> from sympy.physics.mechanics import Body, Point
451
+ >>> B = Body('B')
452
+ >>> P = Point('P')
453
+ >>> f1 = B.x
454
+ >>> f2 = B.y
455
+ >>> B.apply_force(f1)
456
+ >>> B.apply_force(f2, P)
457
+ >>> B.loads
458
+ [(B_masscenter, B_frame.x), (P, B_frame.y)]
459
+
460
+ >>> B.remove_load(P)
461
+ >>> B.loads
462
+ [(B_masscenter, B_frame.x)]
463
+
464
+ """
465
+
466
+ if about is not None:
467
+ if not isinstance(about, Point):
468
+ raise TypeError('Load is applied about Point or ReferenceFrame.')
469
+ else:
470
+ about = self.frame
471
+
472
+ for load in self._loads:
473
+ if about in load:
474
+ self._loads.remove(load)
475
+ break
476
+
477
+ def masscenter_vel(self, body):
478
+ """
479
+ Returns the velocity of the mass center with respect to the provided
480
+ rigid body or reference frame.
481
+
482
+ Parameters
483
+ ==========
484
+
485
+ body: Body or ReferenceFrame
486
+ The rigid body or reference frame to calculate the velocity in.
487
+
488
+ Example
489
+ =======
490
+
491
+ >>> from sympy.physics.mechanics import Body
492
+ >>> A = Body('A')
493
+ >>> B = Body('B')
494
+ >>> A.masscenter.set_vel(B.frame, 5*B.frame.x)
495
+ >>> A.masscenter_vel(B)
496
+ 5*B_frame.x
497
+ >>> A.masscenter_vel(B.frame)
498
+ 5*B_frame.x
499
+
500
+ """
501
+
502
+ if isinstance(body, ReferenceFrame):
503
+ frame=body
504
+ elif isinstance(body, Body):
505
+ frame = body.frame
506
+ return self.masscenter.vel(frame)
507
+
508
+ def ang_vel_in(self, body):
509
+ """
510
+ Returns this body's angular velocity with respect to the provided
511
+ rigid body or reference frame.
512
+
513
+ Parameters
514
+ ==========
515
+
516
+ body: Body or ReferenceFrame
517
+ The rigid body or reference frame to calculate the angular velocity in.
518
+
519
+ Example
520
+ =======
521
+
522
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame
523
+ >>> A = Body('A')
524
+ >>> N = ReferenceFrame('N')
525
+ >>> B = Body('B', frame=N)
526
+ >>> A.frame.set_ang_vel(N, 5*N.x)
527
+ >>> A.ang_vel_in(B)
528
+ 5*N.x
529
+ >>> A.ang_vel_in(N)
530
+ 5*N.x
531
+
532
+ """
533
+
534
+ if isinstance(body, ReferenceFrame):
535
+ frame=body
536
+ elif isinstance(body, Body):
537
+ frame = body.frame
538
+ return self.frame.ang_vel_in(frame)
539
+
540
+ def dcm(self, body):
541
+ """
542
+ Returns the direction cosine matrix of this body relative to the
543
+ provided rigid body or reference frame.
544
+
545
+ Parameters
546
+ ==========
547
+
548
+ body: Body or ReferenceFrame
549
+ The rigid body or reference frame to calculate the dcm.
550
+
551
+ Example
552
+ =======
553
+
554
+ >>> from sympy.physics.mechanics import Body
555
+ >>> A = Body('A')
556
+ >>> B = Body('B')
557
+ >>> A.frame.orient_axis(B.frame, B.frame.x, 5)
558
+ >>> A.dcm(B)
559
+ Matrix([
560
+ [1, 0, 0],
561
+ [0, cos(5), sin(5)],
562
+ [0, -sin(5), cos(5)]])
563
+ >>> A.dcm(B.frame)
564
+ Matrix([
565
+ [1, 0, 0],
566
+ [0, cos(5), sin(5)],
567
+ [0, -sin(5), cos(5)]])
568
+
569
+ """
570
+
571
+ if isinstance(body, ReferenceFrame):
572
+ frame=body
573
+ elif isinstance(body, Body):
574
+ frame = body.frame
575
+ return self.frame.dcm(frame)
576
+
577
+ def parallel_axis(self, point, frame=None):
578
+ """Returns the inertia dyadic of the body with respect to another
579
+ point.
580
+
581
+ Parameters
582
+ ==========
583
+
584
+ point : sympy.physics.vector.Point
585
+ The point to express the inertia dyadic about.
586
+ frame : sympy.physics.vector.ReferenceFrame
587
+ The reference frame used to construct the dyadic.
588
+
589
+ Returns
590
+ =======
591
+
592
+ inertia : sympy.physics.vector.Dyadic
593
+ The inertia dyadic of the rigid body expressed about the provided
594
+ point.
595
+
596
+ Example
597
+ =======
598
+
599
+ >>> from sympy.physics.mechanics import Body
600
+ >>> A = Body('A')
601
+ >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y)
602
+ >>> A.parallel_axis(P).to_matrix(A.frame)
603
+ Matrix([
604
+ [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx],
605
+ [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz],
606
+ [ A_izx, A_iyz, A_izz + 34*A_mass]])
607
+
608
+ """
609
+ if self.is_rigidbody:
610
+ return RigidBody.parallel_axis(self, point, frame)
611
+ return Particle.parallel_axis(self, point, frame)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos,
11
+ tan, AppliedUndef, S)
12
+
13
+ __all__ = ['inertia',
14
+ 'inertia_of_point_mass',
15
+ 'linear_momentum',
16
+ 'angular_momentum',
17
+ 'kinetic_energy',
18
+ 'potential_energy',
19
+ 'Lagrangian',
20
+ 'mechanics_printing',
21
+ 'mprint',
22
+ 'msprint',
23
+ 'mpprint',
24
+ 'mlatex',
25
+ 'msubs',
26
+ 'find_dynamicsymbols']
27
+
28
+ # These are functions that we've moved and renamed during extracting the
29
+ # basic vector calculus code from the mechanics packages.
30
+
31
+ mprint = vprint
32
+ msprint = vsprint
33
+ mpprint = vpprint
34
+ mlatex = vlatex
35
+
36
+
37
+ def mechanics_printing(**kwargs):
38
+ """
39
+ Initializes time derivative printing for all SymPy objects in
40
+ mechanics module.
41
+ """
42
+
43
+ init_vprinting(**kwargs)
44
+
45
+ mechanics_printing.__doc__ = init_vprinting.__doc__
46
+
47
+
48
+ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
49
+ """Simple way to create inertia Dyadic object.
50
+
51
+ Explanation
52
+ ===========
53
+
54
+ If you do not know what a Dyadic is, just treat this like the inertia
55
+ tensor. Then, do the easy thing and define it in a body-fixed frame.
56
+
57
+ Parameters
58
+ ==========
59
+
60
+ frame : ReferenceFrame
61
+ The frame the inertia is defined in
62
+ ixx : Sympifyable
63
+ the xx element in the inertia dyadic
64
+ iyy : Sympifyable
65
+ the yy element in the inertia dyadic
66
+ izz : Sympifyable
67
+ the zz element in the inertia dyadic
68
+ ixy : Sympifyable
69
+ the xy element in the inertia dyadic
70
+ iyz : Sympifyable
71
+ the yz element in the inertia dyadic
72
+ izx : Sympifyable
73
+ the zx element in the inertia dyadic
74
+
75
+ Examples
76
+ ========
77
+
78
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia
79
+ >>> N = ReferenceFrame('N')
80
+ >>> inertia(N, 1, 2, 3)
81
+ (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
82
+
83
+ """
84
+
85
+ if not isinstance(frame, ReferenceFrame):
86
+ raise TypeError('Need to define the inertia in a frame')
87
+ ixx = sympify(ixx)
88
+ ixy = sympify(ixy)
89
+ iyy = sympify(iyy)
90
+ iyz = sympify(iyz)
91
+ izx = sympify(izx)
92
+ izz = sympify(izz)
93
+ ol = ixx * (frame.x | frame.x)
94
+ ol += ixy * (frame.x | frame.y)
95
+ ol += izx * (frame.x | frame.z)
96
+ ol += ixy * (frame.y | frame.x)
97
+ ol += iyy * (frame.y | frame.y)
98
+ ol += iyz * (frame.y | frame.z)
99
+ ol += izx * (frame.z | frame.x)
100
+ ol += iyz * (frame.z | frame.y)
101
+ ol += izz * (frame.z | frame.z)
102
+ return ol
103
+
104
+
105
+ def inertia_of_point_mass(mass, pos_vec, frame):
106
+ """Inertia dyadic of a point mass relative to point O.
107
+
108
+ Parameters
109
+ ==========
110
+
111
+ mass : Sympifyable
112
+ Mass of the point mass
113
+ pos_vec : Vector
114
+ Position from point O to point mass
115
+ frame : ReferenceFrame
116
+ Reference frame to express the dyadic in
117
+
118
+ Examples
119
+ ========
120
+
121
+ >>> from sympy import symbols
122
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
123
+ >>> N = ReferenceFrame('N')
124
+ >>> r, m = symbols('r m')
125
+ >>> px = r * N.x
126
+ >>> inertia_of_point_mass(m, px, N)
127
+ m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
128
+
129
+ """
130
+
131
+ return mass * (((frame.x | frame.x) + (frame.y | frame.y) +
132
+ (frame.z | frame.z)) * (pos_vec & pos_vec) -
133
+ (pos_vec | pos_vec))
134
+
135
+
136
+ def linear_momentum(frame, *body):
137
+ """Linear momentum of the system.
138
+
139
+ Explanation
140
+ ===========
141
+
142
+ This function returns the linear momentum of a system of Particle's and/or
143
+ RigidBody's. The linear momentum of a system is equal to the vector sum of
144
+ the linear momentum of its constituents. Consider a system, S, comprised of
145
+ a rigid body, A, and a particle, P. The linear momentum of the system, L,
146
+ is equal to the vector sum of the linear momentum of the particle, L1, and
147
+ the linear momentum of the rigid body, L2, i.e.
148
+
149
+ L = L1 + L2
150
+
151
+ Parameters
152
+ ==========
153
+
154
+ frame : ReferenceFrame
155
+ The frame in which linear momentum is desired.
156
+ body1, body2, body3... : Particle and/or RigidBody
157
+ The body (or bodies) whose linear momentum is required.
158
+
159
+ Examples
160
+ ========
161
+
162
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
163
+ >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
164
+ >>> N = ReferenceFrame('N')
165
+ >>> P = Point('P')
166
+ >>> P.set_vel(N, 10 * N.x)
167
+ >>> Pa = Particle('Pa', P, 1)
168
+ >>> Ac = Point('Ac')
169
+ >>> Ac.set_vel(N, 25 * N.y)
170
+ >>> I = outer(N.x, N.x)
171
+ >>> A = RigidBody('A', Ac, N, 20, (I, Ac))
172
+ >>> linear_momentum(N, A, Pa)
173
+ 10*N.x + 500*N.y
174
+
175
+ """
176
+
177
+ if not isinstance(frame, ReferenceFrame):
178
+ raise TypeError('Please specify a valid ReferenceFrame')
179
+ else:
180
+ linear_momentum_sys = Vector(0)
181
+ for e in body:
182
+ if isinstance(e, (RigidBody, Particle)):
183
+ linear_momentum_sys += e.linear_momentum(frame)
184
+ else:
185
+ raise TypeError('*body must have only Particle or RigidBody')
186
+ return linear_momentum_sys
187
+
188
+
189
+ def angular_momentum(point, frame, *body):
190
+ """Angular momentum of a system.
191
+
192
+ Explanation
193
+ ===========
194
+
195
+ This function returns the angular momentum of a system of Particle's and/or
196
+ RigidBody's. The angular momentum of such a system is equal to the vector
197
+ sum of the angular momentum of its constituents. Consider a system, S,
198
+ comprised of a rigid body, A, and a particle, P. The angular momentum of
199
+ the system, H, is equal to the vector sum of the angular momentum of the
200
+ particle, H1, and the angular momentum of the rigid body, H2, i.e.
201
+
202
+ H = H1 + H2
203
+
204
+ Parameters
205
+ ==========
206
+
207
+ point : Point
208
+ The point about which angular momentum of the system is desired.
209
+ frame : ReferenceFrame
210
+ The frame in which angular momentum is desired.
211
+ body1, body2, body3... : Particle and/or RigidBody
212
+ The body (or bodies) whose angular momentum is required.
213
+
214
+ Examples
215
+ ========
216
+
217
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
218
+ >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
219
+ >>> N = ReferenceFrame('N')
220
+ >>> O = Point('O')
221
+ >>> O.set_vel(N, 0 * N.x)
222
+ >>> P = O.locatenew('P', 1 * N.x)
223
+ >>> P.set_vel(N, 10 * N.x)
224
+ >>> Pa = Particle('Pa', P, 1)
225
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
226
+ >>> Ac.set_vel(N, 5 * N.y)
227
+ >>> a = ReferenceFrame('a')
228
+ >>> a.set_ang_vel(N, 10 * N.z)
229
+ >>> I = outer(N.z, N.z)
230
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
231
+ >>> angular_momentum(O, N, Pa, A)
232
+ 10*N.z
233
+
234
+ """
235
+
236
+ if not isinstance(frame, ReferenceFrame):
237
+ raise TypeError('Please enter a valid ReferenceFrame')
238
+ if not isinstance(point, Point):
239
+ raise TypeError('Please specify a valid Point')
240
+ else:
241
+ angular_momentum_sys = Vector(0)
242
+ for e in body:
243
+ if isinstance(e, (RigidBody, Particle)):
244
+ angular_momentum_sys += e.angular_momentum(point, frame)
245
+ else:
246
+ raise TypeError('*body must have only Particle or RigidBody')
247
+ return angular_momentum_sys
248
+
249
+
250
+ def kinetic_energy(frame, *body):
251
+ """Kinetic energy of a multibody system.
252
+
253
+ Explanation
254
+ ===========
255
+
256
+ This function returns the kinetic energy of a system of Particle's and/or
257
+ RigidBody's. The kinetic energy of such a system is equal to the sum of
258
+ the kinetic energies of its constituents. Consider a system, S, comprising
259
+ a rigid body, A, and a particle, P. The kinetic energy of the system, T,
260
+ is equal to the vector sum of the kinetic energy of the particle, T1, and
261
+ the kinetic energy of the rigid body, T2, i.e.
262
+
263
+ T = T1 + T2
264
+
265
+ Kinetic energy is a scalar.
266
+
267
+ Parameters
268
+ ==========
269
+
270
+ frame : ReferenceFrame
271
+ The frame in which the velocity or angular velocity of the body is
272
+ defined.
273
+ body1, body2, body3... : Particle and/or RigidBody
274
+ The body (or bodies) whose kinetic energy is required.
275
+
276
+ Examples
277
+ ========
278
+
279
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
280
+ >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
281
+ >>> N = ReferenceFrame('N')
282
+ >>> O = Point('O')
283
+ >>> O.set_vel(N, 0 * N.x)
284
+ >>> P = O.locatenew('P', 1 * N.x)
285
+ >>> P.set_vel(N, 10 * N.x)
286
+ >>> Pa = Particle('Pa', P, 1)
287
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
288
+ >>> Ac.set_vel(N, 5 * N.y)
289
+ >>> a = ReferenceFrame('a')
290
+ >>> a.set_ang_vel(N, 10 * N.z)
291
+ >>> I = outer(N.z, N.z)
292
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
293
+ >>> kinetic_energy(N, Pa, A)
294
+ 350
295
+
296
+ """
297
+
298
+ if not isinstance(frame, ReferenceFrame):
299
+ raise TypeError('Please enter a valid ReferenceFrame')
300
+ ke_sys = S.Zero
301
+ for e in body:
302
+ if isinstance(e, (RigidBody, Particle)):
303
+ ke_sys += e.kinetic_energy(frame)
304
+ else:
305
+ raise TypeError('*body must have only Particle or RigidBody')
306
+ return ke_sys
307
+
308
+
309
+ def potential_energy(*body):
310
+ """Potential energy of a multibody system.
311
+
312
+ Explanation
313
+ ===========
314
+
315
+ This function returns the potential energy of a system of Particle's and/or
316
+ RigidBody's. The potential energy of such a system is equal to the sum of
317
+ the potential energy of its constituents. Consider a system, S, comprising
318
+ a rigid body, A, and a particle, P. The potential energy of the system, V,
319
+ is equal to the vector sum of the potential energy of the particle, V1, and
320
+ the potential energy of the rigid body, V2, i.e.
321
+
322
+ V = V1 + V2
323
+
324
+ Potential energy is a scalar.
325
+
326
+ Parameters
327
+ ==========
328
+
329
+ body1, body2, body3... : Particle and/or RigidBody
330
+ The body (or bodies) whose potential energy is required.
331
+
332
+ Examples
333
+ ========
334
+
335
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
336
+ >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
337
+ >>> from sympy import symbols
338
+ >>> M, m, g, h = symbols('M m g h')
339
+ >>> N = ReferenceFrame('N')
340
+ >>> O = Point('O')
341
+ >>> O.set_vel(N, 0 * N.x)
342
+ >>> P = O.locatenew('P', 1 * N.x)
343
+ >>> Pa = Particle('Pa', P, m)
344
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
345
+ >>> a = ReferenceFrame('a')
346
+ >>> I = outer(N.z, N.z)
347
+ >>> A = RigidBody('A', Ac, a, M, (I, Ac))
348
+ >>> Pa.potential_energy = m * g * h
349
+ >>> A.potential_energy = M * g * h
350
+ >>> potential_energy(Pa, A)
351
+ M*g*h + g*h*m
352
+
353
+ """
354
+
355
+ pe_sys = S.Zero
356
+ for e in body:
357
+ if isinstance(e, (RigidBody, Particle)):
358
+ pe_sys += e.potential_energy
359
+ else:
360
+ raise TypeError('*body must have only Particle or RigidBody')
361
+ return pe_sys
362
+
363
+
364
+ def gravity(acceleration, *bodies):
365
+ """
366
+ Returns a list of gravity forces given the acceleration
367
+ due to gravity and any number of particles or rigidbodies.
368
+
369
+ Example
370
+ =======
371
+
372
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody
373
+ >>> from sympy.physics.mechanics.functions import gravity
374
+ >>> from sympy import symbols
375
+ >>> N = ReferenceFrame('N')
376
+ >>> m, M, g = symbols('m M g')
377
+ >>> F1, F2 = symbols('F1 F2')
378
+ >>> po = Point('po')
379
+ >>> pa = Particle('pa', po, m)
380
+ >>> A = ReferenceFrame('A')
381
+ >>> P = Point('P')
382
+ >>> I = outer(A.x, A.x)
383
+ >>> B = RigidBody('B', P, A, M, (I, P))
384
+ >>> forceList = [(po, F1), (P, F2)]
385
+ >>> forceList.extend(gravity(g*N.y, pa, B))
386
+ >>> forceList
387
+ [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)]
388
+
389
+ """
390
+
391
+ gravity_force = []
392
+ if not bodies:
393
+ raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
394
+
395
+ for e in bodies:
396
+ point = getattr(e, 'masscenter', None)
397
+ if point is None:
398
+ point = e.point
399
+
400
+ gravity_force.append((point, e.mass*acceleration))
401
+
402
+ return gravity_force
403
+
404
+
405
+ def center_of_mass(point, *bodies):
406
+ """
407
+ Returns the position vector from the given point to the center of mass
408
+ of the given bodies(particles or rigidbodies).
409
+
410
+ Example
411
+ =======
412
+
413
+ >>> from sympy import symbols, S
414
+ >>> from sympy.physics.vector import Point
415
+ >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
416
+ >>> from sympy.physics.mechanics.functions import center_of_mass
417
+ >>> a = ReferenceFrame('a')
418
+ >>> m = symbols('m', real=True)
419
+ >>> p1 = Particle('p1', Point('p1_pt'), S(1))
420
+ >>> p2 = Particle('p2', Point('p2_pt'), S(2))
421
+ >>> p3 = Particle('p3', Point('p3_pt'), S(3))
422
+ >>> p4 = Particle('p4', Point('p4_pt'), m)
423
+ >>> b_f = ReferenceFrame('b_f')
424
+ >>> b_cm = Point('b_cm')
425
+ >>> mb = symbols('mb')
426
+ >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
427
+ >>> p2.point.set_pos(p1.point, a.x)
428
+ >>> p3.point.set_pos(p1.point, a.x + a.y)
429
+ >>> p4.point.set_pos(p1.point, a.y)
430
+ >>> b.masscenter.set_pos(p1.point, a.y + a.z)
431
+ >>> point_o=Point('o')
432
+ >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
433
+ >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
434
+ >>> point_o.pos_from(p1.point)
435
+ 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
436
+
437
+ """
438
+ if not bodies:
439
+ raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
440
+
441
+ total_mass = 0
442
+ vec = Vector(0)
443
+ for i in bodies:
444
+ total_mass += i.mass
445
+
446
+ masscenter = getattr(i, 'masscenter', None)
447
+ if masscenter is None:
448
+ masscenter = i.point
449
+ vec += i.mass*masscenter.pos_from(point)
450
+
451
+ return vec/total_mass
452
+
453
+
454
+ def Lagrangian(frame, *body):
455
+ """Lagrangian of a multibody system.
456
+
457
+ Explanation
458
+ ===========
459
+
460
+ This function returns the Lagrangian of a system of Particle's and/or
461
+ RigidBody's. The Lagrangian of such a system is equal to the difference
462
+ between the kinetic energies and potential energies of its constituents. If
463
+ T and V are the kinetic and potential energies of a system then it's
464
+ Lagrangian, L, is defined as
465
+
466
+ L = T - V
467
+
468
+ The Lagrangian is a scalar.
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ frame : ReferenceFrame
474
+ The frame in which the velocity or angular velocity of the body is
475
+ defined to determine the kinetic energy.
476
+
477
+ body1, body2, body3... : Particle and/or RigidBody
478
+ The body (or bodies) whose Lagrangian is required.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
484
+ >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
485
+ >>> from sympy import symbols
486
+ >>> M, m, g, h = symbols('M m g h')
487
+ >>> N = ReferenceFrame('N')
488
+ >>> O = Point('O')
489
+ >>> O.set_vel(N, 0 * N.x)
490
+ >>> P = O.locatenew('P', 1 * N.x)
491
+ >>> P.set_vel(N, 10 * N.x)
492
+ >>> Pa = Particle('Pa', P, 1)
493
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
494
+ >>> Ac.set_vel(N, 5 * N.y)
495
+ >>> a = ReferenceFrame('a')
496
+ >>> a.set_ang_vel(N, 10 * N.z)
497
+ >>> I = outer(N.z, N.z)
498
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
499
+ >>> Pa.potential_energy = m * g * h
500
+ >>> A.potential_energy = M * g * h
501
+ >>> Lagrangian(N, Pa, A)
502
+ -M*g*h - g*h*m + 350
503
+
504
+ """
505
+
506
+ if not isinstance(frame, ReferenceFrame):
507
+ raise TypeError('Please supply a valid ReferenceFrame')
508
+ for e in body:
509
+ if not isinstance(e, (RigidBody, Particle)):
510
+ raise TypeError('*body must have only Particle or RigidBody')
511
+ return kinetic_energy(frame, *body) - potential_energy(*body)
512
+
513
+
514
+ def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
515
+ """Find all dynamicsymbols in expression.
516
+
517
+ Explanation
518
+ ===========
519
+
520
+ If the optional ``exclude`` kwarg is used, only dynamicsymbols
521
+ not in the iterable ``exclude`` are returned.
522
+ If we intend to apply this function on a vector, the optional
523
+ ``reference_frame`` is also used to inform about the corresponding frame
524
+ with respect to which the dynamic symbols of the given vector is to be
525
+ determined.
526
+
527
+ Parameters
528
+ ==========
529
+
530
+ expression : SymPy expression
531
+
532
+ exclude : iterable of dynamicsymbols, optional
533
+
534
+ reference_frame : ReferenceFrame, optional
535
+ The frame with respect to which the dynamic symbols of the
536
+ given vector is to be determined.
537
+
538
+ Examples
539
+ ========
540
+
541
+ >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
542
+ >>> from sympy.physics.mechanics import ReferenceFrame
543
+ >>> x, y = dynamicsymbols('x, y')
544
+ >>> expr = x + x.diff()*y
545
+ >>> find_dynamicsymbols(expr)
546
+ {x(t), y(t), Derivative(x(t), t)}
547
+ >>> find_dynamicsymbols(expr, exclude=[x, y])
548
+ {Derivative(x(t), t)}
549
+ >>> a, b, c = dynamicsymbols('a, b, c')
550
+ >>> A = ReferenceFrame('A')
551
+ >>> v = a * A.x + b * A.y + c * A.z
552
+ >>> find_dynamicsymbols(v, reference_frame=A)
553
+ {a(t), b(t), c(t)}
554
+
555
+ """
556
+ t_set = {dynamicsymbols._t}
557
+ if exclude:
558
+ if iterable(exclude):
559
+ exclude_set = set(exclude)
560
+ else:
561
+ raise TypeError("exclude kwarg must be iterable")
562
+ else:
563
+ exclude_set = set()
564
+ if isinstance(expression, Vector):
565
+ if reference_frame is None:
566
+ raise ValueError("You must provide reference_frame when passing a "
567
+ "vector expression, got %s." % reference_frame)
568
+ else:
569
+ expression = expression.to_matrix(reference_frame)
570
+ return {i for i in expression.atoms(AppliedUndef, Derivative) if
571
+ i.free_symbols == t_set} - exclude_set
572
+
573
+
574
+ def msubs(expr, *sub_dicts, smart=False, **kwargs):
575
+ """A custom subs for use on expressions derived in physics.mechanics.
576
+
577
+ Traverses the expression tree once, performing the subs found in sub_dicts.
578
+ Terms inside ``Derivative`` expressions are ignored:
579
+
580
+ Examples
581
+ ========
582
+
583
+ >>> from sympy.physics.mechanics import dynamicsymbols, msubs
584
+ >>> x = dynamicsymbols('x')
585
+ >>> msubs(x.diff() + x, {x: 1})
586
+ Derivative(x(t), t) + 1
587
+
588
+ Note that sub_dicts can be a single dictionary, or several dictionaries:
589
+
590
+ >>> x, y, z = dynamicsymbols('x, y, z')
591
+ >>> sub1 = {x: 1, y: 2}
592
+ >>> sub2 = {z: 3, x.diff(): 4}
593
+ >>> msubs(x.diff() + x + y + z, sub1, sub2)
594
+ 10
595
+
596
+ If smart=True (default False), also checks for conditions that may result
597
+ in ``nan``, but if simplified would yield a valid expression. For example:
598
+
599
+ >>> from sympy import sin, tan
600
+ >>> (sin(x)/tan(x)).subs(x, 0)
601
+ nan
602
+ >>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
603
+ 1
604
+
605
+ It does this by first replacing all ``tan`` with ``sin/cos``. Then each
606
+ node is traversed. If the node is a fraction, subs is first evaluated on
607
+ the denominator. If this results in 0, simplification of the entire
608
+ fraction is attempted. Using this selective simplification, only
609
+ subexpressions that result in 1/0 are targeted, resulting in faster
610
+ performance.
611
+
612
+ """
613
+
614
+ sub_dict = dict_merge(*sub_dicts)
615
+ if smart:
616
+ func = _smart_subs
617
+ elif hasattr(expr, 'msubs'):
618
+ return expr.msubs(sub_dict)
619
+ else:
620
+ func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
621
+ if isinstance(expr, (Matrix, Vector, Dyadic)):
622
+ return expr.applyfunc(lambda x: func(x, sub_dict))
623
+ else:
624
+ return func(expr, sub_dict)
625
+
626
+
627
+ def _crawl(expr, func, *args, **kwargs):
628
+ """Crawl the expression tree, and apply func to every node."""
629
+ val = func(expr, *args, **kwargs)
630
+ if val is not None:
631
+ return val
632
+ new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
633
+ return expr.func(*new_args)
634
+
635
+
636
+ def _sub_func(expr, sub_dict):
637
+ """Perform direct matching substitution, ignoring derivatives."""
638
+ if expr in sub_dict:
639
+ return sub_dict[expr]
640
+ elif not expr.args or expr.is_Derivative:
641
+ return expr
642
+
643
+
644
+ def _tan_repl_func(expr):
645
+ """Replace tan with sin/cos."""
646
+ if isinstance(expr, tan):
647
+ return sin(*expr.args) / cos(*expr.args)
648
+ elif not expr.args or expr.is_Derivative:
649
+ return expr
650
+
651
+
652
+ def _smart_subs(expr, sub_dict):
653
+ """Performs subs, checking for conditions that may result in `nan` or
654
+ `oo`, and attempts to simplify them out.
655
+
656
+ The expression tree is traversed twice, and the following steps are
657
+ performed on each expression node:
658
+ - First traverse:
659
+ Replace all `tan` with `sin/cos`.
660
+ - Second traverse:
661
+ If node is a fraction, check if the denominator evaluates to 0.
662
+ If so, attempt to simplify it out. Then if node is in sub_dict,
663
+ sub in the corresponding value.
664
+
665
+ """
666
+ expr = _crawl(expr, _tan_repl_func)
667
+
668
+ def _recurser(expr, sub_dict):
669
+ # Decompose the expression into num, den
670
+ num, den = _fraction_decomp(expr)
671
+ if den != 1:
672
+ # If there is a non trivial denominator, we need to handle it
673
+ denom_subbed = _recurser(den, sub_dict)
674
+ if denom_subbed.evalf() == 0:
675
+ # If denom is 0 after this, attempt to simplify the bad expr
676
+ expr = simplify(expr)
677
+ else:
678
+ # Expression won't result in nan, find numerator
679
+ num_subbed = _recurser(num, sub_dict)
680
+ return num_subbed / denom_subbed
681
+ # We have to crawl the tree manually, because `expr` may have been
682
+ # modified in the simplify step. First, perform subs as normal:
683
+ val = _sub_func(expr, sub_dict)
684
+ if val is not None:
685
+ return val
686
+ new_args = (_recurser(arg, sub_dict) for arg in expr.args)
687
+ return expr.func(*new_args)
688
+ return _recurser(expr, sub_dict)
689
+
690
+
691
+ def _fraction_decomp(expr):
692
+ """Return num, den such that expr = num/den."""
693
+ if not isinstance(expr, Mul):
694
+ return expr, 1
695
+ num = []
696
+ den = []
697
+ for a in expr.args:
698
+ if a.is_Pow and a.args[1] < 0:
699
+ den.append(1 / a)
700
+ else:
701
+ num.append(a)
702
+ if not den:
703
+ return expr, 1
704
+ num = Mul(*num)
705
+ den = Mul(*den)
706
+ return num, den
707
+
708
+
709
+ def _f_list_parser(fl, ref_frame):
710
+ """Parses the provided forcelist composed of items
711
+ of the form (obj, force).
712
+ Returns a tuple containing:
713
+ vel_list: The velocity (ang_vel for Frames, vel for Points) in
714
+ the provided reference frame.
715
+ f_list: The forces.
716
+
717
+ Used internally in the KanesMethod and LagrangesMethod classes.
718
+
719
+ """
720
+ def flist_iter():
721
+ for pair in fl:
722
+ obj, force = pair
723
+ if isinstance(obj, ReferenceFrame):
724
+ yield obj.ang_vel_in(ref_frame), force
725
+ elif isinstance(obj, Point):
726
+ yield obj.vel(ref_frame), force
727
+ else:
728
+ raise TypeError('First entry in each forcelist pair must '
729
+ 'be a point or frame.')
730
+
731
+ if not fl:
732
+ vel_list, f_list = (), ()
733
+ else:
734
+ unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
735
+ vel_list, f_list = unzip(list(flist_iter()))
736
+ return vel_list, f_list
737
+
738
+
739
+ def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True,
740
+ is_dynamicsymbols=True):
741
+ t_set = {dynamicsymbols._t}
742
+ # Convert input to iterables
743
+ if coordinates is None:
744
+ coordinates = []
745
+ elif not iterable(coordinates):
746
+ coordinates = [coordinates]
747
+ if speeds is None:
748
+ speeds = []
749
+ elif not iterable(speeds):
750
+ speeds = [speeds]
751
+
752
+ if check_duplicates: # Check for duplicates
753
+ seen = set()
754
+ coord_duplicates = {x for x in coordinates if x in seen or seen.add(x)}
755
+ seen = set()
756
+ speed_duplicates = {x for x in speeds if x in seen or seen.add(x)}
757
+ overlap = set(coordinates).intersection(speeds)
758
+ if coord_duplicates:
759
+ raise ValueError(f'The generalized coordinates {coord_duplicates} '
760
+ f'are duplicated, all generalized coordinates '
761
+ f'should be unique.')
762
+ if speed_duplicates:
763
+ raise ValueError(f'The generalized speeds {speed_duplicates} are '
764
+ f'duplicated, all generalized speeds should be '
765
+ f'unique.')
766
+ if overlap:
767
+ raise ValueError(f'{overlap} are defined as both generalized '
768
+ f'coordinates and generalized speeds.')
769
+ if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols
770
+ for coordinate in coordinates:
771
+ if not (isinstance(coordinate, (AppliedUndef, Derivative)) and
772
+ coordinate.free_symbols == t_set):
773
+ raise ValueError(f'Generalized coordinate "{coordinate}" is not'
774
+ f' a dynamicsymbol.')
775
+ for speed in speeds:
776
+ if not (isinstance(speed, (AppliedUndef, Derivative)) and
777
+ speed.free_symbols == t_set):
778
+ raise ValueError(f'Generalized speed "{speed}" is not a '
779
+ f'dynamicsymbol.')
venv/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py ADDED
@@ -0,0 +1,2163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy.core.backend import pi, AppliedUndef, Derivative, Matrix
6
+ from sympy.physics.mechanics.body import Body
7
+ from sympy.physics.mechanics.functions import _validate_coordinates
8
+ from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point,
9
+ ReferenceFrame)
10
+ from sympy.utilities.iterables import iterable
11
+ from sympy.utilities.exceptions import sympy_deprecation_warning
12
+
13
+ __all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint',
14
+ 'PlanarJoint', 'SphericalJoint', 'WeldJoint']
15
+
16
+
17
+ class Joint(ABC):
18
+ """Abstract base class for all specific joints.
19
+
20
+ Explanation
21
+ ===========
22
+
23
+ A joint subtracts degrees of freedom from a body. This is the base class
24
+ for all specific joints and holds all common methods acting as an interface
25
+ for all joints. Custom joint can be created by inheriting Joint class and
26
+ defining all abstract functions.
27
+
28
+ The abstract methods are:
29
+
30
+ - ``_generate_coordinates``
31
+ - ``_generate_speeds``
32
+ - ``_orient_frames``
33
+ - ``_set_angular_velocity``
34
+ - ``_set_linear_velocity``
35
+
36
+ Parameters
37
+ ==========
38
+
39
+ name : string
40
+ A unique name for the joint.
41
+ parent : Body
42
+ The parent body of joint.
43
+ child : Body
44
+ The child body of joint.
45
+ coordinates : iterable of dynamicsymbols, optional
46
+ Generalized coordinates of the joint.
47
+ speeds : iterable of dynamicsymbols, optional
48
+ Generalized speeds of joint.
49
+ parent_point : Point or Vector, optional
50
+ Attachment point where the joint is fixed to the parent body. If a
51
+ vector is provided, then the attachment point is computed by adding the
52
+ vector to the body's mass center. The default value is the parent's mass
53
+ center.
54
+ child_point : Point or Vector, optional
55
+ Attachment point where the joint is fixed to the child body. If a
56
+ vector is provided, then the attachment point is computed by adding the
57
+ vector to the body's mass center. The default value is the child's mass
58
+ center.
59
+ parent_axis : Vector, optional
60
+ .. deprecated:: 1.12
61
+ Axis fixed in the parent body which aligns with an axis fixed in the
62
+ child body. The default is the x axis of parent's reference frame.
63
+ For more information on this deprecation, see
64
+ :ref:`deprecated-mechanics-joint-axis`.
65
+ child_axis : Vector, optional
66
+ .. deprecated:: 1.12
67
+ Axis fixed in the child body which aligns with an axis fixed in the
68
+ parent body. The default is the x axis of child's reference frame.
69
+ For more information on this deprecation, see
70
+ :ref:`deprecated-mechanics-joint-axis`.
71
+ parent_interframe : ReferenceFrame, optional
72
+ Intermediate frame of the parent body with respect to which the joint
73
+ transformation is formulated. If a Vector is provided then an interframe
74
+ is created which aligns its X axis with the given vector. The default
75
+ value is the parent's own frame.
76
+ child_interframe : ReferenceFrame, optional
77
+ Intermediate frame of the child body with respect to which the joint
78
+ transformation is formulated. If a Vector is provided then an interframe
79
+ is created which aligns its X axis with the given vector. The default
80
+ value is the child's own frame.
81
+ parent_joint_pos : Point or Vector, optional
82
+ .. deprecated:: 1.12
83
+ This argument is replaced by parent_point and will be removed in a
84
+ future version.
85
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
86
+ child_joint_pos : Point or Vector, optional
87
+ .. deprecated:: 1.12
88
+ This argument is replaced by child_point and will be removed in a
89
+ future version.
90
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
91
+
92
+ Attributes
93
+ ==========
94
+
95
+ name : string
96
+ The joint's name.
97
+ parent : Body
98
+ The joint's parent body.
99
+ child : Body
100
+ The joint's child body.
101
+ coordinates : Matrix
102
+ Matrix of the joint's generalized coordinates.
103
+ speeds : Matrix
104
+ Matrix of the joint's generalized speeds.
105
+ parent_point : Point
106
+ Attachment point where the joint is fixed to the parent body.
107
+ child_point : Point
108
+ Attachment point where the joint is fixed to the child body.
109
+ parent_axis : Vector
110
+ The axis fixed in the parent frame that represents the joint.
111
+ child_axis : Vector
112
+ The axis fixed in the child frame that represents the joint.
113
+ parent_interframe : ReferenceFrame
114
+ Intermediate frame of the parent body with respect to which the joint
115
+ transformation is formulated.
116
+ child_interframe : ReferenceFrame
117
+ Intermediate frame of the child body with respect to which the joint
118
+ transformation is formulated.
119
+ kdes : Matrix
120
+ Kinematical differential equations of the joint.
121
+
122
+ Notes
123
+ =====
124
+
125
+ When providing a vector as the intermediate frame, a new intermediate frame
126
+ is created which aligns its X axis with the provided vector. This is done
127
+ with a single fixed rotation about a rotation axis. This rotation axis is
128
+ determined by taking the cross product of the ``body.x`` axis with the
129
+ provided vector. In the case where the provided vector is in the ``-body.x``
130
+ direction, the rotation is done about the ``body.y`` axis.
131
+
132
+ """
133
+
134
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
135
+ parent_point=None, child_point=None, parent_axis=None,
136
+ child_axis=None, parent_interframe=None, child_interframe=None,
137
+ parent_joint_pos=None, child_joint_pos=None):
138
+
139
+ if not isinstance(name, str):
140
+ raise TypeError('Supply a valid name.')
141
+ self._name = name
142
+
143
+ if not isinstance(parent, Body):
144
+ raise TypeError('Parent must be an instance of Body.')
145
+ self._parent = parent
146
+
147
+ if not isinstance(child, Body):
148
+ raise TypeError('Parent must be an instance of Body.')
149
+ self._child = child
150
+
151
+ self._coordinates = self._generate_coordinates(coordinates)
152
+ self._speeds = self._generate_speeds(speeds)
153
+ _validate_coordinates(self.coordinates, self.speeds)
154
+ self._kdes = self._generate_kdes()
155
+
156
+ self._parent_axis = self._axis(parent_axis, parent.frame)
157
+ self._child_axis = self._axis(child_axis, child.frame)
158
+
159
+ if parent_joint_pos is not None or child_joint_pos is not None:
160
+ sympy_deprecation_warning(
161
+ """
162
+ The parent_joint_pos and child_joint_pos arguments for the Joint
163
+ classes are deprecated. Instead use parent_point and child_point.
164
+ """,
165
+ deprecated_since_version="1.12",
166
+ active_deprecations_target="deprecated-mechanics-joint-pos",
167
+ stacklevel=4
168
+ )
169
+ if parent_point is None:
170
+ parent_point = parent_joint_pos
171
+ if child_point is None:
172
+ child_point = child_joint_pos
173
+ self._parent_point = self._locate_joint_pos(parent, parent_point)
174
+ self._child_point = self._locate_joint_pos(child, child_point)
175
+ if parent_axis is not None or child_axis is not None:
176
+ sympy_deprecation_warning(
177
+ """
178
+ The parent_axis and child_axis arguments for the Joint classes
179
+ are deprecated. Instead use parent_interframe, child_interframe.
180
+ """,
181
+ deprecated_since_version="1.12",
182
+ active_deprecations_target="deprecated-mechanics-joint-axis",
183
+ stacklevel=4
184
+ )
185
+ if parent_interframe is None:
186
+ parent_interframe = parent_axis
187
+ if child_interframe is None:
188
+ child_interframe = child_axis
189
+ self._parent_interframe = self._locate_joint_frame(parent,
190
+ parent_interframe)
191
+ self._child_interframe = self._locate_joint_frame(child,
192
+ child_interframe)
193
+
194
+ self._orient_frames()
195
+ self._set_angular_velocity()
196
+ self._set_linear_velocity()
197
+
198
+ def __str__(self):
199
+ return self.name
200
+
201
+ def __repr__(self):
202
+ return self.__str__()
203
+
204
+ @property
205
+ def name(self):
206
+ """Name of the joint."""
207
+ return self._name
208
+
209
+ @property
210
+ def parent(self):
211
+ """Parent body of Joint."""
212
+ return self._parent
213
+
214
+ @property
215
+ def child(self):
216
+ """Child body of Joint."""
217
+ return self._child
218
+
219
+ @property
220
+ def coordinates(self):
221
+ """Matrix of the joint's generalized coordinates."""
222
+ return self._coordinates
223
+
224
+ @property
225
+ def speeds(self):
226
+ """Matrix of the joint's generalized speeds."""
227
+ return self._speeds
228
+
229
+ @property
230
+ def kdes(self):
231
+ """Kinematical differential equations of the joint."""
232
+ return self._kdes
233
+
234
+ @property
235
+ def parent_axis(self):
236
+ """The axis of parent frame."""
237
+ # Will be removed with `deprecated-mechanics-joint-axis`
238
+ return self._parent_axis
239
+
240
+ @property
241
+ def child_axis(self):
242
+ """The axis of child frame."""
243
+ # Will be removed with `deprecated-mechanics-joint-axis`
244
+ return self._child_axis
245
+
246
+ @property
247
+ def parent_point(self):
248
+ """Attachment point where the joint is fixed to the parent body."""
249
+ return self._parent_point
250
+
251
+ @property
252
+ def child_point(self):
253
+ """Attachment point where the joint is fixed to the child body."""
254
+ return self._child_point
255
+
256
+ @property
257
+ def parent_interframe(self):
258
+ return self._parent_interframe
259
+
260
+ @property
261
+ def child_interframe(self):
262
+ return self._child_interframe
263
+
264
+ @abstractmethod
265
+ def _generate_coordinates(self, coordinates):
266
+ """Generate Matrix of the joint's generalized coordinates."""
267
+ pass
268
+
269
+ @abstractmethod
270
+ def _generate_speeds(self, speeds):
271
+ """Generate Matrix of the joint's generalized speeds."""
272
+ pass
273
+
274
+ @abstractmethod
275
+ def _orient_frames(self):
276
+ """Orient frames as per the joint."""
277
+ pass
278
+
279
+ @abstractmethod
280
+ def _set_angular_velocity(self):
281
+ """Set angular velocity of the joint related frames."""
282
+ pass
283
+
284
+ @abstractmethod
285
+ def _set_linear_velocity(self):
286
+ """Set velocity of related points to the joint."""
287
+ pass
288
+
289
+ @staticmethod
290
+ def _to_vector(matrix, frame):
291
+ """Converts a matrix to a vector in the given frame."""
292
+ return Vector([(matrix, frame)])
293
+
294
+ @staticmethod
295
+ def _axis(ax, *frames):
296
+ """Check whether an axis is fixed in one of the frames."""
297
+ if ax is None:
298
+ ax = frames[0].x
299
+ return ax
300
+ if not isinstance(ax, Vector):
301
+ raise TypeError("Axis must be a Vector.")
302
+ ref_frame = None # Find a body in which the axis can be expressed
303
+ for frame in frames:
304
+ try:
305
+ ax.to_matrix(frame)
306
+ except ValueError:
307
+ pass
308
+ else:
309
+ ref_frame = frame
310
+ break
311
+ if ref_frame is None:
312
+ raise ValueError("Axis cannot be expressed in one of the body's "
313
+ "frames.")
314
+ if not ax.dt(ref_frame) == 0:
315
+ raise ValueError('Axis cannot be time-varying when viewed from the '
316
+ 'associated body.')
317
+ return ax
318
+
319
+ @staticmethod
320
+ def _choose_rotation_axis(frame, axis):
321
+ components = axis.to_matrix(frame)
322
+ x, y, z = components[0], components[1], components[2]
323
+
324
+ if x != 0:
325
+ if y != 0:
326
+ if z != 0:
327
+ return cross(axis, frame.x)
328
+ if z != 0:
329
+ return frame.y
330
+ return frame.z
331
+ else:
332
+ if y != 0:
333
+ return frame.x
334
+ return frame.y
335
+
336
+ @staticmethod
337
+ def _create_aligned_interframe(frame, align_axis, frame_axis=None,
338
+ frame_name=None):
339
+ """
340
+ Returns an intermediate frame, where the ``frame_axis`` defined in
341
+ ``frame`` is aligned with ``axis``. By default this means that the X
342
+ axis will be aligned with ``axis``.
343
+
344
+ Parameters
345
+ ==========
346
+
347
+ frame : Body or ReferenceFrame
348
+ The body or reference frame with respect to which the intermediate
349
+ frame is oriented.
350
+ align_axis : Vector
351
+ The vector with respect to which the intermediate frame will be
352
+ aligned.
353
+ frame_axis : Vector
354
+ The vector of the frame which should get aligned with ``axis``. The
355
+ default is the X axis of the frame.
356
+ frame_name : string
357
+ Name of the to be created intermediate frame. The default adds
358
+ "_int_frame" to the name of ``frame``.
359
+
360
+ Example
361
+ =======
362
+
363
+ An intermediate frame, where the X axis of the parent becomes aligned
364
+ with ``parent.y + parent.z`` can be created as follows:
365
+
366
+ >>> from sympy.physics.mechanics.joint import Joint
367
+ >>> from sympy.physics.mechanics import Body
368
+ >>> parent = Body('parent')
369
+ >>> parent_interframe = Joint._create_aligned_interframe(
370
+ ... parent, parent.y + parent.z)
371
+ >>> parent_interframe
372
+ parent_int_frame
373
+ >>> parent.dcm(parent_interframe)
374
+ Matrix([
375
+ [ 0, -sqrt(2)/2, -sqrt(2)/2],
376
+ [sqrt(2)/2, 1/2, -1/2],
377
+ [sqrt(2)/2, -1/2, 1/2]])
378
+ >>> (parent.y + parent.z).express(parent_interframe)
379
+ sqrt(2)*parent_int_frame.x
380
+
381
+ Notes
382
+ =====
383
+
384
+ The direction cosine matrix between the given frame and intermediate
385
+ frame is formed using a simple rotation about an axis that is normal to
386
+ both ``align_axis`` and ``frame_axis``. In general, the normal axis is
387
+ formed by crossing the ``frame_axis`` with the ``align_axis``. The
388
+ exception is if the axes are parallel with opposite directions, in which
389
+ case the rotation vector is chosen using the rules in the following
390
+ table with the vectors expressed in the given frame:
391
+
392
+ .. list-table::
393
+ :header-rows: 1
394
+
395
+ * - ``align_axis``
396
+ - ``frame_axis``
397
+ - ``rotation_axis``
398
+ * - ``-x``
399
+ - ``x``
400
+ - ``z``
401
+ * - ``-y``
402
+ - ``y``
403
+ - ``x``
404
+ * - ``-z``
405
+ - ``z``
406
+ - ``y``
407
+ * - ``-x-y``
408
+ - ``x+y``
409
+ - ``z``
410
+ * - ``-y-z``
411
+ - ``y+z``
412
+ - ``x``
413
+ * - ``-x-z``
414
+ - ``x+z``
415
+ - ``y``
416
+ * - ``-x-y-z``
417
+ - ``x+y+z``
418
+ - ``(x+y+z) × x``
419
+
420
+ """
421
+ if isinstance(frame, Body):
422
+ frame = frame.frame
423
+ if frame_axis is None:
424
+ frame_axis = frame.x
425
+ if frame_name is None:
426
+ if frame.name[-6:] == '_frame':
427
+ frame_name = f'{frame.name[:-6]}_int_frame'
428
+ else:
429
+ frame_name = f'{frame.name}_int_frame'
430
+ angle = frame_axis.angle_between(align_axis)
431
+ rotation_axis = cross(frame_axis, align_axis)
432
+ if rotation_axis == Vector(0) and angle == 0:
433
+ return frame
434
+ if angle == pi:
435
+ rotation_axis = Joint._choose_rotation_axis(frame, align_axis)
436
+
437
+ int_frame = ReferenceFrame(frame_name)
438
+ int_frame.orient_axis(frame, rotation_axis, angle)
439
+ int_frame.set_ang_vel(frame, 0 * rotation_axis)
440
+ return int_frame
441
+
442
+ def _generate_kdes(self):
443
+ """Generate kinematical differential equations."""
444
+ kdes = []
445
+ t = dynamicsymbols._t
446
+ for i in range(len(self.coordinates)):
447
+ kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
448
+ return Matrix(kdes)
449
+
450
+ def _locate_joint_pos(self, body, joint_pos):
451
+ """Returns the attachment point of a body."""
452
+ if joint_pos is None:
453
+ return body.masscenter
454
+ if not isinstance(joint_pos, (Point, Vector)):
455
+ raise TypeError('Attachment point must be a Point or Vector.')
456
+ if isinstance(joint_pos, Vector):
457
+ point_name = f'{self.name}_{body.name}_joint'
458
+ joint_pos = body.masscenter.locatenew(point_name, joint_pos)
459
+ if not joint_pos.pos_from(body.masscenter).dt(body.frame) == 0:
460
+ raise ValueError('Attachment point must be fixed to the associated '
461
+ 'body.')
462
+ return joint_pos
463
+
464
+ def _locate_joint_frame(self, body, interframe):
465
+ """Returns the attachment frame of a body."""
466
+ if interframe is None:
467
+ return body.frame
468
+ if isinstance(interframe, Vector):
469
+ interframe = Joint._create_aligned_interframe(
470
+ body, interframe,
471
+ frame_name=f'{self.name}_{body.name}_int_frame')
472
+ elif not isinstance(interframe, ReferenceFrame):
473
+ raise TypeError('Interframe must be a ReferenceFrame.')
474
+ if not interframe.ang_vel_in(body.frame) == 0:
475
+ raise ValueError(f'Interframe {interframe} is not fixed to body '
476
+ f'{body}.')
477
+ body.masscenter.set_vel(interframe, 0) # Fixate interframe to body
478
+ return interframe
479
+
480
+ def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0,
481
+ number_single=False):
482
+ """Helper method for _generate_coordinates and _generate_speeds.
483
+
484
+ Parameters
485
+ ==========
486
+
487
+ coordinates : iterable
488
+ Iterable of coordinates or speeds that have been provided.
489
+ n_coords : Integer
490
+ Number of coordinates that should be returned.
491
+ label : String, optional
492
+ Coordinate type either 'q' (coordinates) or 'u' (speeds). The
493
+ Default is 'q'.
494
+ offset : Integer
495
+ Count offset when creating new dynamicsymbols. The default is 0.
496
+ number_single : Boolean
497
+ Boolean whether if n_coords == 1, number should still be used. The
498
+ default is False.
499
+
500
+ """
501
+
502
+ def create_symbol(number):
503
+ if n_coords == 1 and not number_single:
504
+ return dynamicsymbols(f'{label}_{self.name}')
505
+ return dynamicsymbols(f'{label}{number}_{self.name}')
506
+
507
+ name = 'generalized coordinate' if label == 'q' else 'generalized speed'
508
+ generated_coordinates = []
509
+ if coordinates is None:
510
+ coordinates = []
511
+ elif not iterable(coordinates):
512
+ coordinates = [coordinates]
513
+ if not (len(coordinates) == 0 or len(coordinates) == n_coords):
514
+ raise ValueError(f'Expected {n_coords} {name}s, instead got '
515
+ f'{len(coordinates)} {name}s.')
516
+ # Supports more iterables, also Matrix
517
+ for i, coord in enumerate(coordinates):
518
+ if coord is None:
519
+ generated_coordinates.append(create_symbol(i + offset))
520
+ elif isinstance(coord, (AppliedUndef, Derivative)):
521
+ generated_coordinates.append(coord)
522
+ else:
523
+ raise TypeError(f'The {name} {coord} should have been a '
524
+ f'dynamicsymbol.')
525
+ for i in range(len(coordinates) + offset, n_coords + offset):
526
+ generated_coordinates.append(create_symbol(i))
527
+ return Matrix(generated_coordinates)
528
+
529
+
530
+ class PinJoint(Joint):
531
+ """Pin (Revolute) Joint.
532
+
533
+ .. image:: PinJoint.svg
534
+
535
+ Explanation
536
+ ===========
537
+
538
+ A pin joint is defined such that the joint rotation axis is fixed in both
539
+ the child and parent and the location of the joint is relative to the mass
540
+ center of each body. The child rotates an angle, θ, from the parent about
541
+ the rotation axis and has a simple angular speed, ω, relative to the
542
+ parent. The direction cosine matrix between the child interframe and
543
+ parent interframe is formed using a simple rotation about the joint axis.
544
+ The page on the joints framework gives a more detailed explanation of the
545
+ intermediate frames.
546
+
547
+ Parameters
548
+ ==========
549
+
550
+ name : string
551
+ A unique name for the joint.
552
+ parent : Body
553
+ The parent body of joint.
554
+ child : Body
555
+ The child body of joint.
556
+ coordinates : dynamicsymbol, optional
557
+ Generalized coordinates of the joint.
558
+ speeds : dynamicsymbol, optional
559
+ Generalized speeds of joint.
560
+ parent_point : Point or Vector, optional
561
+ Attachment point where the joint is fixed to the parent body. If a
562
+ vector is provided, then the attachment point is computed by adding the
563
+ vector to the body's mass center. The default value is the parent's mass
564
+ center.
565
+ child_point : Point or Vector, optional
566
+ Attachment point where the joint is fixed to the child body. If a
567
+ vector is provided, then the attachment point is computed by adding the
568
+ vector to the body's mass center. The default value is the child's mass
569
+ center.
570
+ parent_axis : Vector, optional
571
+ .. deprecated:: 1.12
572
+ Axis fixed in the parent body which aligns with an axis fixed in the
573
+ child body. The default is the x axis of parent's reference frame.
574
+ For more information on this deprecation, see
575
+ :ref:`deprecated-mechanics-joint-axis`.
576
+ child_axis : Vector, optional
577
+ .. deprecated:: 1.12
578
+ Axis fixed in the child body which aligns with an axis fixed in the
579
+ parent body. The default is the x axis of child's reference frame.
580
+ For more information on this deprecation, see
581
+ :ref:`deprecated-mechanics-joint-axis`.
582
+ parent_interframe : ReferenceFrame, optional
583
+ Intermediate frame of the parent body with respect to which the joint
584
+ transformation is formulated. If a Vector is provided then an interframe
585
+ is created which aligns its X axis with the given vector. The default
586
+ value is the parent's own frame.
587
+ child_interframe : ReferenceFrame, optional
588
+ Intermediate frame of the child body with respect to which the joint
589
+ transformation is formulated. If a Vector is provided then an interframe
590
+ is created which aligns its X axis with the given vector. The default
591
+ value is the child's own frame.
592
+ joint_axis : Vector
593
+ The axis about which the rotation occurs. Note that the components
594
+ of this axis are the same in the parent_interframe and child_interframe.
595
+ parent_joint_pos : Point or Vector, optional
596
+ .. deprecated:: 1.12
597
+ This argument is replaced by parent_point and will be removed in a
598
+ future version.
599
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
600
+ child_joint_pos : Point or Vector, optional
601
+ .. deprecated:: 1.12
602
+ This argument is replaced by child_point and will be removed in a
603
+ future version.
604
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
605
+
606
+ Attributes
607
+ ==========
608
+
609
+ name : string
610
+ The joint's name.
611
+ parent : Body
612
+ The joint's parent body.
613
+ child : Body
614
+ The joint's child body.
615
+ coordinates : Matrix
616
+ Matrix of the joint's generalized coordinates. The default value is
617
+ ``dynamicsymbols(f'q_{joint.name}')``.
618
+ speeds : Matrix
619
+ Matrix of the joint's generalized speeds. The default value is
620
+ ``dynamicsymbols(f'u_{joint.name}')``.
621
+ parent_point : Point
622
+ Attachment point where the joint is fixed to the parent body.
623
+ child_point : Point
624
+ Attachment point where the joint is fixed to the child body.
625
+ parent_axis : Vector
626
+ The axis fixed in the parent frame that represents the joint.
627
+ child_axis : Vector
628
+ The axis fixed in the child frame that represents the joint.
629
+ parent_interframe : ReferenceFrame
630
+ Intermediate frame of the parent body with respect to which the joint
631
+ transformation is formulated.
632
+ child_interframe : ReferenceFrame
633
+ Intermediate frame of the child body with respect to which the joint
634
+ transformation is formulated.
635
+ joint_axis : Vector
636
+ The axis about which the rotation occurs. Note that the components of
637
+ this axis are the same in the parent_interframe and child_interframe.
638
+ kdes : Matrix
639
+ Kinematical differential equations of the joint.
640
+
641
+ Examples
642
+ =========
643
+
644
+ A single pin joint is created from two bodies and has the following basic
645
+ attributes:
646
+
647
+ >>> from sympy.physics.mechanics import Body, PinJoint
648
+ >>> parent = Body('P')
649
+ >>> parent
650
+ P
651
+ >>> child = Body('C')
652
+ >>> child
653
+ C
654
+ >>> joint = PinJoint('PC', parent, child)
655
+ >>> joint
656
+ PinJoint: PC parent: P child: C
657
+ >>> joint.name
658
+ 'PC'
659
+ >>> joint.parent
660
+ P
661
+ >>> joint.child
662
+ C
663
+ >>> joint.parent_point
664
+ P_masscenter
665
+ >>> joint.child_point
666
+ C_masscenter
667
+ >>> joint.parent_axis
668
+ P_frame.x
669
+ >>> joint.child_axis
670
+ C_frame.x
671
+ >>> joint.coordinates
672
+ Matrix([[q_PC(t)]])
673
+ >>> joint.speeds
674
+ Matrix([[u_PC(t)]])
675
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
676
+ u_PC(t)*P_frame.x
677
+ >>> joint.child.frame.dcm(joint.parent.frame)
678
+ Matrix([
679
+ [1, 0, 0],
680
+ [0, cos(q_PC(t)), sin(q_PC(t))],
681
+ [0, -sin(q_PC(t)), cos(q_PC(t))]])
682
+ >>> joint.child_point.pos_from(joint.parent_point)
683
+ 0
684
+
685
+ To further demonstrate the use of the pin joint, the kinematics of simple
686
+ double pendulum that rotates about the Z axis of each connected body can be
687
+ created as follows.
688
+
689
+ >>> from sympy import symbols, trigsimp
690
+ >>> from sympy.physics.mechanics import Body, PinJoint
691
+ >>> l1, l2 = symbols('l1 l2')
692
+
693
+ First create bodies to represent the fixed ceiling and one to represent
694
+ each pendulum bob.
695
+
696
+ >>> ceiling = Body('C')
697
+ >>> upper_bob = Body('U')
698
+ >>> lower_bob = Body('L')
699
+
700
+ The first joint will connect the upper bob to the ceiling by a distance of
701
+ ``l1`` and the joint axis will be about the Z axis for each body.
702
+
703
+ >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
704
+ ... child_point=-l1*upper_bob.frame.x,
705
+ ... joint_axis=ceiling.frame.z)
706
+
707
+ The second joint will connect the lower bob to the upper bob by a distance
708
+ of ``l2`` and the joint axis will also be about the Z axis for each body.
709
+
710
+ >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
711
+ ... child_point=-l2*lower_bob.frame.x,
712
+ ... joint_axis=upper_bob.frame.z)
713
+
714
+ Once the joints are established the kinematics of the connected bodies can
715
+ be accessed. First the direction cosine matrices of pendulum link relative
716
+ to the ceiling are found:
717
+
718
+ >>> upper_bob.frame.dcm(ceiling.frame)
719
+ Matrix([
720
+ [ cos(q_P1(t)), sin(q_P1(t)), 0],
721
+ [-sin(q_P1(t)), cos(q_P1(t)), 0],
722
+ [ 0, 0, 1]])
723
+ >>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
724
+ Matrix([
725
+ [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0],
726
+ [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0],
727
+ [ 0, 0, 1]])
728
+
729
+ The position of the lower bob's masscenter is found with:
730
+
731
+ >>> lower_bob.masscenter.pos_from(ceiling.masscenter)
732
+ l1*U_frame.x + l2*L_frame.x
733
+
734
+ The angular velocities of the two pendulum links can be computed with
735
+ respect to the ceiling.
736
+
737
+ >>> upper_bob.frame.ang_vel_in(ceiling.frame)
738
+ u_P1(t)*C_frame.z
739
+ >>> lower_bob.frame.ang_vel_in(ceiling.frame)
740
+ u_P1(t)*C_frame.z + u_P2(t)*U_frame.z
741
+
742
+ And finally, the linear velocities of the two pendulum bobs can be computed
743
+ with respect to the ceiling.
744
+
745
+ >>> upper_bob.masscenter.vel(ceiling.frame)
746
+ l1*u_P1(t)*U_frame.y
747
+ >>> lower_bob.masscenter.vel(ceiling.frame)
748
+ l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y
749
+
750
+ """
751
+
752
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
753
+ parent_point=None, child_point=None, parent_axis=None,
754
+ child_axis=None, parent_interframe=None, child_interframe=None,
755
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
756
+
757
+ self._joint_axis = joint_axis
758
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
759
+ child_point, parent_axis, child_axis,
760
+ parent_interframe, child_interframe, parent_joint_pos,
761
+ child_joint_pos)
762
+
763
+ def __str__(self):
764
+ return (f'PinJoint: {self.name} parent: {self.parent} '
765
+ f'child: {self.child}')
766
+
767
+ @property
768
+ def joint_axis(self):
769
+ """Axis about which the child rotates with respect to the parent."""
770
+ return self._joint_axis
771
+
772
+ def _generate_coordinates(self, coordinate):
773
+ return self._fill_coordinate_list(coordinate, 1, 'q')
774
+
775
+ def _generate_speeds(self, speed):
776
+ return self._fill_coordinate_list(speed, 1, 'u')
777
+
778
+ def _orient_frames(self):
779
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
780
+ self.child_interframe.orient_axis(
781
+ self.parent_interframe, self.joint_axis, self.coordinates[0])
782
+
783
+ def _set_angular_velocity(self):
784
+ self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[
785
+ 0] * self.joint_axis.normalize())
786
+
787
+ def _set_linear_velocity(self):
788
+ self.child_point.set_pos(self.parent_point, 0)
789
+ self.parent_point.set_vel(self.parent.frame, 0)
790
+ self.child_point.set_vel(self.child.frame, 0)
791
+ self.child.masscenter.v2pt_theory(self.parent_point,
792
+ self.parent.frame, self.child.frame)
793
+
794
+
795
+ class PrismaticJoint(Joint):
796
+ """Prismatic (Sliding) Joint.
797
+
798
+ .. image:: PrismaticJoint.svg
799
+
800
+ Explanation
801
+ ===========
802
+
803
+ It is defined such that the child body translates with respect to the parent
804
+ body along the body-fixed joint axis. The location of the joint is defined
805
+ by two points, one in each body, which coincide when the generalized
806
+ coordinate is zero. The direction cosine matrix between the
807
+ parent_interframe and child_interframe is the identity matrix. Therefore,
808
+ the direction cosine matrix between the parent and child frames is fully
809
+ defined by the definition of the intermediate frames. The page on the joints
810
+ framework gives a more detailed explanation of the intermediate frames.
811
+
812
+ Parameters
813
+ ==========
814
+
815
+ name : string
816
+ A unique name for the joint.
817
+ parent : Body
818
+ The parent body of joint.
819
+ child : Body
820
+ The child body of joint.
821
+ coordinates : dynamicsymbol, optional
822
+ Generalized coordinates of the joint. The default value is
823
+ ``dynamicsymbols(f'q_{joint.name}')``.
824
+ speeds : dynamicsymbol, optional
825
+ Generalized speeds of joint. The default value is
826
+ ``dynamicsymbols(f'u_{joint.name}')``.
827
+ parent_point : Point or Vector, optional
828
+ Attachment point where the joint is fixed to the parent body. If a
829
+ vector is provided, then the attachment point is computed by adding the
830
+ vector to the body's mass center. The default value is the parent's mass
831
+ center.
832
+ child_point : Point or Vector, optional
833
+ Attachment point where the joint is fixed to the child body. If a
834
+ vector is provided, then the attachment point is computed by adding the
835
+ vector to the body's mass center. The default value is the child's mass
836
+ center.
837
+ parent_axis : Vector, optional
838
+ .. deprecated:: 1.12
839
+ Axis fixed in the parent body which aligns with an axis fixed in the
840
+ child body. The default is the x axis of parent's reference frame.
841
+ For more information on this deprecation, see
842
+ :ref:`deprecated-mechanics-joint-axis`.
843
+ child_axis : Vector, optional
844
+ .. deprecated:: 1.12
845
+ Axis fixed in the child body which aligns with an axis fixed in the
846
+ parent body. The default is the x axis of child's reference frame.
847
+ For more information on this deprecation, see
848
+ :ref:`deprecated-mechanics-joint-axis`.
849
+ parent_interframe : ReferenceFrame, optional
850
+ Intermediate frame of the parent body with respect to which the joint
851
+ transformation is formulated. If a Vector is provided then an interframe
852
+ is created which aligns its X axis with the given vector. The default
853
+ value is the parent's own frame.
854
+ child_interframe : ReferenceFrame, optional
855
+ Intermediate frame of the child body with respect to which the joint
856
+ transformation is formulated. If a Vector is provided then an interframe
857
+ is created which aligns its X axis with the given vector. The default
858
+ value is the child's own frame.
859
+ joint_axis : Vector
860
+ The axis along which the translation occurs. Note that the components
861
+ of this axis are the same in the parent_interframe and child_interframe.
862
+ parent_joint_pos : Point or Vector, optional
863
+ .. deprecated:: 1.12
864
+ This argument is replaced by parent_point and will be removed in a
865
+ future version.
866
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
867
+ child_joint_pos : Point or Vector, optional
868
+ .. deprecated:: 1.12
869
+ This argument is replaced by child_point and will be removed in a
870
+ future version.
871
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
872
+
873
+ Attributes
874
+ ==========
875
+
876
+ name : string
877
+ The joint's name.
878
+ parent : Body
879
+ The joint's parent body.
880
+ child : Body
881
+ The joint's child body.
882
+ coordinates : Matrix
883
+ Matrix of the joint's generalized coordinates.
884
+ speeds : Matrix
885
+ Matrix of the joint's generalized speeds.
886
+ parent_point : Point
887
+ Attachment point where the joint is fixed to the parent body.
888
+ child_point : Point
889
+ Attachment point where the joint is fixed to the child body.
890
+ parent_axis : Vector
891
+ The axis fixed in the parent frame that represents the joint.
892
+ child_axis : Vector
893
+ The axis fixed in the child frame that represents the joint.
894
+ parent_interframe : ReferenceFrame
895
+ Intermediate frame of the parent body with respect to which the joint
896
+ transformation is formulated.
897
+ child_interframe : ReferenceFrame
898
+ Intermediate frame of the child body with respect to which the joint
899
+ transformation is formulated.
900
+ kdes : Matrix
901
+ Kinematical differential equations of the joint.
902
+
903
+ Examples
904
+ =========
905
+
906
+ A single prismatic joint is created from two bodies and has the following
907
+ basic attributes:
908
+
909
+ >>> from sympy.physics.mechanics import Body, PrismaticJoint
910
+ >>> parent = Body('P')
911
+ >>> parent
912
+ P
913
+ >>> child = Body('C')
914
+ >>> child
915
+ C
916
+ >>> joint = PrismaticJoint('PC', parent, child)
917
+ >>> joint
918
+ PrismaticJoint: PC parent: P child: C
919
+ >>> joint.name
920
+ 'PC'
921
+ >>> joint.parent
922
+ P
923
+ >>> joint.child
924
+ C
925
+ >>> joint.parent_point
926
+ P_masscenter
927
+ >>> joint.child_point
928
+ C_masscenter
929
+ >>> joint.parent_axis
930
+ P_frame.x
931
+ >>> joint.child_axis
932
+ C_frame.x
933
+ >>> joint.coordinates
934
+ Matrix([[q_PC(t)]])
935
+ >>> joint.speeds
936
+ Matrix([[u_PC(t)]])
937
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
938
+ 0
939
+ >>> joint.child.frame.dcm(joint.parent.frame)
940
+ Matrix([
941
+ [1, 0, 0],
942
+ [0, 1, 0],
943
+ [0, 0, 1]])
944
+ >>> joint.child_point.pos_from(joint.parent_point)
945
+ q_PC(t)*P_frame.x
946
+
947
+ To further demonstrate the use of the prismatic joint, the kinematics of two
948
+ masses sliding, one moving relative to a fixed body and the other relative
949
+ to the moving body. about the X axis of each connected body can be created
950
+ as follows.
951
+
952
+ >>> from sympy.physics.mechanics import PrismaticJoint, Body
953
+
954
+ First create bodies to represent the fixed ceiling and one to represent
955
+ a particle.
956
+
957
+ >>> wall = Body('W')
958
+ >>> Part1 = Body('P1')
959
+ >>> Part2 = Body('P2')
960
+
961
+ The first joint will connect the particle to the ceiling and the
962
+ joint axis will be about the X axis for each body.
963
+
964
+ >>> J1 = PrismaticJoint('J1', wall, Part1)
965
+
966
+ The second joint will connect the second particle to the first particle
967
+ and the joint axis will also be about the X axis for each body.
968
+
969
+ >>> J2 = PrismaticJoint('J2', Part1, Part2)
970
+
971
+ Once the joint is established the kinematics of the connected bodies can
972
+ be accessed. First the direction cosine matrices of Part relative
973
+ to the ceiling are found:
974
+
975
+ >>> Part1.dcm(wall)
976
+ Matrix([
977
+ [1, 0, 0],
978
+ [0, 1, 0],
979
+ [0, 0, 1]])
980
+
981
+ >>> Part2.dcm(wall)
982
+ Matrix([
983
+ [1, 0, 0],
984
+ [0, 1, 0],
985
+ [0, 0, 1]])
986
+
987
+ The position of the particles' masscenter is found with:
988
+
989
+ >>> Part1.masscenter.pos_from(wall.masscenter)
990
+ q_J1(t)*W_frame.x
991
+
992
+ >>> Part2.masscenter.pos_from(wall.masscenter)
993
+ q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x
994
+
995
+ The angular velocities of the two particle links can be computed with
996
+ respect to the ceiling.
997
+
998
+ >>> Part1.ang_vel_in(wall)
999
+ 0
1000
+
1001
+ >>> Part2.ang_vel_in(wall)
1002
+ 0
1003
+
1004
+ And finally, the linear velocities of the two particles can be computed
1005
+ with respect to the ceiling.
1006
+
1007
+ >>> Part1.masscenter_vel(wall)
1008
+ u_J1(t)*W_frame.x
1009
+
1010
+ >>> Part2.masscenter.vel(wall.frame)
1011
+ u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x
1012
+
1013
+ """
1014
+
1015
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1016
+ parent_point=None, child_point=None, parent_axis=None,
1017
+ child_axis=None, parent_interframe=None, child_interframe=None,
1018
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
1019
+
1020
+ self._joint_axis = joint_axis
1021
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
1022
+ child_point, parent_axis, child_axis,
1023
+ parent_interframe, child_interframe, parent_joint_pos,
1024
+ child_joint_pos)
1025
+
1026
+ def __str__(self):
1027
+ return (f'PrismaticJoint: {self.name} parent: {self.parent} '
1028
+ f'child: {self.child}')
1029
+
1030
+ @property
1031
+ def joint_axis(self):
1032
+ """Axis along which the child translates with respect to the parent."""
1033
+ return self._joint_axis
1034
+
1035
+ def _generate_coordinates(self, coordinate):
1036
+ return self._fill_coordinate_list(coordinate, 1, 'q')
1037
+
1038
+ def _generate_speeds(self, speed):
1039
+ return self._fill_coordinate_list(speed, 1, 'u')
1040
+
1041
+ def _orient_frames(self):
1042
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1043
+ self.child_interframe.orient_axis(
1044
+ self.parent_interframe, self.joint_axis, 0)
1045
+
1046
+ def _set_angular_velocity(self):
1047
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
1048
+
1049
+ def _set_linear_velocity(self):
1050
+ axis = self.joint_axis.normalize()
1051
+ self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis)
1052
+ self.parent_point.set_vel(self.parent.frame, 0)
1053
+ self.child_point.set_vel(self.child.frame, 0)
1054
+ self.child_point.set_vel(self.parent.frame, self.speeds[0] * axis)
1055
+ self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * axis)
1056
+
1057
+
1058
+ class CylindricalJoint(Joint):
1059
+ """Cylindrical Joint.
1060
+
1061
+ .. image:: CylindricalJoint.svg
1062
+ :align: center
1063
+ :width: 600
1064
+
1065
+ Explanation
1066
+ ===========
1067
+
1068
+ A cylindrical joint is defined such that the child body both rotates about
1069
+ and translates along the body-fixed joint axis with respect to the parent
1070
+ body. The joint axis is both the rotation axis and translation axis. The
1071
+ location of the joint is defined by two points, one in each body, which
1072
+ coincide when the generalized coordinate corresponding to the translation is
1073
+ zero. The direction cosine matrix between the child interframe and parent
1074
+ interframe is formed using a simple rotation about the joint axis. The page
1075
+ on the joints framework gives a more detailed explanation of the
1076
+ intermediate frames.
1077
+
1078
+ Parameters
1079
+ ==========
1080
+
1081
+ name : string
1082
+ A unique name for the joint.
1083
+ parent : Body
1084
+ The parent body of joint.
1085
+ child : Body
1086
+ The child body of joint.
1087
+ rotation_coordinate : dynamicsymbol, optional
1088
+ Generalized coordinate corresponding to the rotation angle. The default
1089
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1090
+ translation_coordinate : dynamicsymbol, optional
1091
+ Generalized coordinate corresponding to the translation distance. The
1092
+ default value is ``dynamicsymbols(f'q1_{joint.name}')``.
1093
+ rotation_speed : dynamicsymbol, optional
1094
+ Generalized speed corresponding to the angular velocity. The default
1095
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1096
+ translation_speed : dynamicsymbol, optional
1097
+ Generalized speed corresponding to the translation velocity. The default
1098
+ value is ``dynamicsymbols(f'u1_{joint.name}')``.
1099
+ parent_point : Point or Vector, optional
1100
+ Attachment point where the joint is fixed to the parent body. If a
1101
+ vector is provided, then the attachment point is computed by adding the
1102
+ vector to the body's mass center. The default value is the parent's mass
1103
+ center.
1104
+ child_point : Point or Vector, optional
1105
+ Attachment point where the joint is fixed to the child body. If a
1106
+ vector is provided, then the attachment point is computed by adding the
1107
+ vector to the body's mass center. The default value is the child's mass
1108
+ center.
1109
+ parent_interframe : ReferenceFrame, optional
1110
+ Intermediate frame of the parent body with respect to which the joint
1111
+ transformation is formulated. If a Vector is provided then an interframe
1112
+ is created which aligns its X axis with the given vector. The default
1113
+ value is the parent's own frame.
1114
+ child_interframe : ReferenceFrame, optional
1115
+ Intermediate frame of the child body with respect to which the joint
1116
+ transformation is formulated. If a Vector is provided then an interframe
1117
+ is created which aligns its X axis with the given vector. The default
1118
+ value is the child's own frame.
1119
+ joint_axis : Vector, optional
1120
+ The rotation as well as translation axis. Note that the components of
1121
+ this axis are the same in the parent_interframe and child_interframe.
1122
+
1123
+ Attributes
1124
+ ==========
1125
+
1126
+ name : string
1127
+ The joint's name.
1128
+ parent : Body
1129
+ The joint's parent body.
1130
+ child : Body
1131
+ The joint's child body.
1132
+ rotation_coordinate : dynamicsymbol
1133
+ Generalized coordinate corresponding to the rotation angle.
1134
+ translation_coordinate : dynamicsymbol
1135
+ Generalized coordinate corresponding to the translation distance.
1136
+ rotation_speed : dynamicsymbol
1137
+ Generalized speed corresponding to the angular velocity.
1138
+ translation_speed : dynamicsymbol
1139
+ Generalized speed corresponding to the translation velocity.
1140
+ coordinates : Matrix
1141
+ Matrix of the joint's generalized coordinates.
1142
+ speeds : Matrix
1143
+ Matrix of the joint's generalized speeds.
1144
+ parent_point : Point
1145
+ Attachment point where the joint is fixed to the parent body.
1146
+ child_point : Point
1147
+ Attachment point where the joint is fixed to the child body.
1148
+ parent_interframe : ReferenceFrame
1149
+ Intermediate frame of the parent body with respect to which the joint
1150
+ transformation is formulated.
1151
+ child_interframe : ReferenceFrame
1152
+ Intermediate frame of the child body with respect to which the joint
1153
+ transformation is formulated.
1154
+ kdes : Matrix
1155
+ Kinematical differential equations of the joint.
1156
+ joint_axis : Vector
1157
+ The axis of rotation and translation.
1158
+
1159
+ Examples
1160
+ =========
1161
+
1162
+ A single cylindrical joint is created between two bodies and has the
1163
+ following basic attributes:
1164
+
1165
+ >>> from sympy.physics.mechanics import Body, CylindricalJoint
1166
+ >>> parent = Body('P')
1167
+ >>> parent
1168
+ P
1169
+ >>> child = Body('C')
1170
+ >>> child
1171
+ C
1172
+ >>> joint = CylindricalJoint('PC', parent, child)
1173
+ >>> joint
1174
+ CylindricalJoint: PC parent: P child: C
1175
+ >>> joint.name
1176
+ 'PC'
1177
+ >>> joint.parent
1178
+ P
1179
+ >>> joint.child
1180
+ C
1181
+ >>> joint.parent_point
1182
+ P_masscenter
1183
+ >>> joint.child_point
1184
+ C_masscenter
1185
+ >>> joint.parent_axis
1186
+ P_frame.x
1187
+ >>> joint.child_axis
1188
+ C_frame.x
1189
+ >>> joint.coordinates
1190
+ Matrix([
1191
+ [q0_PC(t)],
1192
+ [q1_PC(t)]])
1193
+ >>> joint.speeds
1194
+ Matrix([
1195
+ [u0_PC(t)],
1196
+ [u1_PC(t)]])
1197
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
1198
+ u0_PC(t)*P_frame.x
1199
+ >>> joint.child.frame.dcm(joint.parent.frame)
1200
+ Matrix([
1201
+ [1, 0, 0],
1202
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1203
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1204
+ >>> joint.child_point.pos_from(joint.parent_point)
1205
+ q1_PC(t)*P_frame.x
1206
+ >>> child.masscenter.vel(parent.frame)
1207
+ u1_PC(t)*P_frame.x
1208
+
1209
+ To further demonstrate the use of the cylindrical joint, the kinematics of
1210
+ two cylindrical joints perpendicular to each other can be created as follows.
1211
+
1212
+ >>> from sympy import symbols
1213
+ >>> from sympy.physics.mechanics import Body, CylindricalJoint
1214
+ >>> r, l, w = symbols('r l w')
1215
+
1216
+ First create bodies to represent the fixed floor with a fixed pole on it.
1217
+ The second body represents a freely moving tube around that pole. The third
1218
+ body represents a solid flag freely translating along and rotating around
1219
+ the Y axis of the tube.
1220
+
1221
+ >>> floor = Body('floor')
1222
+ >>> tube = Body('tube')
1223
+ >>> flag = Body('flag')
1224
+
1225
+ The first joint will connect the first tube to the floor with it translating
1226
+ along and rotating around the Z axis of both bodies.
1227
+
1228
+ >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z)
1229
+
1230
+ The second joint will connect the tube perpendicular to the flag along the Y
1231
+ axis of both the tube and the flag, with the joint located at a distance
1232
+ ``r`` from the tube's center of mass and a combination of the distances
1233
+ ``l`` and ``w`` from the flag's center of mass.
1234
+
1235
+ >>> flag_joint = CylindricalJoint('C2', tube, flag,
1236
+ ... parent_point=r * tube.y,
1237
+ ... child_point=-w * flag.y + l * flag.z,
1238
+ ... joint_axis=tube.y)
1239
+
1240
+ Once the joints are established the kinematics of the connected bodies can
1241
+ be accessed. First the direction cosine matrices of both the body and the
1242
+ flag relative to the floor are found:
1243
+
1244
+ >>> tube.dcm(floor)
1245
+ Matrix([
1246
+ [ cos(q0_C1(t)), sin(q0_C1(t)), 0],
1247
+ [-sin(q0_C1(t)), cos(q0_C1(t)), 0],
1248
+ [ 0, 0, 1]])
1249
+ >>> flag.dcm(floor)
1250
+ Matrix([
1251
+ [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))],
1252
+ [ -sin(q0_C1(t)), cos(q0_C1(t)), 0],
1253
+ [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]])
1254
+
1255
+ The position of the flag's center of mass is found with:
1256
+
1257
+ >>> flag.masscenter.pos_from(floor.masscenter)
1258
+ q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z
1259
+
1260
+ The angular velocities of the two tubes can be computed with respect to the
1261
+ floor.
1262
+
1263
+ >>> tube.ang_vel_in(floor)
1264
+ u0_C1(t)*floor_frame.z
1265
+ >>> flag.ang_vel_in(floor)
1266
+ u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y
1267
+
1268
+ Finally, the linear velocities of the two tube centers of mass can be
1269
+ computed with respect to the floor, while expressed in the tube's frame.
1270
+
1271
+ >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame)
1272
+ Matrix([
1273
+ [ 0],
1274
+ [ 0],
1275
+ [u1_C1(t)]])
1276
+ >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify()
1277
+ Matrix([
1278
+ [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)],
1279
+ [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)],
1280
+ [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]])
1281
+
1282
+ """
1283
+
1284
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1285
+ translation_coordinate=None, rotation_speed=None,
1286
+ translation_speed=None, parent_point=None, child_point=None,
1287
+ parent_interframe=None, child_interframe=None,
1288
+ joint_axis=None):
1289
+ self._joint_axis = joint_axis
1290
+ coordinates = (rotation_coordinate, translation_coordinate)
1291
+ speeds = (rotation_speed, translation_speed)
1292
+ super().__init__(name, parent, child, coordinates, speeds,
1293
+ parent_point, child_point,
1294
+ parent_interframe=parent_interframe,
1295
+ child_interframe=child_interframe)
1296
+
1297
+ def __str__(self):
1298
+ return (f'CylindricalJoint: {self.name} parent: {self.parent} '
1299
+ f'child: {self.child}')
1300
+
1301
+ @property
1302
+ def joint_axis(self):
1303
+ """Axis about and along which the rotation and translation occurs."""
1304
+ return self._joint_axis
1305
+
1306
+ @property
1307
+ def rotation_coordinate(self):
1308
+ """Generalized coordinate corresponding to the rotation angle."""
1309
+ return self.coordinates[0]
1310
+
1311
+ @property
1312
+ def translation_coordinate(self):
1313
+ """Generalized coordinate corresponding to the translation distance."""
1314
+ return self.coordinates[1]
1315
+
1316
+ @property
1317
+ def rotation_speed(self):
1318
+ """Generalized speed corresponding to the angular velocity."""
1319
+ return self.speeds[0]
1320
+
1321
+ @property
1322
+ def translation_speed(self):
1323
+ """Generalized speed corresponding to the translation velocity."""
1324
+ return self.speeds[1]
1325
+
1326
+ def _generate_coordinates(self, coordinates):
1327
+ return self._fill_coordinate_list(coordinates, 2, 'q')
1328
+
1329
+ def _generate_speeds(self, speeds):
1330
+ return self._fill_coordinate_list(speeds, 2, 'u')
1331
+
1332
+ def _orient_frames(self):
1333
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1334
+ self.child_interframe.orient_axis(
1335
+ self.parent_interframe, self.joint_axis, self.rotation_coordinate)
1336
+
1337
+ def _set_angular_velocity(self):
1338
+ self.child_interframe.set_ang_vel(
1339
+ self.parent_interframe,
1340
+ self.rotation_speed * self.joint_axis.normalize())
1341
+
1342
+ def _set_linear_velocity(self):
1343
+ self.child_point.set_pos(
1344
+ self.parent_point,
1345
+ self.translation_coordinate * self.joint_axis.normalize())
1346
+ self.parent_point.set_vel(self.parent.frame, 0)
1347
+ self.child_point.set_vel(self.child.frame, 0)
1348
+ self.child_point.set_vel(
1349
+ self.parent.frame,
1350
+ self.translation_speed * self.joint_axis.normalize())
1351
+ self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame,
1352
+ self.child_interframe)
1353
+
1354
+
1355
+ class PlanarJoint(Joint):
1356
+ """Planar Joint.
1357
+
1358
+ .. image:: PlanarJoint.svg
1359
+ :align: center
1360
+ :width: 800
1361
+
1362
+ Explanation
1363
+ ===========
1364
+
1365
+ A planar joint is defined such that the child body translates over a fixed
1366
+ plane of the parent body as well as rotate about the rotation axis, which
1367
+ is perpendicular to that plane. The origin of this plane is the
1368
+ ``parent_point`` and the plane is spanned by two nonparallel planar vectors.
1369
+ The location of the ``child_point`` is based on the planar vectors
1370
+ ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$),
1371
+ i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine
1372
+ matrix between the ``child_interframe`` and ``parent_interframe`` is formed
1373
+ using a simple rotation ($q_0$) about the rotation axis.
1374
+
1375
+ In order to simplify the definition of the ``PlanarJoint``, the
1376
+ ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of
1377
+ the ``parent_interframe`` according to the table below. This ensures that
1378
+ you can only define these vectors by creating a separate frame and supplying
1379
+ that as the interframe. If you however would only like to supply the normals
1380
+ of the plane with respect to the parent and child bodies, then you can also
1381
+ supply those to the ``parent_interframe`` and ``child_interframe``
1382
+ arguments. An example of both of these cases is in the examples section
1383
+ below and the page on the joints framework provides a more detailed
1384
+ explanation of the intermediate frames.
1385
+
1386
+ .. list-table::
1387
+
1388
+ * - ``rotation_axis``
1389
+ - ``parent_interframe.x``
1390
+ * - ``planar_vectors[0]``
1391
+ - ``parent_interframe.y``
1392
+ * - ``planar_vectors[1]``
1393
+ - ``parent_interframe.z``
1394
+
1395
+ Parameters
1396
+ ==========
1397
+
1398
+ name : string
1399
+ A unique name for the joint.
1400
+ parent : Body
1401
+ The parent body of joint.
1402
+ child : Body
1403
+ The child body of joint.
1404
+ rotation_coordinate : dynamicsymbol, optional
1405
+ Generalized coordinate corresponding to the rotation angle. The default
1406
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1407
+ planar_coordinates : iterable of dynamicsymbols, optional
1408
+ Two generalized coordinates used for the planar translation. The default
1409
+ value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``.
1410
+ rotation_speed : dynamicsymbol, optional
1411
+ Generalized speed corresponding to the angular velocity. The default
1412
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1413
+ planar_speeds : dynamicsymbols, optional
1414
+ Two generalized speeds used for the planar translation velocity. The
1415
+ default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``.
1416
+ parent_point : Point or Vector, optional
1417
+ Attachment point where the joint is fixed to the parent body. If a
1418
+ vector is provided, then the attachment point is computed by adding the
1419
+ vector to the body's mass center. The default value is the parent's mass
1420
+ center.
1421
+ child_point : Point or Vector, optional
1422
+ Attachment point where the joint is fixed to the child body. If a
1423
+ vector is provided, then the attachment point is computed by adding the
1424
+ vector to the body's mass center. The default value is the child's mass
1425
+ center.
1426
+ parent_interframe : ReferenceFrame, optional
1427
+ Intermediate frame of the parent body with respect to which the joint
1428
+ transformation is formulated. If a Vector is provided then an interframe
1429
+ is created which aligns its X axis with the given vector. The default
1430
+ value is the parent's own frame.
1431
+ child_interframe : ReferenceFrame, optional
1432
+ Intermediate frame of the child body with respect to which the joint
1433
+ transformation is formulated. If a Vector is provided then an interframe
1434
+ is created which aligns its X axis with the given vector. The default
1435
+ value is the child's own frame.
1436
+
1437
+ Attributes
1438
+ ==========
1439
+
1440
+ name : string
1441
+ The joint's name.
1442
+ parent : Body
1443
+ The joint's parent body.
1444
+ child : Body
1445
+ The joint's child body.
1446
+ rotation_coordinate : dynamicsymbol
1447
+ Generalized coordinate corresponding to the rotation angle.
1448
+ planar_coordinates : Matrix
1449
+ Two generalized coordinates used for the planar translation.
1450
+ rotation_speed : dynamicsymbol
1451
+ Generalized speed corresponding to the angular velocity.
1452
+ planar_speeds : Matrix
1453
+ Two generalized speeds used for the planar translation velocity.
1454
+ coordinates : Matrix
1455
+ Matrix of the joint's generalized coordinates.
1456
+ speeds : Matrix
1457
+ Matrix of the joint's generalized speeds.
1458
+ parent_point : Point
1459
+ Attachment point where the joint is fixed to the parent body.
1460
+ child_point : Point
1461
+ Attachment point where the joint is fixed to the child body.
1462
+ parent_interframe : ReferenceFrame
1463
+ Intermediate frame of the parent body with respect to which the joint
1464
+ transformation is formulated.
1465
+ child_interframe : ReferenceFrame
1466
+ Intermediate frame of the child body with respect to which the joint
1467
+ transformation is formulated.
1468
+ kdes : Matrix
1469
+ Kinematical differential equations of the joint.
1470
+ rotation_axis : Vector
1471
+ The axis about which the rotation occurs.
1472
+ planar_vectors : list
1473
+ The vectors that describe the planar translation directions.
1474
+
1475
+ Examples
1476
+ =========
1477
+
1478
+ A single planar joint is created between two bodies and has the following
1479
+ basic attributes:
1480
+
1481
+ >>> from sympy.physics.mechanics import Body, PlanarJoint
1482
+ >>> parent = Body('P')
1483
+ >>> parent
1484
+ P
1485
+ >>> child = Body('C')
1486
+ >>> child
1487
+ C
1488
+ >>> joint = PlanarJoint('PC', parent, child)
1489
+ >>> joint
1490
+ PlanarJoint: PC parent: P child: C
1491
+ >>> joint.name
1492
+ 'PC'
1493
+ >>> joint.parent
1494
+ P
1495
+ >>> joint.child
1496
+ C
1497
+ >>> joint.parent_point
1498
+ P_masscenter
1499
+ >>> joint.child_point
1500
+ C_masscenter
1501
+ >>> joint.rotation_axis
1502
+ P_frame.x
1503
+ >>> joint.planar_vectors
1504
+ [P_frame.y, P_frame.z]
1505
+ >>> joint.rotation_coordinate
1506
+ q0_PC(t)
1507
+ >>> joint.planar_coordinates
1508
+ Matrix([
1509
+ [q1_PC(t)],
1510
+ [q2_PC(t)]])
1511
+ >>> joint.coordinates
1512
+ Matrix([
1513
+ [q0_PC(t)],
1514
+ [q1_PC(t)],
1515
+ [q2_PC(t)]])
1516
+ >>> joint.rotation_speed
1517
+ u0_PC(t)
1518
+ >>> joint.planar_speeds
1519
+ Matrix([
1520
+ [u1_PC(t)],
1521
+ [u2_PC(t)]])
1522
+ >>> joint.speeds
1523
+ Matrix([
1524
+ [u0_PC(t)],
1525
+ [u1_PC(t)],
1526
+ [u2_PC(t)]])
1527
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
1528
+ u0_PC(t)*P_frame.x
1529
+ >>> joint.child.frame.dcm(joint.parent.frame)
1530
+ Matrix([
1531
+ [1, 0, 0],
1532
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1533
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1534
+ >>> joint.child_point.pos_from(joint.parent_point)
1535
+ q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z
1536
+ >>> child.masscenter.vel(parent.frame)
1537
+ u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z
1538
+
1539
+ To further demonstrate the use of the planar joint, the kinematics of a
1540
+ block sliding on a slope, can be created as follows.
1541
+
1542
+ >>> from sympy import symbols
1543
+ >>> from sympy.physics.mechanics import PlanarJoint, Body, ReferenceFrame
1544
+ >>> a, d, h = symbols('a d h')
1545
+
1546
+ First create bodies to represent the slope and the block.
1547
+
1548
+ >>> ground = Body('G')
1549
+ >>> block = Body('B')
1550
+
1551
+ To define the slope you can either define the plane by specifying the
1552
+ ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to
1553
+ create a rotated intermediate frame, so that the ``parent_vectors`` and
1554
+ ``rotation_axis`` will be the unit vectors of this intermediate frame.
1555
+
1556
+ >>> slope = ReferenceFrame('A')
1557
+ >>> slope.orient_axis(ground.frame, ground.y, a)
1558
+
1559
+ The planar joint can be created using these bodies and intermediate frame.
1560
+ We can specify the origin of the slope to be ``d`` above the slope's center
1561
+ of mass and the block's center of mass to be a distance ``h`` above the
1562
+ slope's surface. Note that we can specify the normal of the plane using the
1563
+ rotation axis argument.
1564
+
1565
+ >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x,
1566
+ ... child_point=-h * block.x, parent_interframe=slope)
1567
+
1568
+ Once the joint is established the kinematics of the bodies can be accessed.
1569
+ First the ``rotation_axis``, which is normal to the plane and the
1570
+ ``plane_vectors``, can be found.
1571
+
1572
+ >>> joint.rotation_axis
1573
+ A.x
1574
+ >>> joint.planar_vectors
1575
+ [A.y, A.z]
1576
+
1577
+ The direction cosine matrix of the block with respect to the ground can be
1578
+ found with:
1579
+
1580
+ >>> block.dcm(ground)
1581
+ Matrix([
1582
+ [ cos(a), 0, -sin(a)],
1583
+ [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1584
+ [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1585
+
1586
+ The angular velocity of the block can be computed with respect to the
1587
+ ground.
1588
+
1589
+ >>> block.ang_vel_in(ground)
1590
+ u0_PC(t)*A.x
1591
+
1592
+ The position of the block's center of mass can be found with:
1593
+
1594
+ >>> block.masscenter.pos_from(ground.masscenter)
1595
+ d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z
1596
+
1597
+ Finally, the linear velocity of the block's center of mass can be
1598
+ computed with respect to the ground.
1599
+
1600
+ >>> block.masscenter.vel(ground.frame)
1601
+ u1_PC(t)*A.y + u2_PC(t)*A.z
1602
+
1603
+ In some cases it could be your preference to only define the normals of the
1604
+ plane with respect to both bodies. This can most easily be done by supplying
1605
+ vectors to the ``interframe`` arguments. What will happen in this case is
1606
+ that an interframe will be created with its ``x`` axis aligned with the
1607
+ provided vector. For a further explanation of how this is done see the notes
1608
+ of the ``Joint`` class. In the code below, the above example (with the block
1609
+ on the slope) is recreated by supplying vectors to the interframe arguments.
1610
+ Note that the previously described option is however more computationally
1611
+ efficient, because the algorithm now has to compute the rotation angle
1612
+ between the provided vector and the 'x' axis.
1613
+
1614
+ >>> from sympy import symbols, cos, sin
1615
+ >>> from sympy.physics.mechanics import PlanarJoint, Body
1616
+ >>> a, d, h = symbols('a d h')
1617
+ >>> ground = Body('G')
1618
+ >>> block = Body('B')
1619
+ >>> joint = PlanarJoint(
1620
+ ... 'PC', ground, block, parent_point=d * ground.x,
1621
+ ... child_point=-h * block.x, child_interframe=block.x,
1622
+ ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z)
1623
+ >>> block.dcm(ground).simplify()
1624
+ Matrix([
1625
+ [ cos(a), 0, sin(a)],
1626
+ [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1627
+ [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1628
+
1629
+ """
1630
+
1631
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1632
+ planar_coordinates=None, rotation_speed=None,
1633
+ planar_speeds=None, parent_point=None, child_point=None,
1634
+ parent_interframe=None, child_interframe=None):
1635
+ # A ready to merge implementation of setting the planar_vectors and
1636
+ # rotation_axis was added and removed in PR #24046
1637
+ coordinates = (rotation_coordinate, planar_coordinates)
1638
+ speeds = (rotation_speed, planar_speeds)
1639
+ super().__init__(name, parent, child, coordinates, speeds,
1640
+ parent_point, child_point,
1641
+ parent_interframe=parent_interframe,
1642
+ child_interframe=child_interframe)
1643
+
1644
+ def __str__(self):
1645
+ return (f'PlanarJoint: {self.name} parent: {self.parent} '
1646
+ f'child: {self.child}')
1647
+
1648
+ @property
1649
+ def rotation_coordinate(self):
1650
+ """Generalized coordinate corresponding to the rotation angle."""
1651
+ return self.coordinates[0]
1652
+
1653
+ @property
1654
+ def planar_coordinates(self):
1655
+ """Two generalized coordinates used for the planar translation."""
1656
+ return self.coordinates[1:, 0]
1657
+
1658
+ @property
1659
+ def rotation_speed(self):
1660
+ """Generalized speed corresponding to the angular velocity."""
1661
+ return self.speeds[0]
1662
+
1663
+ @property
1664
+ def planar_speeds(self):
1665
+ """Two generalized speeds used for the planar translation velocity."""
1666
+ return self.speeds[1:, 0]
1667
+
1668
+ @property
1669
+ def rotation_axis(self):
1670
+ """The axis about which the rotation occurs."""
1671
+ return self.parent_interframe.x
1672
+
1673
+ @property
1674
+ def planar_vectors(self):
1675
+ """The vectors that describe the planar translation directions."""
1676
+ return [self.parent_interframe.y, self.parent_interframe.z]
1677
+
1678
+ def _generate_coordinates(self, coordinates):
1679
+ rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q',
1680
+ number_single=True)
1681
+ planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1)
1682
+ return rotation_speed.col_join(planar_speeds)
1683
+
1684
+ def _generate_speeds(self, speeds):
1685
+ rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u',
1686
+ number_single=True)
1687
+ planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1)
1688
+ return rotation_speed.col_join(planar_speeds)
1689
+
1690
+ def _orient_frames(self):
1691
+ self.child_interframe.orient_axis(
1692
+ self.parent_interframe, self.rotation_axis,
1693
+ self.rotation_coordinate)
1694
+
1695
+ def _set_angular_velocity(self):
1696
+ self.child_interframe.set_ang_vel(
1697
+ self.parent_interframe,
1698
+ self.rotation_speed * self.rotation_axis)
1699
+
1700
+ def _set_linear_velocity(self):
1701
+ self.child_point.set_pos(
1702
+ self.parent_point,
1703
+ self.planar_coordinates[0] * self.planar_vectors[0] +
1704
+ self.planar_coordinates[1] * self.planar_vectors[1])
1705
+ self.parent_point.set_vel(self.parent_interframe, 0)
1706
+ self.child_point.set_vel(self.child_interframe, 0)
1707
+ self.child_point.set_vel(
1708
+ self.parent.frame, self.planar_speeds[0] * self.planar_vectors[0] +
1709
+ self.planar_speeds[1] * self.planar_vectors[1])
1710
+ self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame,
1711
+ self.child.frame)
1712
+
1713
+
1714
+ class SphericalJoint(Joint):
1715
+ """Spherical (Ball-and-Socket) Joint.
1716
+
1717
+ .. image:: SphericalJoint.svg
1718
+ :align: center
1719
+ :width: 600
1720
+
1721
+ Explanation
1722
+ ===========
1723
+
1724
+ A spherical joint is defined such that the child body is free to rotate in
1725
+ any direction, without allowing a translation of the ``child_point``. As can
1726
+ also be seen in the image, the ``parent_point`` and ``child_point`` are
1727
+ fixed on top of each other, i.e. the ``joint_point``. This rotation is
1728
+ defined using the :func:`parent_interframe.orient(child_interframe,
1729
+ rot_type, amounts, rot_order)
1730
+ <sympy.physics.vector.frame.ReferenceFrame.orient>` method. The default
1731
+ rotation consists of three relative rotations, i.e. body-fixed rotations.
1732
+ Based on the direction cosine matrix following from these rotations, the
1733
+ angular velocity is computed based on the generalized coordinates and
1734
+ generalized speeds.
1735
+
1736
+ Parameters
1737
+ ==========
1738
+
1739
+ name : string
1740
+ A unique name for the joint.
1741
+ parent : Body
1742
+ The parent body of joint.
1743
+ child : Body
1744
+ The child body of joint.
1745
+ coordinates: iterable of dynamicsymbols, optional
1746
+ Generalized coordinates of the joint.
1747
+ speeds : iterable of dynamicsymbols, optional
1748
+ Generalized speeds of joint.
1749
+ parent_point : Point or Vector, optional
1750
+ Attachment point where the joint is fixed to the parent body. If a
1751
+ vector is provided, then the attachment point is computed by adding the
1752
+ vector to the body's mass center. The default value is the parent's mass
1753
+ center.
1754
+ child_point : Point or Vector, optional
1755
+ Attachment point where the joint is fixed to the child body. If a
1756
+ vector is provided, then the attachment point is computed by adding the
1757
+ vector to the body's mass center. The default value is the child's mass
1758
+ center.
1759
+ parent_interframe : ReferenceFrame, optional
1760
+ Intermediate frame of the parent body with respect to which the joint
1761
+ transformation is formulated. If a Vector is provided then an interframe
1762
+ is created which aligns its X axis with the given vector. The default
1763
+ value is the parent's own frame.
1764
+ child_interframe : ReferenceFrame, optional
1765
+ Intermediate frame of the child body with respect to which the joint
1766
+ transformation is formulated. If a Vector is provided then an interframe
1767
+ is created which aligns its X axis with the given vector. The default
1768
+ value is the child's own frame.
1769
+ rot_type : str, optional
1770
+ The method used to generate the direction cosine matrix. Supported
1771
+ methods are:
1772
+
1773
+ - ``'Body'``: three successive rotations about new intermediate axes,
1774
+ also called "Euler and Tait-Bryan angles"
1775
+ - ``'Space'``: three successive rotations about the parent frames' unit
1776
+ vectors
1777
+
1778
+ The default method is ``'Body'``.
1779
+ amounts :
1780
+ Expressions defining the rotation angles or direction cosine matrix.
1781
+ These must match the ``rot_type``. See examples below for details. The
1782
+ input types are:
1783
+
1784
+ - ``'Body'``: 3-tuple of expressions, symbols, or functions
1785
+ - ``'Space'``: 3-tuple of expressions, symbols, or functions
1786
+
1787
+ The default amounts are the given ``coordinates``.
1788
+ rot_order : str or int, optional
1789
+ If applicable, the order of the successive of rotations. The string
1790
+ ``'123'`` and integer ``123`` are equivalent, for example. Required for
1791
+ ``'Body'`` and ``'Space'``. The default value is ``123``.
1792
+
1793
+ Attributes
1794
+ ==========
1795
+
1796
+ name : string
1797
+ The joint's name.
1798
+ parent : Body
1799
+ The joint's parent body.
1800
+ child : Body
1801
+ The joint's child body.
1802
+ coordinates : Matrix
1803
+ Matrix of the joint's generalized coordinates.
1804
+ speeds : Matrix
1805
+ Matrix of the joint's generalized speeds.
1806
+ parent_point : Point
1807
+ Attachment point where the joint is fixed to the parent body.
1808
+ child_point : Point
1809
+ Attachment point where the joint is fixed to the child body.
1810
+ parent_interframe : ReferenceFrame
1811
+ Intermediate frame of the parent body with respect to which the joint
1812
+ transformation is formulated.
1813
+ child_interframe : ReferenceFrame
1814
+ Intermediate frame of the child body with respect to which the joint
1815
+ transformation is formulated.
1816
+ kdes : Matrix
1817
+ Kinematical differential equations of the joint.
1818
+
1819
+ Examples
1820
+ =========
1821
+
1822
+ A single spherical joint is created from two bodies and has the following
1823
+ basic attributes:
1824
+
1825
+ >>> from sympy.physics.mechanics import Body, SphericalJoint
1826
+ >>> parent = Body('P')
1827
+ >>> parent
1828
+ P
1829
+ >>> child = Body('C')
1830
+ >>> child
1831
+ C
1832
+ >>> joint = SphericalJoint('PC', parent, child)
1833
+ >>> joint
1834
+ SphericalJoint: PC parent: P child: C
1835
+ >>> joint.name
1836
+ 'PC'
1837
+ >>> joint.parent
1838
+ P
1839
+ >>> joint.child
1840
+ C
1841
+ >>> joint.parent_point
1842
+ P_masscenter
1843
+ >>> joint.child_point
1844
+ C_masscenter
1845
+ >>> joint.parent_interframe
1846
+ P_frame
1847
+ >>> joint.child_interframe
1848
+ C_frame
1849
+ >>> joint.coordinates
1850
+ Matrix([
1851
+ [q0_PC(t)],
1852
+ [q1_PC(t)],
1853
+ [q2_PC(t)]])
1854
+ >>> joint.speeds
1855
+ Matrix([
1856
+ [u0_PC(t)],
1857
+ [u1_PC(t)],
1858
+ [u2_PC(t)]])
1859
+ >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame)
1860
+ Matrix([
1861
+ [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))],
1862
+ [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))],
1863
+ [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]])
1864
+ >>> child.frame.x.to_matrix(parent.frame)
1865
+ Matrix([
1866
+ [ cos(q1_PC(t))*cos(q2_PC(t))],
1867
+ [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))],
1868
+ [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]])
1869
+ >>> joint.child_point.pos_from(joint.parent_point)
1870
+ 0
1871
+
1872
+ To further demonstrate the use of the spherical joint, the kinematics of a
1873
+ spherical joint with a ZXZ rotation can be created as follows.
1874
+
1875
+ >>> from sympy import symbols
1876
+ >>> from sympy.physics.mechanics import Body, SphericalJoint
1877
+ >>> l1 = symbols('l1')
1878
+
1879
+ First create bodies to represent the fixed floor and a pendulum bob.
1880
+
1881
+ >>> floor = Body('F')
1882
+ >>> bob = Body('B')
1883
+
1884
+ The joint will connect the bob to the floor, with the joint located at a
1885
+ distance of ``l1`` from the child's center of mass and the rotation set to a
1886
+ body-fixed ZXZ rotation.
1887
+
1888
+ >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y,
1889
+ ... rot_type='body', rot_order='ZXZ')
1890
+
1891
+ Now that the joint is established, the kinematics of the connected body can
1892
+ be accessed.
1893
+
1894
+ The position of the bob's masscenter is found with:
1895
+
1896
+ >>> bob.masscenter.pos_from(floor.masscenter)
1897
+ - l1*B_frame.y
1898
+
1899
+ The angular velocities of the pendulum link can be computed with respect to
1900
+ the floor.
1901
+
1902
+ >>> bob.frame.ang_vel_in(floor.frame).to_matrix(
1903
+ ... floor.frame).simplify()
1904
+ Matrix([
1905
+ [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))],
1906
+ [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))],
1907
+ [ u0_S(t) + u2_S(t)*cos(q1_S(t))]])
1908
+
1909
+ Finally, the linear velocity of the bob's center of mass can be computed.
1910
+
1911
+ >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame)
1912
+ Matrix([
1913
+ [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))],
1914
+ [ 0],
1915
+ [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]])
1916
+
1917
+ """
1918
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1919
+ parent_point=None, child_point=None, parent_interframe=None,
1920
+ child_interframe=None, rot_type='BODY', amounts=None,
1921
+ rot_order=123):
1922
+ self._rot_type = rot_type
1923
+ self._amounts = amounts
1924
+ self._rot_order = rot_order
1925
+ super().__init__(name, parent, child, coordinates, speeds,
1926
+ parent_point, child_point,
1927
+ parent_interframe=parent_interframe,
1928
+ child_interframe=child_interframe)
1929
+
1930
+ def __str__(self):
1931
+ return (f'SphericalJoint: {self.name} parent: {self.parent} '
1932
+ f'child: {self.child}')
1933
+
1934
+ def _generate_coordinates(self, coordinates):
1935
+ return self._fill_coordinate_list(coordinates, 3, 'q')
1936
+
1937
+ def _generate_speeds(self, speeds):
1938
+ return self._fill_coordinate_list(speeds, len(self.coordinates), 'u')
1939
+
1940
+ def _orient_frames(self):
1941
+ supported_rot_types = ('BODY', 'SPACE')
1942
+ if self._rot_type.upper() not in supported_rot_types:
1943
+ raise NotImplementedError(
1944
+ f'Rotation type "{self._rot_type}" is not implemented. '
1945
+ f'Implemented rotation types are: {supported_rot_types}')
1946
+ amounts = self.coordinates if self._amounts is None else self._amounts
1947
+ self.child_interframe.orient(self.parent_interframe, self._rot_type,
1948
+ amounts, self._rot_order)
1949
+
1950
+ def _set_angular_velocity(self):
1951
+ t = dynamicsymbols._t
1952
+ vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace(
1953
+ {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)}
1954
+ )
1955
+ self.child_interframe.set_ang_vel(self.parent_interframe, vel)
1956
+
1957
+ def _set_linear_velocity(self):
1958
+ self.child_point.set_pos(self.parent_point, 0)
1959
+ self.parent_point.set_vel(self.parent.frame, 0)
1960
+ self.child_point.set_vel(self.child.frame, 0)
1961
+ self.child.masscenter.v2pt_theory(self.parent_point, self.parent.frame,
1962
+ self.child.frame)
1963
+
1964
+
1965
+ class WeldJoint(Joint):
1966
+ """Weld Joint.
1967
+
1968
+ .. image:: WeldJoint.svg
1969
+ :align: center
1970
+ :width: 500
1971
+
1972
+ Explanation
1973
+ ===========
1974
+
1975
+ A weld joint is defined such that there is no relative motion between the
1976
+ child and parent bodies. The direction cosine matrix between the attachment
1977
+ frame (``parent_interframe`` and ``child_interframe``) is the identity
1978
+ matrix and the attachment points (``parent_point`` and ``child_point``) are
1979
+ coincident. The page on the joints framework gives a more detailed
1980
+ explanation of the intermediate frames.
1981
+
1982
+ Parameters
1983
+ ==========
1984
+
1985
+ name : string
1986
+ A unique name for the joint.
1987
+ parent : Body
1988
+ The parent body of joint.
1989
+ child : Body
1990
+ The child body of joint.
1991
+ parent_point : Point or Vector, optional
1992
+ Attachment point where the joint is fixed to the parent body. If a
1993
+ vector is provided, then the attachment point is computed by adding the
1994
+ vector to the body's mass center. The default value is the parent's mass
1995
+ center.
1996
+ child_point : Point or Vector, optional
1997
+ Attachment point where the joint is fixed to the child body. If a
1998
+ vector is provided, then the attachment point is computed by adding the
1999
+ vector to the body's mass center. The default value is the child's mass
2000
+ center.
2001
+ parent_interframe : ReferenceFrame, optional
2002
+ Intermediate frame of the parent body with respect to which the joint
2003
+ transformation is formulated. If a Vector is provided then an interframe
2004
+ is created which aligns its X axis with the given vector. The default
2005
+ value is the parent's own frame.
2006
+ child_interframe : ReferenceFrame, optional
2007
+ Intermediate frame of the child body with respect to which the joint
2008
+ transformation is formulated. If a Vector is provided then an interframe
2009
+ is created which aligns its X axis with the given vector. The default
2010
+ value is the child's own frame.
2011
+
2012
+ Attributes
2013
+ ==========
2014
+
2015
+ name : string
2016
+ The joint's name.
2017
+ parent : Body
2018
+ The joint's parent body.
2019
+ child : Body
2020
+ The joint's child body.
2021
+ coordinates : Matrix
2022
+ Matrix of the joint's generalized coordinates. The default value is
2023
+ ``dynamicsymbols(f'q_{joint.name}')``.
2024
+ speeds : Matrix
2025
+ Matrix of the joint's generalized speeds. The default value is
2026
+ ``dynamicsymbols(f'u_{joint.name}')``.
2027
+ parent_point : Point
2028
+ Attachment point where the joint is fixed to the parent body.
2029
+ child_point : Point
2030
+ Attachment point where the joint is fixed to the child body.
2031
+ parent_interframe : ReferenceFrame
2032
+ Intermediate frame of the parent body with respect to which the joint
2033
+ transformation is formulated.
2034
+ child_interframe : ReferenceFrame
2035
+ Intermediate frame of the child body with respect to which the joint
2036
+ transformation is formulated.
2037
+ kdes : Matrix
2038
+ Kinematical differential equations of the joint.
2039
+
2040
+ Examples
2041
+ =========
2042
+
2043
+ A single weld joint is created from two bodies and has the following basic
2044
+ attributes:
2045
+
2046
+ >>> from sympy.physics.mechanics import Body, WeldJoint
2047
+ >>> parent = Body('P')
2048
+ >>> parent
2049
+ P
2050
+ >>> child = Body('C')
2051
+ >>> child
2052
+ C
2053
+ >>> joint = WeldJoint('PC', parent, child)
2054
+ >>> joint
2055
+ WeldJoint: PC parent: P child: C
2056
+ >>> joint.name
2057
+ 'PC'
2058
+ >>> joint.parent
2059
+ P
2060
+ >>> joint.child
2061
+ C
2062
+ >>> joint.parent_point
2063
+ P_masscenter
2064
+ >>> joint.child_point
2065
+ C_masscenter
2066
+ >>> joint.coordinates
2067
+ Matrix(0, 0, [])
2068
+ >>> joint.speeds
2069
+ Matrix(0, 0, [])
2070
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
2071
+ 0
2072
+ >>> joint.child.frame.dcm(joint.parent.frame)
2073
+ Matrix([
2074
+ [1, 0, 0],
2075
+ [0, 1, 0],
2076
+ [0, 0, 1]])
2077
+ >>> joint.child_point.pos_from(joint.parent_point)
2078
+ 0
2079
+
2080
+ To further demonstrate the use of the weld joint, two relatively-fixed
2081
+ bodies rotated by a quarter turn about the Y axis can be created as follows:
2082
+
2083
+ >>> from sympy import symbols, pi
2084
+ >>> from sympy.physics.mechanics import ReferenceFrame, Body, WeldJoint
2085
+ >>> l1, l2 = symbols('l1 l2')
2086
+
2087
+ First create the bodies to represent the parent and rotated child body.
2088
+
2089
+ >>> parent = Body('P')
2090
+ >>> child = Body('C')
2091
+
2092
+ Next the intermediate frame specifying the fixed rotation with respect to
2093
+ the parent can be created.
2094
+
2095
+ >>> rotated_frame = ReferenceFrame('Pr')
2096
+ >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2)
2097
+
2098
+ The weld between the parent body and child body is located at a distance
2099
+ ``l1`` from the parent's center of mass in the X direction and ``l2`` from
2100
+ the child's center of mass in the child's negative X direction.
2101
+
2102
+ >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x,
2103
+ ... child_point=-l2 * child.x,
2104
+ ... parent_interframe=rotated_frame)
2105
+
2106
+ Now that the joint has been established, the kinematics of the bodies can be
2107
+ accessed. The direction cosine matrix of the child body with respect to the
2108
+ parent can be found:
2109
+
2110
+ >>> child.dcm(parent)
2111
+ Matrix([
2112
+ [0, 0, -1],
2113
+ [0, 1, 0],
2114
+ [1, 0, 0]])
2115
+
2116
+ As can also been seen from the direction cosine matrix, the parent X axis is
2117
+ aligned with the child's Z axis:
2118
+ >>> parent.x == child.z
2119
+ True
2120
+
2121
+ The position of the child's center of mass with respect to the parent's
2122
+ center of mass can be found with:
2123
+
2124
+ >>> child.masscenter.pos_from(parent.masscenter)
2125
+ l1*P_frame.x + l2*C_frame.x
2126
+
2127
+ The angular velocity of the child with respect to the parent is 0 as one
2128
+ would expect.
2129
+
2130
+ >>> child.ang_vel_in(parent)
2131
+ 0
2132
+
2133
+ """
2134
+
2135
+ def __init__(self, name, parent, child, parent_point=None, child_point=None,
2136
+ parent_interframe=None, child_interframe=None):
2137
+ super().__init__(name, parent, child, [], [], parent_point,
2138
+ child_point, parent_interframe=parent_interframe,
2139
+ child_interframe=child_interframe)
2140
+ self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770
2141
+
2142
+ def __str__(self):
2143
+ return (f'WeldJoint: {self.name} parent: {self.parent} '
2144
+ f'child: {self.child}')
2145
+
2146
+ def _generate_coordinates(self, coordinate):
2147
+ return Matrix()
2148
+
2149
+ def _generate_speeds(self, speed):
2150
+ return Matrix()
2151
+
2152
+ def _orient_frames(self):
2153
+ self.child_interframe.orient_axis(self.parent_interframe,
2154
+ self.parent_interframe.x, 0)
2155
+
2156
+ def _set_angular_velocity(self):
2157
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
2158
+
2159
+ def _set_linear_velocity(self):
2160
+ self.child_point.set_pos(self.parent_point, 0)
2161
+ self.parent_point.set_vel(self.parent.frame, 0)
2162
+ self.child_point.set_vel(self.child.frame, 0)
2163
+ self.child.masscenter.set_vel(self.parent.frame, 0)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
2
+ RigidBody, Particle)
3
+ from sympy.physics.mechanics.method import _Methods
4
+ from sympy.core.backend import Matrix
5
+
6
+ __all__ = ['JointsMethod']
7
+
8
+
9
+ class JointsMethod(_Methods):
10
+ """Method for formulating the equations of motion using a set of interconnected bodies with joints.
11
+
12
+ Parameters
13
+ ==========
14
+
15
+ newtonion : Body or ReferenceFrame
16
+ The newtonion(inertial) frame.
17
+ *joints : Joint
18
+ The joints in the system
19
+
20
+ Attributes
21
+ ==========
22
+
23
+ q, u : iterable
24
+ Iterable of the generalized coordinates and speeds
25
+ bodies : iterable
26
+ Iterable of Body objects in the system.
27
+ loads : iterable
28
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
29
+ describing the forces on the system.
30
+ mass_matrix : Matrix, shape(n, n)
31
+ The system's mass matrix
32
+ forcing : Matrix, shape(n, 1)
33
+ The system's forcing vector
34
+ mass_matrix_full : Matrix, shape(2*n, 2*n)
35
+ The "mass matrix" for the u's and q's
36
+ forcing_full : Matrix, shape(2*n, 1)
37
+ The "forcing vector" for the u's and q's
38
+ method : KanesMethod or Lagrange's method
39
+ Method's object.
40
+ kdes : iterable
41
+ Iterable of kde in they system.
42
+
43
+ Examples
44
+ ========
45
+
46
+ This is a simple example for a one degree of freedom translational
47
+ spring-mass-damper.
48
+
49
+ >>> from sympy import symbols
50
+ >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
51
+ >>> from sympy.physics.vector import dynamicsymbols
52
+ >>> c, k = symbols('c k')
53
+ >>> x, v = dynamicsymbols('x v')
54
+ >>> wall = Body('W')
55
+ >>> body = Body('B')
56
+ >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
57
+ >>> wall.apply_force(c*v*wall.x, reaction_body=body)
58
+ >>> wall.apply_force(k*x*wall.x, reaction_body=body)
59
+ >>> method = JointsMethod(wall, J)
60
+ >>> method.form_eoms()
61
+ Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
62
+ >>> M = method.mass_matrix_full
63
+ >>> F = method.forcing_full
64
+ >>> rhs = M.LUsolve(F)
65
+ >>> rhs
66
+ Matrix([
67
+ [ v(t)],
68
+ [(-c*v(t) - k*x(t))/B_mass]])
69
+
70
+ Notes
71
+ =====
72
+
73
+ ``JointsMethod`` currently only works with systems that do not have any
74
+ configuration or motion constraints.
75
+
76
+ """
77
+
78
+ def __init__(self, newtonion, *joints):
79
+ if isinstance(newtonion, Body):
80
+ self.frame = newtonion.frame
81
+ else:
82
+ self.frame = newtonion
83
+
84
+ self._joints = joints
85
+ self._bodies = self._generate_bodylist()
86
+ self._loads = self._generate_loadlist()
87
+ self._q = self._generate_q()
88
+ self._u = self._generate_u()
89
+ self._kdes = self._generate_kdes()
90
+
91
+ self._method = None
92
+
93
+ @property
94
+ def bodies(self):
95
+ """List of bodies in they system."""
96
+ return self._bodies
97
+
98
+ @property
99
+ def loads(self):
100
+ """List of loads on the system."""
101
+ return self._loads
102
+
103
+ @property
104
+ def q(self):
105
+ """List of the generalized coordinates."""
106
+ return self._q
107
+
108
+ @property
109
+ def u(self):
110
+ """List of the generalized speeds."""
111
+ return self._u
112
+
113
+ @property
114
+ def kdes(self):
115
+ """List of the generalized coordinates."""
116
+ return self._kdes
117
+
118
+ @property
119
+ def forcing_full(self):
120
+ """The "forcing vector" for the u's and q's."""
121
+ return self.method.forcing_full
122
+
123
+ @property
124
+ def mass_matrix_full(self):
125
+ """The "mass matrix" for the u's and q's."""
126
+ return self.method.mass_matrix_full
127
+
128
+ @property
129
+ def mass_matrix(self):
130
+ """The system's mass matrix."""
131
+ return self.method.mass_matrix
132
+
133
+ @property
134
+ def forcing(self):
135
+ """The system's forcing vector."""
136
+ return self.method.forcing
137
+
138
+ @property
139
+ def method(self):
140
+ """Object of method used to form equations of systems."""
141
+ return self._method
142
+
143
+ def _generate_bodylist(self):
144
+ bodies = []
145
+ for joint in self._joints:
146
+ if joint.child not in bodies:
147
+ bodies.append(joint.child)
148
+ if joint.parent not in bodies:
149
+ bodies.append(joint.parent)
150
+ return bodies
151
+
152
+ def _generate_loadlist(self):
153
+ load_list = []
154
+ for body in self.bodies:
155
+ load_list.extend(body.loads)
156
+ return load_list
157
+
158
+ def _generate_q(self):
159
+ q_ind = []
160
+ for joint in self._joints:
161
+ for coordinate in joint.coordinates:
162
+ if coordinate in q_ind:
163
+ raise ValueError('Coordinates of joints should be unique.')
164
+ q_ind.append(coordinate)
165
+ return Matrix(q_ind)
166
+
167
+ def _generate_u(self):
168
+ u_ind = []
169
+ for joint in self._joints:
170
+ for speed in joint.speeds:
171
+ if speed in u_ind:
172
+ raise ValueError('Speeds of joints should be unique.')
173
+ u_ind.append(speed)
174
+ return Matrix(u_ind)
175
+
176
+ def _generate_kdes(self):
177
+ kd_ind = Matrix(1, 0, []).T
178
+ for joint in self._joints:
179
+ kd_ind = kd_ind.col_join(joint.kdes)
180
+ return kd_ind
181
+
182
+ def _convert_bodies(self):
183
+ # Convert `Body` to `Particle` and `RigidBody`
184
+ bodylist = []
185
+ for body in self.bodies:
186
+ if body.is_rigidbody:
187
+ rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
188
+ (body.central_inertia, body.masscenter))
189
+ rb.potential_energy = body.potential_energy
190
+ bodylist.append(rb)
191
+ else:
192
+ part = Particle(body.name, body.masscenter, body.mass)
193
+ part.potential_energy = body.potential_energy
194
+ bodylist.append(part)
195
+ return bodylist
196
+
197
+ def form_eoms(self, method=KanesMethod):
198
+ """Method to form system's equation of motions.
199
+
200
+ Parameters
201
+ ==========
202
+
203
+ method : Class
204
+ Class name of method.
205
+
206
+ Returns
207
+ ========
208
+
209
+ Matrix
210
+ Vector of equations of motions.
211
+
212
+ Examples
213
+ ========
214
+
215
+ This is a simple example for a one degree of freedom translational
216
+ spring-mass-damper.
217
+
218
+ >>> from sympy import S, symbols
219
+ >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
220
+ >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
221
+ >>> q = dynamicsymbols('q')
222
+ >>> qd = dynamicsymbols('q', 1)
223
+ >>> m, k, b = symbols('m k b')
224
+ >>> wall = Body('W')
225
+ >>> part = Body('P', mass=m)
226
+ >>> part.potential_energy = k * q**2 / S(2)
227
+ >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
228
+ >>> wall.apply_force(b * qd * wall.x, reaction_body=part)
229
+ >>> method = JointsMethod(wall, J)
230
+ >>> method.form_eoms(LagrangesMethod)
231
+ Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
232
+
233
+ We can also solve for the states using the 'rhs' method.
234
+
235
+ >>> method.rhs()
236
+ Matrix([
237
+ [ Derivative(q(t), t)],
238
+ [(-b*Derivative(q(t), t) - k*q(t))/m]])
239
+
240
+ """
241
+
242
+ bodylist = self._convert_bodies()
243
+ if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
244
+ L = Lagrangian(self.frame, *bodylist)
245
+ self._method = method(L, self.q, self.loads, bodylist, self.frame)
246
+ else: #KanesMethod or similar
247
+ self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
248
+ forcelist=self.loads, bodies=bodylist)
249
+ soln = self.method._form_eoms()
250
+ return soln
251
+
252
+ def rhs(self, inv_method=None):
253
+ """Returns equations that can be solved numerically.
254
+
255
+ Parameters
256
+ ==========
257
+
258
+ inv_method : str
259
+ The specific sympy inverse matrix calculation method to use. For a
260
+ list of valid methods, see
261
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
262
+
263
+ Returns
264
+ ========
265
+
266
+ Matrix
267
+ Numerically solvable equations.
268
+
269
+ See Also
270
+ ========
271
+
272
+ sympy.physics.mechanics.kane.KanesMethod.rhs:
273
+ KanesMethod's rhs function.
274
+ sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
275
+ LagrangesMethod's rhs function.
276
+
277
+ """
278
+
279
+ return self.method.rhs(inv_method=inv_method)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import zeros, Matrix, diff, eye
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 (
9
+ msubs, find_dynamicsymbols, _f_list_parser, _validate_coordinates)
10
+ from sympy.physics.mechanics.linearize import Linearizer
11
+ from sympy.utilities.iterables import iterable
12
+
13
+ __all__ = ['KanesMethod']
14
+
15
+
16
+ class KanesMethod(_Methods):
17
+ r"""Kane's method object.
18
+
19
+ Explanation
20
+ ===========
21
+
22
+ This object is used to do the "book-keeping" as you go through and form
23
+ equations of motion in the way Kane presents in:
24
+ Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
25
+
26
+ The attributes are for equations in the form [M] udot = forcing.
27
+
28
+ Attributes
29
+ ==========
30
+
31
+ q, u : Matrix
32
+ Matrices of the generalized coordinates and speeds
33
+ bodies : iterable
34
+ Iterable of Point and RigidBody objects in the system.
35
+ loads : iterable
36
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
37
+ describing the forces on the system.
38
+ auxiliary_eqs : Matrix
39
+ If applicable, the set of auxiliary Kane's
40
+ equations used to solve for non-contributing
41
+ forces.
42
+ mass_matrix : Matrix
43
+ The system's dynamics mass matrix: [k_d; k_dnh]
44
+ forcing : Matrix
45
+ The system's dynamics forcing vector: -[f_d; f_dnh]
46
+ mass_matrix_kin : Matrix
47
+ The "mass matrix" for kinematic differential equations: k_kqdot
48
+ forcing_kin : Matrix
49
+ The forcing vector for kinematic differential equations: -(k_ku*u + f_k)
50
+ mass_matrix_full : Matrix
51
+ The "mass matrix" for the u's and q's with dynamics and kinematics
52
+ forcing_full : Matrix
53
+ The "forcing vector" for the u's and q's with dynamics and kinematics
54
+ explicit_kinematics : bool
55
+ Boolean whether the mass matrices and forcing vectors should use the
56
+ explicit form (default) or implicit form for kinematics.
57
+ See the notes for more details.
58
+
59
+ Notes
60
+ =====
61
+
62
+ The mass matrices and forcing vectors related to kinematic equations
63
+ are given in the explicit form by default. In other words, the kinematic
64
+ mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$.
65
+ In order to get the implicit form of those matrices/vectors, you can set the
66
+ ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$ is not
67
+ necessarily an identity matrix. This can provide more compact equations for
68
+ non-simple kinematics (see #22626).
69
+
70
+ Examples
71
+ ========
72
+
73
+ This is a simple example for a one degree of freedom translational
74
+ spring-mass-damper.
75
+
76
+ In this example, we first need to do the kinematics.
77
+ This involves creating generalized speeds and coordinates and their
78
+ derivatives.
79
+ Then we create a point and set its velocity in a frame.
80
+
81
+ >>> from sympy import symbols
82
+ >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame
83
+ >>> from sympy.physics.mechanics import Point, Particle, KanesMethod
84
+ >>> q, u = dynamicsymbols('q u')
85
+ >>> qd, ud = dynamicsymbols('q u', 1)
86
+ >>> m, c, k = symbols('m c k')
87
+ >>> N = ReferenceFrame('N')
88
+ >>> P = Point('P')
89
+ >>> P.set_vel(N, u * N.x)
90
+
91
+ Next we need to arrange/store information in the way that KanesMethod
92
+ requires. The kinematic differential equations need to be stored in a
93
+ dict. A list of forces/torques must be constructed, where each entry in
94
+ the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the
95
+ Vectors represent the Force or Torque.
96
+ Next a particle needs to be created, and it needs to have a point and mass
97
+ assigned to it.
98
+ Finally, a list of all bodies and particles needs to be created.
99
+
100
+ >>> kd = [qd - u]
101
+ >>> FL = [(P, (-k * q - c * u) * N.x)]
102
+ >>> pa = Particle('pa', P, m)
103
+ >>> BL = [pa]
104
+
105
+ Finally we can generate the equations of motion.
106
+ First we create the KanesMethod object and supply an inertial frame,
107
+ coordinates, generalized speeds, and the kinematic differential equations.
108
+ Additional quantities such as configuration and motion constraints,
109
+ dependent coordinates and speeds, and auxiliary speeds are also supplied
110
+ here (see the online documentation).
111
+ Next we form FR* and FR to complete: Fr + Fr* = 0.
112
+ We have the equations of motion at this point.
113
+ It makes sense to rearrange them though, so we calculate the mass matrix and
114
+ the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is
115
+ the mass matrix, udot is a vector of the time derivatives of the
116
+ generalized speeds, and forcing is a vector representing "forcing" terms.
117
+
118
+ >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd)
119
+ >>> (fr, frstar) = KM.kanes_equations(BL, FL)
120
+ >>> MM = KM.mass_matrix
121
+ >>> forcing = KM.forcing
122
+ >>> rhs = MM.inv() * forcing
123
+ >>> rhs
124
+ Matrix([[(-c*u(t) - k*q(t))/m]])
125
+ >>> KM.linearize(A_and_B=True)[0]
126
+ Matrix([
127
+ [ 0, 1],
128
+ [-k/m, -c/m]])
129
+
130
+ Please look at the documentation pages for more information on how to
131
+ perform linearization and how to deal with dependent coordinates & speeds,
132
+ and how do deal with bringing non-contributing forces into evidence.
133
+
134
+ """
135
+
136
+ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
137
+ configuration_constraints=None, u_dependent=None,
138
+ velocity_constraints=None, acceleration_constraints=None,
139
+ u_auxiliary=None, bodies=None, forcelist=None, explicit_kinematics=True):
140
+
141
+ """Please read the online documentation. """
142
+ if not q_ind:
143
+ q_ind = [dynamicsymbols('dummy_q')]
144
+ kd_eqs = [dynamicsymbols('dummy_kd')]
145
+
146
+ if not isinstance(frame, ReferenceFrame):
147
+ raise TypeError('An inertial ReferenceFrame must be supplied')
148
+ self._inertial = frame
149
+
150
+ self._fr = None
151
+ self._frstar = None
152
+
153
+ self._forcelist = forcelist
154
+ self._bodylist = bodies
155
+
156
+ self.explicit_kinematics = explicit_kinematics
157
+
158
+ self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
159
+ u_auxiliary)
160
+ _validate_coordinates(self.q, self.u)
161
+ self._initialize_kindiffeq_matrices(kd_eqs)
162
+ self._initialize_constraint_matrices(configuration_constraints,
163
+ velocity_constraints, acceleration_constraints)
164
+
165
+ def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
166
+ """Initialize the coordinate and speed vectors."""
167
+
168
+ none_handler = lambda x: Matrix(x) if x else Matrix()
169
+
170
+ # Initialize generalized coordinates
171
+ q_dep = none_handler(q_dep)
172
+ if not iterable(q_ind):
173
+ raise TypeError('Generalized coordinates must be an iterable.')
174
+ if not iterable(q_dep):
175
+ raise TypeError('Dependent coordinates must be an iterable.')
176
+ q_ind = Matrix(q_ind)
177
+ self._qdep = q_dep
178
+ self._q = Matrix([q_ind, q_dep])
179
+ self._qdot = self.q.diff(dynamicsymbols._t)
180
+
181
+ # Initialize generalized speeds
182
+ u_dep = none_handler(u_dep)
183
+ if not iterable(u_ind):
184
+ raise TypeError('Generalized speeds must be an iterable.')
185
+ if not iterable(u_dep):
186
+ raise TypeError('Dependent speeds must be an iterable.')
187
+ u_ind = Matrix(u_ind)
188
+ self._udep = u_dep
189
+ self._u = Matrix([u_ind, u_dep])
190
+ self._udot = self.u.diff(dynamicsymbols._t)
191
+ self._uaux = none_handler(u_aux)
192
+
193
+ def _initialize_constraint_matrices(self, config, vel, acc):
194
+ """Initializes constraint matrices."""
195
+
196
+ # Define vector dimensions
197
+ o = len(self.u)
198
+ m = len(self._udep)
199
+ p = o - m
200
+ none_handler = lambda x: Matrix(x) if x else Matrix()
201
+
202
+ # Initialize configuration constraints
203
+ config = none_handler(config)
204
+ if len(self._qdep) != len(config):
205
+ raise ValueError('There must be an equal number of dependent '
206
+ 'coordinates and configuration constraints.')
207
+ self._f_h = none_handler(config)
208
+
209
+ # Initialize velocity and acceleration constraints
210
+ vel = none_handler(vel)
211
+ acc = none_handler(acc)
212
+ if len(vel) != m:
213
+ raise ValueError('There must be an equal number of dependent '
214
+ 'speeds and velocity constraints.')
215
+ if acc and (len(acc) != m):
216
+ raise ValueError('There must be an equal number of dependent '
217
+ 'speeds and acceleration constraints.')
218
+ if vel:
219
+ u_zero = {i: 0 for i in self.u}
220
+ udot_zero = {i: 0 for i in self._udot}
221
+
222
+ # When calling kanes_equations, another class instance will be
223
+ # created if auxiliary u's are present. In this case, the
224
+ # computation of kinetic differential equation matrices will be
225
+ # skipped as this was computed during the original KanesMethod
226
+ # object, and the qd_u_map will not be available.
227
+ if self._qdot_u_map is not None:
228
+ vel = msubs(vel, self._qdot_u_map)
229
+
230
+ self._f_nh = msubs(vel, u_zero)
231
+ self._k_nh = (vel - self._f_nh).jacobian(self.u)
232
+ # If no acceleration constraints given, calculate them.
233
+ if not acc:
234
+ _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u +
235
+ self._f_nh.diff(dynamicsymbols._t))
236
+ if self._qdot_u_map is not None:
237
+ _f_dnh = msubs(_f_dnh, self._qdot_u_map)
238
+ self._f_dnh = _f_dnh
239
+ self._k_dnh = self._k_nh
240
+ else:
241
+ if self._qdot_u_map is not None:
242
+ acc = msubs(acc, self._qdot_u_map)
243
+ self._f_dnh = msubs(acc, udot_zero)
244
+ self._k_dnh = (acc - self._f_dnh).jacobian(self._udot)
245
+
246
+ # Form of non-holonomic constraints is B*u + C = 0.
247
+ # We partition B into independent and dependent columns:
248
+ # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds
249
+ # to independent speeds as: udep = Ars*uind, neglecting the C term.
250
+ B_ind = self._k_nh[:, :p]
251
+ B_dep = self._k_nh[:, p:o]
252
+ self._Ars = -B_dep.LUsolve(B_ind)
253
+ else:
254
+ self._f_nh = Matrix()
255
+ self._k_nh = Matrix()
256
+ self._f_dnh = Matrix()
257
+ self._k_dnh = Matrix()
258
+ self._Ars = Matrix()
259
+
260
+ def _initialize_kindiffeq_matrices(self, kdeqs):
261
+ """Initialize the kinematic differential equation matrices.
262
+
263
+ Parameters
264
+ ==========
265
+ kdeqs : sequence of sympy expressions
266
+ Kinematic differential equations in the form of f(u,q',q,t) where
267
+ f() = 0. The equations have to be linear in the generalized
268
+ coordinates and generalized speeds.
269
+
270
+ """
271
+
272
+ if kdeqs:
273
+ if len(self.q) != len(kdeqs):
274
+ raise ValueError('There must be an equal number of kinematic '
275
+ 'differential equations and coordinates.')
276
+
277
+ u = self.u
278
+ qdot = self._qdot
279
+
280
+ kdeqs = Matrix(kdeqs)
281
+
282
+ u_zero = {ui: 0 for ui in u}
283
+ uaux_zero = {uai: 0 for uai in self._uaux}
284
+ qdot_zero = {qdi: 0 for qdi in qdot}
285
+
286
+ # Extract the linear coefficient matrices as per the following
287
+ # equation:
288
+ #
289
+ # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0
290
+ #
291
+ k_ku = kdeqs.jacobian(u)
292
+ k_kqdot = kdeqs.jacobian(qdot)
293
+ f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero)
294
+
295
+ # The kinematic differential equations should be linear in both q'
296
+ # and u, so check for u and q' in the components.
297
+ dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k))
298
+ nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms]
299
+ if nonlin_vars:
300
+ msg = ('The provided kinematic differential equations are '
301
+ 'nonlinear in {}. They must be linear in the '
302
+ 'generalized speeds and derivatives of the generalized '
303
+ 'coordinates.')
304
+ raise ValueError(msg.format(nonlin_vars))
305
+
306
+ self._f_k_implicit = f_k.xreplace(uaux_zero)
307
+ self._k_ku_implicit = k_ku.xreplace(uaux_zero)
308
+ self._k_kqdot_implicit = k_kqdot
309
+
310
+ # Solve for q'(t) such that the coefficient matrices are now in
311
+ # this form:
312
+ #
313
+ # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0
314
+ #
315
+ # NOTE : Solving the kinematic differential equations here is not
316
+ # necessary and prevents the equations from being provided in fully
317
+ # implicit form.
318
+ f_k_explicit = k_kqdot.LUsolve(f_k)
319
+ k_ku_explicit = k_kqdot.LUsolve(k_ku)
320
+ self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit)))
321
+
322
+ self._f_k = f_k_explicit.xreplace(uaux_zero)
323
+ self._k_ku = k_ku_explicit.xreplace(uaux_zero)
324
+ self._k_kqdot = eye(len(qdot))
325
+
326
+ else:
327
+ self._qdot_u_map = None
328
+ self._f_k_implicit = self._f_k = Matrix()
329
+ self._k_ku_implicit = self._k_ku = Matrix()
330
+ self._k_kqdot_implicit = self._k_kqdot = Matrix()
331
+
332
+ def _form_fr(self, fl):
333
+ """Form the generalized active force."""
334
+ if fl is not None and (len(fl) == 0 or not iterable(fl)):
335
+ raise ValueError('Force pairs must be supplied in an '
336
+ 'non-empty iterable or None.')
337
+
338
+ N = self._inertial
339
+ # pull out relevant velocities for constructing partial velocities
340
+ vel_list, f_list = _f_list_parser(fl, N)
341
+ vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
342
+ f_list = [msubs(i, self._qdot_u_map) for i in f_list]
343
+
344
+ # Fill Fr with dot product of partial velocities and forces
345
+ o = len(self.u)
346
+ b = len(f_list)
347
+ FR = zeros(o, 1)
348
+ partials = partial_velocity(vel_list, self.u, N)
349
+ for i in range(o):
350
+ FR[i] = sum(partials[j][i] & f_list[j] for j in range(b))
351
+
352
+ # In case there are dependent speeds
353
+ if self._udep:
354
+ p = o - len(self._udep)
355
+ FRtilde = FR[:p, 0]
356
+ FRold = FR[p:o, 0]
357
+ FRtilde += self._Ars.T * FRold
358
+ FR = FRtilde
359
+
360
+ self._forcelist = fl
361
+ self._fr = FR
362
+ return FR
363
+
364
+ def _form_frstar(self, bl):
365
+ """Form the generalized inertia force."""
366
+
367
+ if not iterable(bl):
368
+ raise TypeError('Bodies must be supplied in an iterable.')
369
+
370
+ t = dynamicsymbols._t
371
+ N = self._inertial
372
+ # Dicts setting things to zero
373
+ udot_zero = {i: 0 for i in self._udot}
374
+ uaux_zero = {i: 0 for i in self._uaux}
375
+ uauxdot = [diff(i, t) for i in self._uaux]
376
+ uauxdot_zero = {i: 0 for i in uauxdot}
377
+ # Dictionary of q' and q'' to u and u'
378
+ q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in
379
+ self._qdot_u_map.items()}
380
+ q_ddot_u_map.update(self._qdot_u_map)
381
+
382
+ # Fill up the list of partials: format is a list with num elements
383
+ # equal to number of entries in body list. Each of these elements is a
384
+ # list - either of length 1 for the translational components of
385
+ # particles or of length 2 for the translational and rotational
386
+ # components of rigid bodies. The inner most list is the list of
387
+ # partial velocities.
388
+ def get_partial_velocity(body):
389
+ if isinstance(body, RigidBody):
390
+ vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)]
391
+ elif isinstance(body, Particle):
392
+ vlist = [body.point.vel(N),]
393
+ else:
394
+ raise TypeError('The body list may only contain either '
395
+ 'RigidBody or Particle as list elements.')
396
+ v = [msubs(vel, self._qdot_u_map) for vel in vlist]
397
+ return partial_velocity(v, self.u, N)
398
+ partials = [get_partial_velocity(body) for body in bl]
399
+
400
+ # Compute fr_star in two components:
401
+ # fr_star = -(MM*u' + nonMM)
402
+ o = len(self.u)
403
+ MM = zeros(o, o)
404
+ nonMM = zeros(o, 1)
405
+ zero_uaux = lambda expr: msubs(expr, uaux_zero)
406
+ zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero)
407
+ for i, body in enumerate(bl):
408
+ if isinstance(body, RigidBody):
409
+ M = zero_uaux(body.mass)
410
+ I = zero_uaux(body.central_inertia)
411
+ vel = zero_uaux(body.masscenter.vel(N))
412
+ omega = zero_uaux(body.frame.ang_vel_in(N))
413
+ acc = zero_udot_uaux(body.masscenter.acc(N))
414
+ inertial_force = (M.diff(t) * vel + M * acc)
415
+ inertial_torque = zero_uaux((I.dt(body.frame) & omega) +
416
+ msubs(I & body.frame.ang_acc_in(N), udot_zero) +
417
+ (omega ^ (I & omega)))
418
+ for j in range(o):
419
+ tmp_vel = zero_uaux(partials[i][0][j])
420
+ tmp_ang = zero_uaux(I & partials[i][1][j])
421
+ for k in range(o):
422
+ # translational
423
+ MM[j, k] += M * (tmp_vel & partials[i][0][k])
424
+ # rotational
425
+ MM[j, k] += (tmp_ang & partials[i][1][k])
426
+ nonMM[j] += inertial_force & partials[i][0][j]
427
+ nonMM[j] += inertial_torque & partials[i][1][j]
428
+ else:
429
+ M = zero_uaux(body.mass)
430
+ vel = zero_uaux(body.point.vel(N))
431
+ acc = zero_udot_uaux(body.point.acc(N))
432
+ inertial_force = (M.diff(t) * vel + M * acc)
433
+ for j in range(o):
434
+ temp = zero_uaux(partials[i][0][j])
435
+ for k in range(o):
436
+ MM[j, k] += M * (temp & partials[i][0][k])
437
+ nonMM[j] += inertial_force & partials[i][0][j]
438
+ # Compose fr_star out of MM and nonMM
439
+ MM = zero_uaux(msubs(MM, q_ddot_u_map))
440
+ nonMM = msubs(msubs(nonMM, q_ddot_u_map),
441
+ udot_zero, uauxdot_zero, uaux_zero)
442
+ fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM)
443
+
444
+ # If there are dependent speeds, we need to find fr_star_tilde
445
+ if self._udep:
446
+ p = o - len(self._udep)
447
+ fr_star_ind = fr_star[:p, 0]
448
+ fr_star_dep = fr_star[p:o, 0]
449
+ fr_star = fr_star_ind + (self._Ars.T * fr_star_dep)
450
+ # Apply the same to MM
451
+ MMi = MM[:p, :]
452
+ MMd = MM[p:o, :]
453
+ MM = MMi + (self._Ars.T * MMd)
454
+
455
+ self._bodylist = bl
456
+ self._frstar = fr_star
457
+ self._k_d = MM
458
+ self._f_d = -msubs(self._fr + self._frstar, udot_zero)
459
+ return fr_star
460
+
461
+ def to_linearizer(self):
462
+ """Returns an instance of the Linearizer class, initiated from the
463
+ data in the KanesMethod class. This may be more desirable than using
464
+ the linearize class method, as the Linearizer object will allow more
465
+ efficient recalculation (i.e. about varying operating points)."""
466
+
467
+ if (self._fr is None) or (self._frstar is None):
468
+ raise ValueError('Need to compute Fr, Fr* first.')
469
+
470
+ # Get required equation components. The Kane's method class breaks
471
+ # these into pieces. Need to reassemble
472
+ f_c = self._f_h
473
+ if self._f_nh and self._k_nh:
474
+ f_v = self._f_nh + self._k_nh*Matrix(self.u)
475
+ else:
476
+ f_v = Matrix()
477
+ if self._f_dnh and self._k_dnh:
478
+ f_a = self._f_dnh + self._k_dnh*Matrix(self._udot)
479
+ else:
480
+ f_a = Matrix()
481
+ # Dicts to sub to zero, for splitting up expressions
482
+ u_zero = {i: 0 for i in self.u}
483
+ ud_zero = {i: 0 for i in self._udot}
484
+ qd_zero = {i: 0 for i in self._qdot}
485
+ qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])}
486
+ # Break the kinematic differential eqs apart into f_0 and f_1
487
+ f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot)
488
+ f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u)
489
+ # Break the dynamic differential eqs into f_2 and f_3
490
+ f_2 = msubs(self._frstar, qd_u_zero)
491
+ f_3 = msubs(self._frstar, ud_zero) + self._fr
492
+ f_4 = zeros(len(f_2), 1)
493
+
494
+ # Get the required vector components
495
+ q = self.q
496
+ u = self.u
497
+ if self._qdep:
498
+ q_i = q[:-len(self._qdep)]
499
+ else:
500
+ q_i = q
501
+ q_d = self._qdep
502
+ if self._udep:
503
+ u_i = u[:-len(self._udep)]
504
+ else:
505
+ u_i = u
506
+ u_d = self._udep
507
+
508
+ # Form dictionary to set auxiliary speeds & their derivatives to 0.
509
+ uaux = self._uaux
510
+ uauxdot = uaux.diff(dynamicsymbols._t)
511
+ uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])}
512
+
513
+ # Checking for dynamic symbols outside the dynamic differential
514
+ # equations; throws error if there is.
515
+ sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot]))
516
+ if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot,
517
+ self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]):
518
+ raise ValueError('Cannot have dynamicsymbols outside dynamic \
519
+ forcing vector.')
520
+
521
+ # Find all other dynamic symbols, forming the forcing vector r.
522
+ # Sort r to make it canonical.
523
+ r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list))
524
+ r.sort(key=default_sort_key)
525
+
526
+ # Check for any derivatives of variables in r that are also found in r.
527
+ for i in r:
528
+ if diff(i, dynamicsymbols._t) in r:
529
+ raise ValueError('Cannot have derivatives of specified \
530
+ quantities when linearizing forcing terms.')
531
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
532
+ q_d, u_i, u_d, r)
533
+
534
+ # TODO : Remove `new_method` after 1.1 has been released.
535
+ def linearize(self, *, new_method=None, **kwargs):
536
+ """ Linearize the equations of motion about a symbolic operating point.
537
+
538
+ Explanation
539
+ ===========
540
+
541
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
542
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
543
+
544
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
545
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
546
+ computationally intensive if there are many symbolic parameters. For
547
+ this reason, it may be more desirable to use the default A_and_B=False,
548
+ returning M, A, and B. Values may then be substituted in to these
549
+ matrices, and the state space form found as
550
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
551
+
552
+ In both cases, r is found as all dynamicsymbols in the equations of
553
+ motion that are not part of q, u, q', or u'. They are sorted in
554
+ canonical form.
555
+
556
+ The operating points may be also entered using the ``op_point`` kwarg.
557
+ This takes a dictionary of {symbol: value}, or a an iterable of such
558
+ dictionaries. The values may be numeric or symbolic. The more values
559
+ you can specify beforehand, the faster this computation will run.
560
+
561
+ For more documentation, please see the ``Linearizer`` class."""
562
+ linearizer = self.to_linearizer()
563
+ result = linearizer.linearize(**kwargs)
564
+ return result + (linearizer.r,)
565
+
566
+ def kanes_equations(self, bodies=None, loads=None):
567
+ """ Method to form Kane's equations, Fr + Fr* = 0.
568
+
569
+ Explanation
570
+ ===========
571
+
572
+ Returns (Fr, Fr*). In the case where auxiliary generalized speeds are
573
+ present (say, s auxiliary speeds, o generalized speeds, and m motion
574
+ constraints) the length of the returned vectors will be o - m + s in
575
+ length. The first o - m equations will be the constrained Kane's
576
+ equations, then the s auxiliary Kane's equations. These auxiliary
577
+ equations can be accessed with the auxiliary_eqs property.
578
+
579
+ Parameters
580
+ ==========
581
+
582
+ bodies : iterable
583
+ An iterable of all RigidBody's and Particle's in the system.
584
+ A system must have at least one body.
585
+ loads : iterable
586
+ Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector)
587
+ tuples which represent the force at a point or torque on a frame.
588
+ Must be either a non-empty iterable of tuples or None which corresponds
589
+ to a system with no constraints.
590
+ """
591
+ if bodies is None:
592
+ bodies = self.bodies
593
+ if loads is None and self._forcelist is not None:
594
+ loads = self._forcelist
595
+ if loads == []:
596
+ loads = None
597
+ if not self._k_kqdot:
598
+ raise AttributeError('Create an instance of KanesMethod with '
599
+ 'kinematic differential equations to use this method.')
600
+ fr = self._form_fr(loads)
601
+ frstar = self._form_frstar(bodies)
602
+ if self._uaux:
603
+ if not self._udep:
604
+ km = KanesMethod(self._inertial, self.q, self._uaux,
605
+ u_auxiliary=self._uaux)
606
+ else:
607
+ km = KanesMethod(self._inertial, self.q, self._uaux,
608
+ u_auxiliary=self._uaux, u_dependent=self._udep,
609
+ velocity_constraints=(self._k_nh * self.u +
610
+ self._f_nh),
611
+ acceleration_constraints=(self._k_dnh * self._udot +
612
+ self._f_dnh)
613
+ )
614
+ km._qdot_u_map = self._qdot_u_map
615
+ self._km = km
616
+ fraux = km._form_fr(loads)
617
+ frstaraux = km._form_frstar(bodies)
618
+ self._aux_eq = fraux + frstaraux
619
+ self._fr = fr.col_join(fraux)
620
+ self._frstar = frstar.col_join(frstaraux)
621
+ return (self._fr, self._frstar)
622
+
623
+ def _form_eoms(self):
624
+ fr, frstar = self.kanes_equations(self.bodylist, self.forcelist)
625
+ return fr + frstar
626
+
627
+ def rhs(self, inv_method=None):
628
+ """Returns the system's equations of motion in first order form. The
629
+ output is the right hand side of::
630
+
631
+ x' = |q'| =: f(q, u, r, p, t)
632
+ |u'|
633
+
634
+ The right hand side is what is needed by most numerical ODE
635
+ integrators.
636
+
637
+ Parameters
638
+ ==========
639
+
640
+ inv_method : str
641
+ The specific sympy inverse matrix calculation method to use. For a
642
+ list of valid methods, see
643
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
644
+
645
+ """
646
+ rhs = zeros(len(self.q) + len(self.u), 1)
647
+ kdes = self.kindiffdict()
648
+ for i, q_i in enumerate(self.q):
649
+ rhs[i] = kdes[q_i.diff()]
650
+
651
+ if inv_method is None:
652
+ rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing)
653
+ else:
654
+ rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method,
655
+ try_block_diag=True) *
656
+ self.forcing)
657
+
658
+ return rhs
659
+
660
+ def kindiffdict(self):
661
+ """Returns a dictionary mapping q' to u."""
662
+ if not self._qdot_u_map:
663
+ raise AttributeError('Create an instance of KanesMethod with '
664
+ 'kinematic differential equations to use this method.')
665
+ return self._qdot_u_map
666
+
667
+ @property
668
+ def auxiliary_eqs(self):
669
+ """A matrix containing the auxiliary equations."""
670
+ if not self._fr or not self._frstar:
671
+ raise ValueError('Need to compute Fr, Fr* first.')
672
+ if not self._uaux:
673
+ raise ValueError('No auxiliary speeds have been declared.')
674
+ return self._aux_eq
675
+
676
+ @property
677
+ def mass_matrix_kin(self):
678
+ r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system."""
679
+ return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit
680
+
681
+ @property
682
+ def forcing_kin(self):
683
+ """The kinematic "forcing vector" of the system."""
684
+ if self.explicit_kinematics:
685
+ return -(self._k_ku * Matrix(self.u) + self._f_k)
686
+ else:
687
+ return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit)
688
+
689
+ @property
690
+ def mass_matrix(self):
691
+ """The mass matrix of the system."""
692
+ if not self._fr or not self._frstar:
693
+ raise ValueError('Need to compute Fr, Fr* first.')
694
+ return Matrix([self._k_d, self._k_dnh])
695
+
696
+ @property
697
+ def forcing(self):
698
+ """The forcing vector of the system."""
699
+ if not self._fr or not self._frstar:
700
+ raise ValueError('Need to compute Fr, Fr* first.')
701
+ return -Matrix([self._f_d, self._f_dnh])
702
+
703
+ @property
704
+ def mass_matrix_full(self):
705
+ """The mass matrix of the system, augmented by the kinematic
706
+ differential equations in explicit or implicit form."""
707
+ if not self._fr or not self._frstar:
708
+ raise ValueError('Need to compute Fr, Fr* first.')
709
+ o, n = len(self.u), len(self.q)
710
+ return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join(
711
+ zeros(o, n).row_join(self.mass_matrix))
712
+
713
+ @property
714
+ def forcing_full(self):
715
+ """The forcing vector of the system, augmented by the kinematic
716
+ differential equations in explicit or implicit form."""
717
+ return Matrix([self.forcing_kin, self.forcing])
718
+
719
+ @property
720
+ def q(self):
721
+ return self._q
722
+
723
+ @property
724
+ def u(self):
725
+ return self._u
726
+
727
+ @property
728
+ def bodylist(self):
729
+ return self._bodylist
730
+
731
+ @property
732
+ def forcelist(self):
733
+ return self._forcelist
734
+
735
+ @property
736
+ def bodies(self):
737
+ return self._bodylist
738
+
739
+ @property
740
+ def loads(self):
741
+ return self._forcelist
venv/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend 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 = {i: 0 for i in self._qdoubledots}
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) & 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
+ """Returns an instance of the Linearizer class, initiated from the
294
+ data in the LagrangesMethod class. This may be more desirable than using
295
+ the linearize class method, as the Linearizer object will allow more
296
+ efficient recalculation (i.e. about varying operating points).
297
+
298
+ Parameters
299
+ ==========
300
+
301
+ q_ind, qd_ind : array_like, optional
302
+ The independent generalized coordinates and speeds.
303
+ q_dep, qd_dep : array_like, optional
304
+ The dependent generalized coordinates and speeds.
305
+ """
306
+
307
+ # Compose vectors
308
+ t = dynamicsymbols._t
309
+ q = self.q
310
+ u = self._qdots
311
+ ud = u.diff(t)
312
+ # Get vector of lagrange multipliers
313
+ lams = self.lam_vec
314
+
315
+ mat_build = lambda x: Matrix(x) if x else Matrix()
316
+ q_i = mat_build(q_ind)
317
+ q_d = mat_build(q_dep)
318
+ u_i = mat_build(qd_ind)
319
+ u_d = mat_build(qd_dep)
320
+
321
+ # Compose general form equations
322
+ f_c = self._hol_coneqs
323
+ f_v = self.coneqs
324
+ f_a = f_v.diff(t)
325
+ f_0 = u
326
+ f_1 = -u
327
+ f_2 = self._term1
328
+ f_3 = -(self._term2 + self._term4)
329
+ f_4 = -self._term3
330
+
331
+ # Check that there are an appropriate number of independent and
332
+ # dependent coordinates
333
+ if len(q_d) != len(f_c) or len(u_d) != len(f_v):
334
+ raise ValueError(("Must supply {:} dependent coordinates, and " +
335
+ "{:} dependent speeds").format(len(f_c), len(f_v)))
336
+ if set(Matrix([q_i, q_d])) != set(q):
337
+ raise ValueError("Must partition q into q_ind and q_dep, with " +
338
+ "no extra or missing symbols.")
339
+ if set(Matrix([u_i, u_d])) != set(u):
340
+ raise ValueError("Must partition qd into qd_ind and qd_dep, " +
341
+ "with no extra or missing symbols.")
342
+
343
+ # Find all other dynamic symbols, forming the forcing vector r.
344
+ # Sort r to make it canonical.
345
+ insyms = set(Matrix([q, u, ud, lams]))
346
+ r = list(find_dynamicsymbols(f_3, insyms))
347
+ r.sort(key=default_sort_key)
348
+ # Check for any derivatives of variables in r that are also found in r.
349
+ for i in r:
350
+ if diff(i, dynamicsymbols._t) in r:
351
+ raise ValueError('Cannot have derivatives of specified \
352
+ quantities when linearizing forcing terms.')
353
+
354
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
355
+ q_d, u_i, u_d, r, lams)
356
+
357
+ def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None,
358
+ **kwargs):
359
+ """Linearize the equations of motion about a symbolic operating point.
360
+
361
+ Explanation
362
+ ===========
363
+
364
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
365
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
366
+
367
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
368
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
369
+ computationally intensive if there are many symbolic parameters. For
370
+ this reason, it may be more desirable to use the default A_and_B=False,
371
+ returning M, A, and B. Values may then be substituted in to these
372
+ matrices, and the state space form found as
373
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
374
+
375
+ In both cases, r is found as all dynamicsymbols in the equations of
376
+ motion that are not part of q, u, q', or u'. They are sorted in
377
+ canonical form.
378
+
379
+ The operating points may be also entered using the ``op_point`` kwarg.
380
+ This takes a dictionary of {symbol: value}, or a an iterable of such
381
+ dictionaries. The values may be numeric or symbolic. The more values
382
+ you can specify beforehand, the faster this computation will run.
383
+
384
+ For more documentation, please see the ``Linearizer`` class."""
385
+
386
+ linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep)
387
+ result = linearizer.linearize(**kwargs)
388
+ return result + (linearizer.r,)
389
+
390
+ def solve_multipliers(self, op_point=None, sol_type='dict'):
391
+ """Solves for the values of the lagrange multipliers symbolically at
392
+ the specified operating point.
393
+
394
+ Parameters
395
+ ==========
396
+
397
+ op_point : dict or iterable of dicts, optional
398
+ Point at which to solve at. The operating point is specified as
399
+ a dictionary or iterable of dictionaries of {symbol: value}. The
400
+ value may be numeric or symbolic itself.
401
+
402
+ sol_type : str, optional
403
+ Solution return type. Valid options are:
404
+ - 'dict': A dict of {symbol : value} (default)
405
+ - 'Matrix': An ordered column matrix of the solution
406
+ """
407
+
408
+ # Determine number of multipliers
409
+ k = len(self.lam_vec)
410
+ if k == 0:
411
+ raise ValueError("System has no lagrange multipliers to solve for.")
412
+ # Compose dict of operating conditions
413
+ if isinstance(op_point, dict):
414
+ op_point_dict = op_point
415
+ elif iterable(op_point):
416
+ op_point_dict = {}
417
+ for op in op_point:
418
+ op_point_dict.update(op)
419
+ elif op_point is None:
420
+ op_point_dict = {}
421
+ else:
422
+ raise TypeError("op_point must be either a dictionary or an "
423
+ "iterable of dictionaries.")
424
+ # Compose the system to be solved
425
+ mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join(
426
+ zeros(k, k)))
427
+ force_matrix = self.forcing.col_join(self._f_cd)
428
+ # Sub in the operating point
429
+ mass_matrix = msubs(mass_matrix, op_point_dict)
430
+ force_matrix = msubs(force_matrix, op_point_dict)
431
+ # Solve for the multipliers
432
+ sol_list = mass_matrix.LUsolve(-force_matrix)[-k:]
433
+ if sol_type == 'dict':
434
+ return dict(zip(self.lam_vec, sol_list))
435
+ elif sol_type == 'Matrix':
436
+ return Matrix(sol_list)
437
+ else:
438
+ raise ValueError("Unknown sol_type {:}.".format(sol_type))
439
+
440
+ def rhs(self, inv_method=None, **kwargs):
441
+ """Returns equations that can be solved numerically.
442
+
443
+ Parameters
444
+ ==========
445
+
446
+ inv_method : str
447
+ The specific sympy inverse matrix calculation method to use. For a
448
+ list of valid methods, see
449
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
450
+ """
451
+
452
+ if inv_method is None:
453
+ self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full)
454
+ else:
455
+ self._rhs = (self.mass_matrix_full.inv(inv_method,
456
+ try_block_diag=True) * self.forcing_full)
457
+ return self._rhs
458
+
459
+ @property
460
+ def q(self):
461
+ return self._q
462
+
463
+ @property
464
+ def u(self):
465
+ return self._qdots
466
+
467
+ @property
468
+ def bodies(self):
469
+ return self._bodies
470
+
471
+ @property
472
+ def forcelist(self):
473
+ return self._forcelist
474
+
475
+ @property
476
+ def loads(self):
477
+ return self._forcelist
venv/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['Linearizer']
2
+
3
+ from sympy.core.backend 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
8
+
9
+ from collections import namedtuple
10
+ from collections.abc import Iterable
11
+
12
+ class Linearizer:
13
+ """This object holds the general model form for a dynamic system.
14
+ This model is used for computing the linearized form of the system,
15
+ while properly dealing with constraints leading to dependent
16
+ coordinates and speeds.
17
+
18
+ Attributes
19
+ ==========
20
+
21
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
22
+ Matrices holding the general system form.
23
+ q, u, r : Matrix
24
+ Matrices holding the generalized coordinates, speeds, and
25
+ input vectors.
26
+ q_i, u_i : Matrix
27
+ Matrices of the independent generalized coordinates and speeds.
28
+ q_d, u_d : Matrix
29
+ Matrices of the dependent generalized coordinates and speeds.
30
+ perm_mat : Matrix
31
+ Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
32
+ """
33
+
34
+ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u,
35
+ q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None):
36
+ """
37
+ Parameters
38
+ ==========
39
+
40
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
41
+ System of equations holding the general system form.
42
+ Supply empty array or Matrix if the parameter
43
+ does not exist.
44
+ q : array_like
45
+ The generalized coordinates.
46
+ u : array_like
47
+ The generalized speeds
48
+ q_i, u_i : array_like, optional
49
+ The independent generalized coordinates and speeds.
50
+ q_d, u_d : array_like, optional
51
+ The dependent generalized coordinates and speeds.
52
+ r : array_like, optional
53
+ The input variables.
54
+ lams : array_like, optional
55
+ The lagrange multipliers
56
+ """
57
+
58
+ # Generalized equation form
59
+ self.f_0 = Matrix(f_0)
60
+ self.f_1 = Matrix(f_1)
61
+ self.f_2 = Matrix(f_2)
62
+ self.f_3 = Matrix(f_3)
63
+ self.f_4 = Matrix(f_4)
64
+ self.f_c = Matrix(f_c)
65
+ self.f_v = Matrix(f_v)
66
+ self.f_a = Matrix(f_a)
67
+
68
+ # Generalized equation variables
69
+ self.q = Matrix(q)
70
+ self.u = Matrix(u)
71
+ none_handler = lambda x: Matrix(x) if x else Matrix()
72
+ self.q_i = none_handler(q_i)
73
+ self.q_d = none_handler(q_d)
74
+ self.u_i = none_handler(u_i)
75
+ self.u_d = none_handler(u_d)
76
+ self.r = none_handler(r)
77
+ self.lams = none_handler(lams)
78
+
79
+ # Derivatives of generalized equation variables
80
+ self._qd = self.q.diff(dynamicsymbols._t)
81
+ self._ud = self.u.diff(dynamicsymbols._t)
82
+ # If the user doesn't actually use generalized variables, and the
83
+ # qd and u vectors have any intersecting variables, this can cause
84
+ # problems. We'll fix this with some hackery, and Dummy variables
85
+ dup_vars = set(self._qd).intersection(self.u)
86
+ self._qd_dup = Matrix([var if var not in dup_vars else Dummy()
87
+ for var in self._qd])
88
+
89
+ # Derive dimesion terms
90
+ l = len(self.f_c)
91
+ m = len(self.f_v)
92
+ n = len(self.q)
93
+ o = len(self.u)
94
+ s = len(self.r)
95
+ k = len(self.lams)
96
+ dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
97
+ self._dims = dims(l, m, n, o, s, k)
98
+
99
+ self._Pq = None
100
+ self._Pqi = None
101
+ self._Pqd = None
102
+ self._Pu = None
103
+ self._Pui = None
104
+ self._Pud = None
105
+ self._C_0 = None
106
+ self._C_1 = None
107
+ self._C_2 = None
108
+ self.perm_mat = None
109
+
110
+ self._setup_done = False
111
+
112
+ def _setup(self):
113
+ # Calculations here only need to be run once. They are moved out of
114
+ # the __init__ method to increase the speed of Linearizer creation.
115
+ self._form_permutation_matrices()
116
+ self._form_block_matrices()
117
+ self._form_coefficient_matrices()
118
+ self._setup_done = True
119
+
120
+ def _form_permutation_matrices(self):
121
+ """Form the permutation matrices Pq and Pu."""
122
+
123
+ # Extract dimension variables
124
+ l, m, n, o, s, k = self._dims
125
+ # Compute permutation matrices
126
+ if n != 0:
127
+ self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
128
+ if l > 0:
129
+ self._Pqi = self._Pq[:, :-l]
130
+ self._Pqd = self._Pq[:, -l:]
131
+ else:
132
+ self._Pqi = self._Pq
133
+ self._Pqd = Matrix()
134
+ if o != 0:
135
+ self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
136
+ if m > 0:
137
+ self._Pui = self._Pu[:, :-m]
138
+ self._Pud = self._Pu[:, -m:]
139
+ else:
140
+ self._Pui = self._Pu
141
+ self._Pud = Matrix()
142
+ # Compute combination permutation matrix for computing A and B
143
+ P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
144
+ P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
145
+ if P_col1:
146
+ if P_col2:
147
+ self.perm_mat = P_col1.row_join(P_col2)
148
+ else:
149
+ self.perm_mat = P_col1
150
+ else:
151
+ self.perm_mat = P_col2
152
+
153
+ def _form_coefficient_matrices(self):
154
+ """Form the coefficient matrices C_0, C_1, and C_2."""
155
+
156
+ # Extract dimension variables
157
+ l, m, n, o, s, k = self._dims
158
+ # Build up the coefficient matrices C_0, C_1, and C_2
159
+ # If there are configuration constraints (l > 0), form C_0 as normal.
160
+ # If not, C_0 is I_(nxn). Note that this works even if n=0
161
+ if l > 0:
162
+ f_c_jac_q = self.f_c.jacobian(self.q)
163
+ self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q *
164
+ self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi
165
+ else:
166
+ self._C_0 = eye(n)
167
+ # If there are motion constraints (m > 0), form C_1 and C_2 as normal.
168
+ # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
169
+ # o = 0.
170
+ if m > 0:
171
+ f_v_jac_u = self.f_v.jacobian(self.u)
172
+ temp = f_v_jac_u * self._Pud
173
+ if n != 0:
174
+ f_v_jac_q = self.f_v.jacobian(self.q)
175
+ self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q)
176
+ else:
177
+ self._C_1 = zeros(o, n)
178
+ self._C_2 = (eye(o) - self._Pud *
179
+ temp.LUsolve(f_v_jac_u)) * self._Pui
180
+ else:
181
+ self._C_1 = zeros(o, n)
182
+ self._C_2 = eye(o)
183
+
184
+ def _form_block_matrices(self):
185
+ """Form the block matrices for composing M, A, and B."""
186
+
187
+ # Extract dimension variables
188
+ l, m, n, o, s, k = self._dims
189
+ # Block Matrix Definitions. These are only defined if under certain
190
+ # conditions. If undefined, an empty matrix is used instead
191
+ if n != 0:
192
+ self._M_qq = self.f_0.jacobian(self._qd)
193
+ self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
194
+ else:
195
+ self._M_qq = Matrix()
196
+ self._A_qq = Matrix()
197
+ if n != 0 and m != 0:
198
+ self._M_uqc = self.f_a.jacobian(self._qd_dup)
199
+ self._A_uqc = -self.f_a.jacobian(self.q)
200
+ else:
201
+ self._M_uqc = Matrix()
202
+ self._A_uqc = Matrix()
203
+ if n != 0 and o - m + k != 0:
204
+ self._M_uqd = self.f_3.jacobian(self._qd_dup)
205
+ self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
206
+ else:
207
+ self._M_uqd = Matrix()
208
+ self._A_uqd = Matrix()
209
+ if o != 0 and m != 0:
210
+ self._M_uuc = self.f_a.jacobian(self._ud)
211
+ self._A_uuc = -self.f_a.jacobian(self.u)
212
+ else:
213
+ self._M_uuc = Matrix()
214
+ self._A_uuc = Matrix()
215
+ if o != 0 and o - m + k != 0:
216
+ self._M_uud = self.f_2.jacobian(self._ud)
217
+ self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
218
+ else:
219
+ self._M_uud = Matrix()
220
+ self._A_uud = Matrix()
221
+ if o != 0 and n != 0:
222
+ self._A_qu = -self.f_1.jacobian(self.u)
223
+ else:
224
+ self._A_qu = Matrix()
225
+ if k != 0 and o - m + k != 0:
226
+ self._M_uld = self.f_4.jacobian(self.lams)
227
+ else:
228
+ self._M_uld = Matrix()
229
+ if s != 0 and o - m + k != 0:
230
+ self._B_u = -self.f_3.jacobian(self.r)
231
+ else:
232
+ self._B_u = Matrix()
233
+
234
+ def linearize(self, op_point=None, A_and_B=False, simplify=False):
235
+ """Linearize the system about the operating point. Note that
236
+ q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
237
+ These may be either symbolic or numeric.
238
+
239
+ Parameters
240
+ ==========
241
+
242
+ op_point : dict or iterable of dicts, optional
243
+ Dictionary or iterable of dictionaries containing the operating
244
+ point conditions. These will be substituted in to the linearized
245
+ system before the linearization is complete. Leave blank if you
246
+ want a completely symbolic form. Note that any reduction in
247
+ symbols (whether substituted for numbers or expressions with a
248
+ common parameter) will result in faster runtime.
249
+
250
+ A_and_B : bool, optional
251
+ If A_and_B=False (default), (M, A, B) is returned for forming
252
+ [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True,
253
+ (A, B) is returned for forming dx = [A]x + [B]r, where
254
+ x = [q_ind, u_ind]^T.
255
+
256
+ simplify : bool, optional
257
+ Determines if returned values are simplified before return.
258
+ For large expressions this may be time consuming. Default is False.
259
+
260
+ Potential Issues
261
+ ================
262
+
263
+ Note that the process of solving with A_and_B=True is
264
+ computationally intensive if there are many symbolic parameters.
265
+ For this reason, it may be more desirable to use the default
266
+ A_and_B=False, returning M, A, and B. More values may then be
267
+ substituted in to these matrices later on. The state space form can
268
+ then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where
269
+ P = Linearizer.perm_mat.
270
+ """
271
+
272
+ # Run the setup if needed:
273
+ if not self._setup_done:
274
+ self._setup()
275
+
276
+ # Compose dict of operating conditions
277
+ if isinstance(op_point, dict):
278
+ op_point_dict = op_point
279
+ elif isinstance(op_point, Iterable):
280
+ op_point_dict = {}
281
+ for op in op_point:
282
+ op_point_dict.update(op)
283
+ else:
284
+ op_point_dict = {}
285
+
286
+ # Extract dimension variables
287
+ l, m, n, o, s, k = self._dims
288
+
289
+ # Rename terms to shorten expressions
290
+ M_qq = self._M_qq
291
+ M_uqc = self._M_uqc
292
+ M_uqd = self._M_uqd
293
+ M_uuc = self._M_uuc
294
+ M_uud = self._M_uud
295
+ M_uld = self._M_uld
296
+ A_qq = self._A_qq
297
+ A_uqc = self._A_uqc
298
+ A_uqd = self._A_uqd
299
+ A_qu = self._A_qu
300
+ A_uuc = self._A_uuc
301
+ A_uud = self._A_uud
302
+ B_u = self._B_u
303
+ C_0 = self._C_0
304
+ C_1 = self._C_1
305
+ C_2 = self._C_2
306
+
307
+ # Build up Mass Matrix
308
+ # |M_qq 0_nxo 0_nxk|
309
+ # M = |M_uqc M_uuc 0_mxk|
310
+ # |M_uqd M_uud M_uld|
311
+ if o != 0:
312
+ col2 = Matrix([zeros(n, o), M_uuc, M_uud])
313
+ if k != 0:
314
+ col3 = Matrix([zeros(n + m, k), M_uld])
315
+ if n != 0:
316
+ col1 = Matrix([M_qq, M_uqc, M_uqd])
317
+ if o != 0 and k != 0:
318
+ M = col1.row_join(col2).row_join(col3)
319
+ elif o != 0:
320
+ M = col1.row_join(col2)
321
+ else:
322
+ M = col1
323
+ elif k != 0:
324
+ M = col2.row_join(col3)
325
+ else:
326
+ M = col2
327
+ M_eq = msubs(M, op_point_dict)
328
+
329
+ # Build up state coefficient matrix A
330
+ # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
331
+ # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
332
+ # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
333
+ # Col 1 is only defined if n != 0
334
+ if n != 0:
335
+ r1c1 = A_qq
336
+ if o != 0:
337
+ r1c1 += (A_qu * C_1)
338
+ r1c1 = r1c1 * C_0
339
+ if m != 0:
340
+ r2c1 = A_uqc
341
+ if o != 0:
342
+ r2c1 += (A_uuc * C_1)
343
+ r2c1 = r2c1 * C_0
344
+ else:
345
+ r2c1 = Matrix()
346
+ if o - m + k != 0:
347
+ r3c1 = A_uqd
348
+ if o != 0:
349
+ r3c1 += (A_uud * C_1)
350
+ r3c1 = r3c1 * C_0
351
+ else:
352
+ r3c1 = Matrix()
353
+ col1 = Matrix([r1c1, r2c1, r3c1])
354
+ else:
355
+ col1 = Matrix()
356
+ # Col 2 is only defined if o != 0
357
+ if o != 0:
358
+ if n != 0:
359
+ r1c2 = A_qu * C_2
360
+ else:
361
+ r1c2 = Matrix()
362
+ if m != 0:
363
+ r2c2 = A_uuc * C_2
364
+ else:
365
+ r2c2 = Matrix()
366
+ if o - m + k != 0:
367
+ r3c2 = A_uud * C_2
368
+ else:
369
+ r3c2 = Matrix()
370
+ col2 = Matrix([r1c2, r2c2, r3c2])
371
+ else:
372
+ col2 = Matrix()
373
+ if col1:
374
+ if col2:
375
+ Amat = col1.row_join(col2)
376
+ else:
377
+ Amat = col1
378
+ else:
379
+ Amat = col2
380
+ Amat_eq = msubs(Amat, op_point_dict)
381
+
382
+ # Build up the B matrix if there are forcing variables
383
+ # |0_(n + m)xs|
384
+ # B = |B_u |
385
+ if s != 0 and o - m + k != 0:
386
+ Bmat = zeros(n + m, s).col_join(B_u)
387
+ Bmat_eq = msubs(Bmat, op_point_dict)
388
+ else:
389
+ Bmat_eq = Matrix()
390
+
391
+ # kwarg A_and_B indicates to return A, B for forming the equation
392
+ # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
393
+ if A_and_B:
394
+ A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq)
395
+ if Bmat_eq:
396
+ B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq)
397
+ else:
398
+ # Bmat = Matrix([]), so no need to sub
399
+ B_cont = Bmat_eq
400
+ if simplify:
401
+ A_cont.simplify()
402
+ B_cont.simplify()
403
+ return A_cont, B_cont
404
+ # Otherwise return M, A, B for forming the equation
405
+ # [M]dx = [A]x + [B]r, where x = [q, u]^T
406
+ else:
407
+ if simplify:
408
+ M_eq.simplify()
409
+ Amat_eq.simplify()
410
+ Bmat_eq.simplify()
411
+ return M_eq, Amat_eq, Bmat_eq
412
+
413
+
414
+ def permutation_matrix(orig_vec, per_vec):
415
+ """Compute the permutation matrix to change order of
416
+ orig_vec into order of per_vec.
417
+
418
+ Parameters
419
+ ==========
420
+
421
+ orig_vec : array_like
422
+ Symbols in original ordering.
423
+ per_vec : array_like
424
+ Symbols in new ordering.
425
+
426
+ Returns
427
+ =======
428
+
429
+ p_matrix : Matrix
430
+ Permutation matrix such that orig_vec == (p_matrix * per_vec).
431
+ """
432
+ if not isinstance(orig_vec, (list, tuple)):
433
+ orig_vec = flatten(orig_vec)
434
+ if not isinstance(per_vec, (list, tuple)):
435
+ per_vec = flatten(per_vec)
436
+ if set(orig_vec) != set(per_vec):
437
+ raise ValueError("orig_vec and per_vec must be the same length, " +
438
+ "and contain the same symbols.")
439
+ ind_list = [orig_vec.index(i) for i in per_vec]
440
+ p_matrix = zeros(len(orig_vec))
441
+ for i, j in enumerate(ind_list):
442
+ p_matrix[i, j] = 1
443
+ return p_matrix
venv/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.")
venv/lib/python3.10/site-packages/sympy/physics/mechanics/models.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """This module contains some sample symbolic models used for testing and
3
+ examples."""
4
+
5
+ # Internal imports
6
+ from sympy.core import backend as sm
7
+ import sympy.physics.mechanics as me
8
+
9
+
10
+ def multi_mass_spring_damper(n=1, apply_gravity=False,
11
+ apply_external_forces=False):
12
+ r"""Returns a system containing the symbolic equations of motion and
13
+ associated variables for a simple multi-degree of freedom point mass,
14
+ spring, damper system with optional gravitational and external
15
+ specified forces. For example, a two mass system under the influence of
16
+ gravity and external forces looks like:
17
+
18
+ ::
19
+
20
+ ----------------
21
+ | | | | g
22
+ \ | | | V
23
+ k0 / --- c0 |
24
+ | | | x0, v0
25
+ --------- V
26
+ | m0 | -----
27
+ --------- |
28
+ | | | |
29
+ \ v | | |
30
+ k1 / f0 --- c1 |
31
+ | | | x1, v1
32
+ --------- V
33
+ | m1 | -----
34
+ ---------
35
+ | f1
36
+ V
37
+
38
+ Parameters
39
+ ==========
40
+
41
+ n : integer
42
+ The number of masses in the serial chain.
43
+ apply_gravity : boolean
44
+ If true, gravity will be applied to each mass.
45
+ apply_external_forces : boolean
46
+ If true, a time varying external force will be applied to each mass.
47
+
48
+ Returns
49
+ =======
50
+
51
+ kane : sympy.physics.mechanics.kane.KanesMethod
52
+ A KanesMethod object.
53
+
54
+ """
55
+
56
+ mass = sm.symbols('m:{}'.format(n))
57
+ stiffness = sm.symbols('k:{}'.format(n))
58
+ damping = sm.symbols('c:{}'.format(n))
59
+
60
+ acceleration_due_to_gravity = sm.symbols('g')
61
+
62
+ coordinates = me.dynamicsymbols('x:{}'.format(n))
63
+ speeds = me.dynamicsymbols('v:{}'.format(n))
64
+ specifieds = me.dynamicsymbols('f:{}'.format(n))
65
+
66
+ ceiling = me.ReferenceFrame('N')
67
+ origin = me.Point('origin')
68
+ origin.set_vel(ceiling, 0)
69
+
70
+ points = [origin]
71
+ kinematic_equations = []
72
+ particles = []
73
+ forces = []
74
+
75
+ for i in range(n):
76
+
77
+ center = points[-1].locatenew('center{}'.format(i),
78
+ coordinates[i] * ceiling.x)
79
+ center.set_vel(ceiling, points[-1].vel(ceiling) +
80
+ speeds[i] * ceiling.x)
81
+ points.append(center)
82
+
83
+ block = me.Particle('block{}'.format(i), center, mass[i])
84
+
85
+ kinematic_equations.append(speeds[i] - coordinates[i].diff())
86
+
87
+ total_force = (-stiffness[i] * coordinates[i] -
88
+ damping[i] * speeds[i])
89
+ try:
90
+ total_force += (stiffness[i + 1] * coordinates[i + 1] +
91
+ damping[i + 1] * speeds[i + 1])
92
+ except IndexError: # no force from below on last mass
93
+ pass
94
+
95
+ if apply_gravity:
96
+ total_force += mass[i] * acceleration_due_to_gravity
97
+
98
+ if apply_external_forces:
99
+ total_force += specifieds[i]
100
+
101
+ forces.append((center, total_force * ceiling.x))
102
+
103
+ particles.append(block)
104
+
105
+ kane = me.KanesMethod(ceiling, q_ind=coordinates, u_ind=speeds,
106
+ kd_eqs=kinematic_equations)
107
+ kane.kanes_equations(particles, forces)
108
+
109
+ return kane
110
+
111
+
112
+ def n_link_pendulum_on_cart(n=1, cart_force=True, joint_torques=False):
113
+ r"""Returns the system containing the symbolic first order equations of
114
+ motion for a 2D n-link pendulum on a sliding cart under the influence of
115
+ gravity.
116
+
117
+ ::
118
+
119
+ |
120
+ o y v
121
+ \ 0 ^ g
122
+ \ |
123
+ --\-|----
124
+ | \| |
125
+ F-> | o --|---> x
126
+ | |
127
+ ---------
128
+ o o
129
+
130
+ Parameters
131
+ ==========
132
+
133
+ n : integer
134
+ The number of links in the pendulum.
135
+ cart_force : boolean, default=True
136
+ If true an external specified lateral force is applied to the cart.
137
+ joint_torques : boolean, default=False
138
+ If true joint torques will be added as specified inputs at each
139
+ joint.
140
+
141
+ Returns
142
+ =======
143
+
144
+ kane : sympy.physics.mechanics.kane.KanesMethod
145
+ A KanesMethod object.
146
+
147
+ Notes
148
+ =====
149
+
150
+ The degrees of freedom of the system are n + 1, i.e. one for each
151
+ pendulum link and one for the lateral motion of the cart.
152
+
153
+ M x' = F, where x = [u0, ..., un+1, q0, ..., qn+1]
154
+
155
+ The joint angles are all defined relative to the ground where the x axis
156
+ defines the ground line and the y axis points up. The joint torques are
157
+ applied between each adjacent link and the between the cart and the
158
+ lower link where a positive torque corresponds to positive angle.
159
+
160
+ """
161
+ if n <= 0:
162
+ raise ValueError('The number of links must be a positive integer.')
163
+
164
+ q = me.dynamicsymbols('q:{}'.format(n + 1))
165
+ u = me.dynamicsymbols('u:{}'.format(n + 1))
166
+
167
+ if joint_torques is True:
168
+ T = me.dynamicsymbols('T1:{}'.format(n + 1))
169
+
170
+ m = sm.symbols('m:{}'.format(n + 1))
171
+ l = sm.symbols('l:{}'.format(n))
172
+ g, t = sm.symbols('g t')
173
+
174
+ I = me.ReferenceFrame('I')
175
+ O = me.Point('O')
176
+ O.set_vel(I, 0)
177
+
178
+ P0 = me.Point('P0')
179
+ P0.set_pos(O, q[0] * I.x)
180
+ P0.set_vel(I, u[0] * I.x)
181
+ Pa0 = me.Particle('Pa0', P0, m[0])
182
+
183
+ frames = [I]
184
+ points = [P0]
185
+ particles = [Pa0]
186
+ forces = [(P0, -m[0] * g * I.y)]
187
+ kindiffs = [q[0].diff(t) - u[0]]
188
+
189
+ if cart_force is True or joint_torques is True:
190
+ specified = []
191
+ else:
192
+ specified = None
193
+
194
+ for i in range(n):
195
+ Bi = I.orientnew('B{}'.format(i), 'Axis', [q[i + 1], I.z])
196
+ Bi.set_ang_vel(I, u[i + 1] * I.z)
197
+ frames.append(Bi)
198
+
199
+ Pi = points[-1].locatenew('P{}'.format(i + 1), l[i] * Bi.y)
200
+ Pi.v2pt_theory(points[-1], I, Bi)
201
+ points.append(Pi)
202
+
203
+ Pai = me.Particle('Pa' + str(i + 1), Pi, m[i + 1])
204
+ particles.append(Pai)
205
+
206
+ forces.append((Pi, -m[i + 1] * g * I.y))
207
+
208
+ if joint_torques is True:
209
+
210
+ specified.append(T[i])
211
+
212
+ if i == 0:
213
+ forces.append((I, -T[i] * I.z))
214
+
215
+ if i == n - 1:
216
+ forces.append((Bi, T[i] * I.z))
217
+ else:
218
+ forces.append((Bi, T[i] * I.z - T[i + 1] * I.z))
219
+
220
+ kindiffs.append(q[i + 1].diff(t) - u[i + 1])
221
+
222
+ if cart_force is True:
223
+ F = me.dynamicsymbols('F')
224
+ forces.append((P0, F * I.x))
225
+ specified.append(F)
226
+
227
+ kane = me.KanesMethod(I, q_ind=q, u_ind=u, kd_eqs=kindiffs)
228
+ kane.kanes_equations(particles, forces)
229
+
230
+ return kane
venv/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import sympify
2
+ from sympy.physics.vector import Point
3
+
4
+ from sympy.utilities.exceptions import sympy_deprecation_warning
5
+
6
+ __all__ = ['Particle']
7
+
8
+
9
+ class Particle:
10
+ """A particle.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ Particles have a non-zero mass and lack spatial extension; they take up no
16
+ space.
17
+
18
+ Values need to be supplied on initialization, but can be changed later.
19
+
20
+ Parameters
21
+ ==========
22
+
23
+ name : str
24
+ Name of particle
25
+ point : Point
26
+ A physics/mechanics Point which represents the position, velocity, and
27
+ acceleration of this Particle
28
+ mass : sympifyable
29
+ A SymPy expression representing the Particle's mass
30
+
31
+ Examples
32
+ ========
33
+
34
+ >>> from sympy.physics.mechanics import Particle, Point
35
+ >>> from sympy import Symbol
36
+ >>> po = Point('po')
37
+ >>> m = Symbol('m')
38
+ >>> pa = Particle('pa', po, m)
39
+ >>> # Or you could change these later
40
+ >>> pa.mass = m
41
+ >>> pa.point = po
42
+
43
+ """
44
+
45
+ def __init__(self, name, point, mass):
46
+ if not isinstance(name, str):
47
+ raise TypeError('Supply a valid name.')
48
+ self._name = name
49
+ self.mass = mass
50
+ self.point = point
51
+ self.potential_energy = 0
52
+
53
+ def __str__(self):
54
+ return self._name
55
+
56
+ def __repr__(self):
57
+ return self.__str__()
58
+
59
+ @property
60
+ def mass(self):
61
+ """Mass of the particle."""
62
+ return self._mass
63
+
64
+ @mass.setter
65
+ def mass(self, value):
66
+ self._mass = sympify(value)
67
+
68
+ @property
69
+ def point(self):
70
+ """Point of the particle."""
71
+ return self._point
72
+
73
+ @point.setter
74
+ def point(self, p):
75
+ if not isinstance(p, Point):
76
+ raise TypeError("Particle point attribute must be a Point object.")
77
+ self._point = p
78
+
79
+ def linear_momentum(self, frame):
80
+ """Linear momentum of the particle.
81
+
82
+ Explanation
83
+ ===========
84
+
85
+ The linear momentum L, of a particle P, with respect to frame N is
86
+ given by:
87
+
88
+ L = m * v
89
+
90
+ where m is the mass of the particle, and v is the velocity of the
91
+ particle in the frame N.
92
+
93
+ Parameters
94
+ ==========
95
+
96
+ frame : ReferenceFrame
97
+ The frame in which linear momentum is desired.
98
+
99
+ Examples
100
+ ========
101
+
102
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
103
+ >>> from sympy.physics.mechanics import dynamicsymbols
104
+ >>> from sympy.physics.vector import init_vprinting
105
+ >>> init_vprinting(pretty_print=False)
106
+ >>> m, v = dynamicsymbols('m v')
107
+ >>> N = ReferenceFrame('N')
108
+ >>> P = Point('P')
109
+ >>> A = Particle('A', P, m)
110
+ >>> P.set_vel(N, v * N.x)
111
+ >>> A.linear_momentum(N)
112
+ m*v*N.x
113
+
114
+ """
115
+
116
+ return self.mass * self.point.vel(frame)
117
+
118
+ def angular_momentum(self, point, frame):
119
+ """Angular momentum of the particle about the point.
120
+
121
+ Explanation
122
+ ===========
123
+
124
+ The angular momentum H, about some point O of a particle, P, is given
125
+ by:
126
+
127
+ ``H = cross(r, m * v)``
128
+
129
+ where r is the position vector from point O to the particle P, m is
130
+ the mass of the particle, and v is the velocity of the particle in
131
+ the inertial frame, N.
132
+
133
+ Parameters
134
+ ==========
135
+
136
+ point : Point
137
+ The point about which angular momentum of the particle is desired.
138
+
139
+ frame : ReferenceFrame
140
+ The frame in which angular momentum is desired.
141
+
142
+ Examples
143
+ ========
144
+
145
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
146
+ >>> from sympy.physics.mechanics import dynamicsymbols
147
+ >>> from sympy.physics.vector import init_vprinting
148
+ >>> init_vprinting(pretty_print=False)
149
+ >>> m, v, r = dynamicsymbols('m v r')
150
+ >>> N = ReferenceFrame('N')
151
+ >>> O = Point('O')
152
+ >>> A = O.locatenew('A', r * N.x)
153
+ >>> P = Particle('P', A, m)
154
+ >>> P.point.set_vel(N, v * N.y)
155
+ >>> P.angular_momentum(O, N)
156
+ m*r*v*N.z
157
+
158
+ """
159
+
160
+ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame))
161
+
162
+ def kinetic_energy(self, frame):
163
+ """Kinetic energy of the particle.
164
+
165
+ Explanation
166
+ ===========
167
+
168
+ The kinetic energy, T, of a particle, P, is given by:
169
+
170
+ ``T = 1/2 (dot(m * v, v))``
171
+
172
+ where m is the mass of particle P, and v is the velocity of the
173
+ particle in the supplied ReferenceFrame.
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ frame : ReferenceFrame
179
+ The Particle's velocity is typically defined with respect to
180
+ an inertial frame but any relevant frame in which the velocity is
181
+ known can be supplied.
182
+
183
+ Examples
184
+ ========
185
+
186
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
187
+ >>> from sympy import symbols
188
+ >>> m, v, r = symbols('m v r')
189
+ >>> N = ReferenceFrame('N')
190
+ >>> O = Point('O')
191
+ >>> P = Particle('P', O, m)
192
+ >>> P.point.set_vel(N, v * N.y)
193
+ >>> P.kinetic_energy(N)
194
+ m*v**2/2
195
+
196
+ """
197
+
198
+ return (self.mass / sympify(2) * self.point.vel(frame) &
199
+ self.point.vel(frame))
200
+
201
+ @property
202
+ def potential_energy(self):
203
+ """The potential energy of the Particle.
204
+
205
+ Examples
206
+ ========
207
+
208
+ >>> from sympy.physics.mechanics import Particle, Point
209
+ >>> from sympy import symbols
210
+ >>> m, g, h = symbols('m g h')
211
+ >>> O = Point('O')
212
+ >>> P = Particle('P', O, m)
213
+ >>> P.potential_energy = m * g * h
214
+ >>> P.potential_energy
215
+ g*h*m
216
+
217
+ """
218
+
219
+ return self._pe
220
+
221
+ @potential_energy.setter
222
+ def potential_energy(self, scalar):
223
+ """Used to set the potential energy of the Particle.
224
+
225
+ Parameters
226
+ ==========
227
+
228
+ scalar : Sympifyable
229
+ The potential energy (a scalar) of the Particle.
230
+
231
+ Examples
232
+ ========
233
+
234
+ >>> from sympy.physics.mechanics import Particle, Point
235
+ >>> from sympy import symbols
236
+ >>> m, g, h = symbols('m g h')
237
+ >>> O = Point('O')
238
+ >>> P = Particle('P', O, m)
239
+ >>> P.potential_energy = m * g * h
240
+
241
+ """
242
+
243
+ self._pe = sympify(scalar)
244
+
245
+ def set_potential_energy(self, scalar):
246
+ sympy_deprecation_warning(
247
+ """
248
+ The sympy.physics.mechanics.Particle.set_potential_energy()
249
+ method is deprecated. Instead use
250
+
251
+ P.potential_energy = scalar
252
+ """,
253
+ deprecated_since_version="1.5",
254
+ active_deprecations_target="deprecated-set-potential-energy",
255
+ )
256
+ self.potential_energy = scalar
257
+
258
+ def parallel_axis(self, point, frame):
259
+ """Returns an inertia dyadic of the particle with respect to another
260
+ point and frame.
261
+
262
+ Parameters
263
+ ==========
264
+
265
+ point : sympy.physics.vector.Point
266
+ The point to express the inertia dyadic about.
267
+ frame : sympy.physics.vector.ReferenceFrame
268
+ The reference frame used to construct the dyadic.
269
+
270
+ Returns
271
+ =======
272
+
273
+ inertia : sympy.physics.vector.Dyadic
274
+ The inertia dyadic of the particle expressed about the provided
275
+ point and frame.
276
+
277
+ """
278
+ # circular import issue
279
+ from sympy.physics.mechanics import inertia_of_point_mass
280
+ return inertia_of_point_mass(self.mass, self.point.pos_from(point),
281
+ frame)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import sympify
2
+ from sympy.physics.vector import Point, ReferenceFrame, Dyadic
3
+
4
+ from sympy.utilities.exceptions import sympy_deprecation_warning
5
+
6
+ __all__ = ['RigidBody']
7
+
8
+
9
+ class RigidBody:
10
+ """An idealized rigid body.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ This is essentially a container which holds the various components which
16
+ describe a rigid body: a name, mass, center of mass, reference frame, and
17
+ inertia.
18
+
19
+ All of these need to be supplied on creation, but can be changed
20
+ afterwards.
21
+
22
+ Attributes
23
+ ==========
24
+
25
+ name : string
26
+ The body's name.
27
+ masscenter : Point
28
+ The point which represents the center of mass of the rigid body.
29
+ frame : ReferenceFrame
30
+ The ReferenceFrame which the rigid body is fixed in.
31
+ mass : Sympifyable
32
+ The body's mass.
33
+ inertia : (Dyadic, Point)
34
+ The body's inertia about a point; stored in a tuple as shown above.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy import Symbol
40
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody
41
+ >>> from sympy.physics.mechanics import outer
42
+ >>> m = Symbol('m')
43
+ >>> A = ReferenceFrame('A')
44
+ >>> P = Point('P')
45
+ >>> I = outer (A.x, A.x)
46
+ >>> inertia_tuple = (I, P)
47
+ >>> B = RigidBody('B', P, A, m, inertia_tuple)
48
+ >>> # Or you could change them afterwards
49
+ >>> m2 = Symbol('m2')
50
+ >>> B.mass = m2
51
+
52
+ """
53
+
54
+ def __init__(self, name, masscenter, frame, mass, inertia):
55
+ if not isinstance(name, str):
56
+ raise TypeError('Supply a valid name.')
57
+ self._name = name
58
+ self.masscenter = masscenter
59
+ self.mass = mass
60
+ self.frame = frame
61
+ self.inertia = inertia
62
+ self.potential_energy = 0
63
+
64
+ def __str__(self):
65
+ return self._name
66
+
67
+ def __repr__(self):
68
+ return self.__str__()
69
+
70
+ @property
71
+ def frame(self):
72
+ """The ReferenceFrame fixed to the body."""
73
+ return self._frame
74
+
75
+ @frame.setter
76
+ def frame(self, F):
77
+ if not isinstance(F, ReferenceFrame):
78
+ raise TypeError("RigidBody frame must be a ReferenceFrame object.")
79
+ self._frame = F
80
+
81
+ @property
82
+ def masscenter(self):
83
+ """The body's center of mass."""
84
+ return self._masscenter
85
+
86
+ @masscenter.setter
87
+ def masscenter(self, p):
88
+ if not isinstance(p, Point):
89
+ raise TypeError("RigidBody center of mass must be a Point object.")
90
+ self._masscenter = p
91
+
92
+ @property
93
+ def mass(self):
94
+ """The body's mass."""
95
+ return self._mass
96
+
97
+ @mass.setter
98
+ def mass(self, m):
99
+ self._mass = sympify(m)
100
+
101
+ @property
102
+ def inertia(self):
103
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
104
+ return (self._inertia, self._inertia_point)
105
+
106
+ @inertia.setter
107
+ def inertia(self, I):
108
+ if not isinstance(I[0], Dyadic):
109
+ raise TypeError("RigidBody inertia must be a Dyadic object.")
110
+ if not isinstance(I[1], Point):
111
+ raise TypeError("RigidBody inertia must be about a Point.")
112
+ self._inertia = I[0]
113
+ self._inertia_point = I[1]
114
+ # have I S/O, want I S/S*
115
+ # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O
116
+ # I_S/S* = I_S/O - I_S*/O
117
+ from sympy.physics.mechanics.functions import inertia_of_point_mass
118
+ I_Ss_O = inertia_of_point_mass(self.mass,
119
+ self.masscenter.pos_from(I[1]),
120
+ self.frame)
121
+ self._central_inertia = I[0] - I_Ss_O
122
+
123
+ @property
124
+ def central_inertia(self):
125
+ """The body's central inertia dyadic."""
126
+ return self._central_inertia
127
+
128
+ @central_inertia.setter
129
+ def central_inertia(self, I):
130
+ if not isinstance(I, Dyadic):
131
+ raise TypeError("RigidBody inertia must be a Dyadic object.")
132
+ self.inertia = (I, self.masscenter)
133
+
134
+ def linear_momentum(self, frame):
135
+ """ Linear momentum of the rigid body.
136
+
137
+ Explanation
138
+ ===========
139
+
140
+ The linear momentum L, of a rigid body B, with respect to frame N is
141
+ given by:
142
+
143
+ L = M * v*
144
+
145
+ where M is the mass of the rigid body and v* is the velocity of
146
+ the mass center of B in the frame, N.
147
+
148
+ Parameters
149
+ ==========
150
+
151
+ frame : ReferenceFrame
152
+ The frame in which linear momentum is desired.
153
+
154
+ Examples
155
+ ========
156
+
157
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
158
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
159
+ >>> from sympy.physics.vector import init_vprinting
160
+ >>> init_vprinting(pretty_print=False)
161
+ >>> M, v = dynamicsymbols('M v')
162
+ >>> N = ReferenceFrame('N')
163
+ >>> P = Point('P')
164
+ >>> P.set_vel(N, v * N.x)
165
+ >>> I = outer (N.x, N.x)
166
+ >>> Inertia_tuple = (I, P)
167
+ >>> B = RigidBody('B', P, N, M, Inertia_tuple)
168
+ >>> B.linear_momentum(N)
169
+ M*v*N.x
170
+
171
+ """
172
+
173
+ return self.mass * self.masscenter.vel(frame)
174
+
175
+ def angular_momentum(self, point, frame):
176
+ """Returns the angular momentum of the rigid body about a point in the
177
+ given frame.
178
+
179
+ Explanation
180
+ ===========
181
+
182
+ The angular momentum H of a rigid body B about some point O in a frame
183
+ N is given by:
184
+
185
+ ``H = dot(I, w) + cross(r, M * v)``
186
+
187
+ where I is the central inertia dyadic of B, w is the angular velocity
188
+ of body B in the frame, N, r is the position vector from point O to the
189
+ mass center of B, and v is the velocity of the mass center in the
190
+ frame, N.
191
+
192
+ Parameters
193
+ ==========
194
+
195
+ point : Point
196
+ The point about which angular momentum is desired.
197
+ frame : ReferenceFrame
198
+ The frame in which angular momentum is desired.
199
+
200
+ Examples
201
+ ========
202
+
203
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
204
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
205
+ >>> from sympy.physics.vector import init_vprinting
206
+ >>> init_vprinting(pretty_print=False)
207
+ >>> M, v, r, omega = dynamicsymbols('M v r omega')
208
+ >>> N = ReferenceFrame('N')
209
+ >>> b = ReferenceFrame('b')
210
+ >>> b.set_ang_vel(N, omega * b.x)
211
+ >>> P = Point('P')
212
+ >>> P.set_vel(N, 1 * N.x)
213
+ >>> I = outer(b.x, b.x)
214
+ >>> B = RigidBody('B', P, b, M, (I, P))
215
+ >>> B.angular_momentum(P, N)
216
+ omega*b.x
217
+
218
+ """
219
+ I = self.central_inertia
220
+ w = self.frame.ang_vel_in(frame)
221
+ m = self.mass
222
+ r = self.masscenter.pos_from(point)
223
+ v = self.masscenter.vel(frame)
224
+
225
+ return I.dot(w) + r.cross(m * v)
226
+
227
+ def kinetic_energy(self, frame):
228
+ """Kinetic energy of the rigid body.
229
+
230
+ Explanation
231
+ ===========
232
+
233
+ The kinetic energy, T, of a rigid body, B, is given by:
234
+
235
+ ``T = 1/2 * (dot(dot(I, w), w) + dot(m * v, v))``
236
+
237
+ where I and m are the central inertia dyadic and mass of rigid body B,
238
+ respectively, omega is the body's angular velocity and v is the
239
+ velocity of the body's mass center in the supplied ReferenceFrame.
240
+
241
+ Parameters
242
+ ==========
243
+
244
+ frame : ReferenceFrame
245
+ The RigidBody's angular velocity and the velocity of it's mass
246
+ center are typically defined with respect to an inertial frame but
247
+ any relevant frame in which the velocities are known can be supplied.
248
+
249
+ Examples
250
+ ========
251
+
252
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
253
+ >>> from sympy.physics.mechanics import RigidBody
254
+ >>> from sympy import symbols
255
+ >>> M, v, r, omega = symbols('M v r omega')
256
+ >>> N = ReferenceFrame('N')
257
+ >>> b = ReferenceFrame('b')
258
+ >>> b.set_ang_vel(N, omega * b.x)
259
+ >>> P = Point('P')
260
+ >>> P.set_vel(N, v * N.x)
261
+ >>> I = outer (b.x, b.x)
262
+ >>> inertia_tuple = (I, P)
263
+ >>> B = RigidBody('B', P, b, M, inertia_tuple)
264
+ >>> B.kinetic_energy(N)
265
+ M*v**2/2 + omega**2/2
266
+
267
+ """
268
+
269
+ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia &
270
+ self.frame.ang_vel_in(frame)) / sympify(2))
271
+
272
+ translational_KE = (self.mass * (self.masscenter.vel(frame) &
273
+ self.masscenter.vel(frame)) / sympify(2))
274
+
275
+ return rotational_KE + translational_KE
276
+
277
+ @property
278
+ def potential_energy(self):
279
+ """The potential energy of the RigidBody.
280
+
281
+ Examples
282
+ ========
283
+
284
+ >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame
285
+ >>> from sympy import symbols
286
+ >>> M, g, h = symbols('M g h')
287
+ >>> b = ReferenceFrame('b')
288
+ >>> P = Point('P')
289
+ >>> I = outer (b.x, b.x)
290
+ >>> Inertia_tuple = (I, P)
291
+ >>> B = RigidBody('B', P, b, M, Inertia_tuple)
292
+ >>> B.potential_energy = M * g * h
293
+ >>> B.potential_energy
294
+ M*g*h
295
+
296
+ """
297
+
298
+ return self._pe
299
+
300
+ @potential_energy.setter
301
+ def potential_energy(self, scalar):
302
+ """Used to set the potential energy of this RigidBody.
303
+
304
+ Parameters
305
+ ==========
306
+
307
+ scalar: Sympifyable
308
+ The potential energy (a scalar) of the RigidBody.
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy.physics.mechanics import Point, outer
314
+ >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame
315
+ >>> from sympy import symbols
316
+ >>> b = ReferenceFrame('b')
317
+ >>> M, g, h = symbols('M g h')
318
+ >>> P = Point('P')
319
+ >>> I = outer (b.x, b.x)
320
+ >>> Inertia_tuple = (I, P)
321
+ >>> B = RigidBody('B', P, b, M, Inertia_tuple)
322
+ >>> B.potential_energy = M * g * h
323
+
324
+ """
325
+
326
+ self._pe = sympify(scalar)
327
+
328
+ def set_potential_energy(self, scalar):
329
+ sympy_deprecation_warning(
330
+ """
331
+ The sympy.physics.mechanics.RigidBody.set_potential_energy()
332
+ method is deprecated. Instead use
333
+
334
+ B.potential_energy = scalar
335
+ """,
336
+ deprecated_since_version="1.5",
337
+ active_deprecations_target="deprecated-set-potential-energy",
338
+ )
339
+ self.potential_energy = scalar
340
+
341
+ def parallel_axis(self, point, frame=None):
342
+ """Returns the inertia dyadic of the body with respect to another
343
+ point.
344
+
345
+ Parameters
346
+ ==========
347
+
348
+ point : sympy.physics.vector.Point
349
+ The point to express the inertia dyadic about.
350
+ frame : sympy.physics.vector.ReferenceFrame
351
+ The reference frame used to construct the dyadic.
352
+
353
+ Returns
354
+ =======
355
+
356
+ inertia : sympy.physics.vector.Dyadic
357
+ The inertia dyadic of the rigid body expressed about the provided
358
+ point.
359
+
360
+ """
361
+ # circular import issue
362
+ from sympy.physics.mechanics.functions import inertia_of_point_mass
363
+ if frame is None:
364
+ frame = self.frame
365
+ return self.central_inertia + inertia_of_point_mass(
366
+ self.mass, self.masscenter.pos_from(point), frame)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/system.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import eye, Matrix, zeros
2
+ from sympy.physics.mechanics import dynamicsymbols
3
+ from sympy.physics.mechanics.functions import find_dynamicsymbols
4
+
5
+ __all__ = ['SymbolicSystem']
6
+
7
+
8
+ class SymbolicSystem:
9
+ """SymbolicSystem is a class that contains all the information about a
10
+ system in a symbolic format such as the equations of motions and the bodies
11
+ and loads in the system.
12
+
13
+ There are three ways that the equations of motion can be described for
14
+ Symbolic System:
15
+
16
+
17
+ [1] Explicit form where the kinematics and dynamics are combined
18
+ x' = F_1(x, t, r, p)
19
+
20
+ [2] Implicit form where the kinematics and dynamics are combined
21
+ M_2(x, p) x' = F_2(x, t, r, p)
22
+
23
+ [3] Implicit form where the kinematics and dynamics are separate
24
+ M_3(q, p) u' = F_3(q, u, t, r, p)
25
+ q' = G(q, u, t, r, p)
26
+
27
+ where
28
+
29
+ x : states, e.g. [q, u]
30
+ t : time
31
+ r : specified (exogenous) inputs
32
+ p : constants
33
+ q : generalized coordinates
34
+ u : generalized speeds
35
+ F_1 : right hand side of the combined equations in explicit form
36
+ F_2 : right hand side of the combined equations in implicit form
37
+ F_3 : right hand side of the dynamical equations in implicit form
38
+ M_2 : mass matrix of the combined equations in implicit form
39
+ M_3 : mass matrix of the dynamical equations in implicit form
40
+ G : right hand side of the kinematical differential equations
41
+
42
+ Parameters
43
+ ==========
44
+
45
+ coord_states : ordered iterable of functions of time
46
+ This input will either be a collection of the coordinates or states
47
+ of the system depending on whether or not the speeds are also
48
+ given. If speeds are specified this input will be assumed to
49
+ be the coordinates otherwise this input will be assumed to
50
+ be the states.
51
+
52
+ right_hand_side : Matrix
53
+ This variable is the right hand side of the equations of motion in
54
+ any of the forms. The specific form will be assumed depending on
55
+ whether a mass matrix or coordinate derivatives are given.
56
+
57
+ speeds : ordered iterable of functions of time, optional
58
+ This is a collection of the generalized speeds of the system. If
59
+ given it will be assumed that the first argument (coord_states)
60
+ will represent the generalized coordinates of the system.
61
+
62
+ mass_matrix : Matrix, optional
63
+ The matrix of the implicit forms of the equations of motion (forms
64
+ [2] and [3]). The distinction between the forms is determined by
65
+ whether or not the coordinate derivatives are passed in. If
66
+ they are given form [3] will be assumed otherwise form [2] is
67
+ assumed.
68
+
69
+ coordinate_derivatives : Matrix, optional
70
+ The right hand side of the kinematical equations in explicit form.
71
+ If given it will be assumed that the equations of motion are being
72
+ entered in form [3].
73
+
74
+ alg_con : Iterable, optional
75
+ The indexes of the rows in the equations of motion that contain
76
+ algebraic constraints instead of differential equations. If the
77
+ equations are input in form [3], it will be assumed the indexes are
78
+ referencing the mass_matrix/right_hand_side combination and not the
79
+ coordinate_derivatives.
80
+
81
+ output_eqns : Dictionary, optional
82
+ Any output equations that are desired to be tracked are stored in a
83
+ dictionary where the key corresponds to the name given for the
84
+ specific equation and the value is the equation itself in symbolic
85
+ form
86
+
87
+ coord_idxs : Iterable, optional
88
+ If coord_states corresponds to the states rather than the
89
+ coordinates this variable will tell SymbolicSystem which indexes of
90
+ the states correspond to generalized coordinates.
91
+
92
+ speed_idxs : Iterable, optional
93
+ If coord_states corresponds to the states rather than the
94
+ coordinates this variable will tell SymbolicSystem which indexes of
95
+ the states correspond to generalized speeds.
96
+
97
+ bodies : iterable of Body/Rigidbody objects, optional
98
+ Iterable containing the bodies of the system
99
+
100
+ loads : iterable of load instances (described below), optional
101
+ Iterable containing the loads of the system where forces are given
102
+ by (point of application, force vector) and torques are given by
103
+ (reference frame acting upon, torque vector). Ex [(point, force),
104
+ (ref_frame, torque)]
105
+
106
+ Attributes
107
+ ==========
108
+
109
+ coordinates : Matrix, shape(n, 1)
110
+ This is a matrix containing the generalized coordinates of the system
111
+
112
+ speeds : Matrix, shape(m, 1)
113
+ This is a matrix containing the generalized speeds of the system
114
+
115
+ states : Matrix, shape(o, 1)
116
+ This is a matrix containing the state variables of the system
117
+
118
+ alg_con : List
119
+ This list contains the indices of the algebraic constraints in the
120
+ combined equations of motion. The presence of these constraints
121
+ requires that a DAE solver be used instead of an ODE solver.
122
+ If the system is given in form [3] the alg_con variable will be
123
+ adjusted such that it is a representation of the combined kinematics
124
+ and dynamics thus make sure it always matches the mass matrix
125
+ entered.
126
+
127
+ dyn_implicit_mat : Matrix, shape(m, m)
128
+ This is the M matrix in form [3] of the equations of motion (the mass
129
+ matrix or generalized inertia matrix of the dynamical equations of
130
+ motion in implicit form).
131
+
132
+ dyn_implicit_rhs : Matrix, shape(m, 1)
133
+ This is the F vector in form [3] of the equations of motion (the right
134
+ hand side of the dynamical equations of motion in implicit form).
135
+
136
+ comb_implicit_mat : Matrix, shape(o, o)
137
+ This is the M matrix in form [2] of the equations of motion.
138
+ This matrix contains a block diagonal structure where the top
139
+ left block (the first rows) represent the matrix in the
140
+ implicit form of the kinematical equations and the bottom right
141
+ block (the last rows) represent the matrix in the implicit form
142
+ of the dynamical equations.
143
+
144
+ comb_implicit_rhs : Matrix, shape(o, 1)
145
+ This is the F vector in form [2] of the equations of motion. The top
146
+ part of the vector represents the right hand side of the implicit form
147
+ of the kinemaical equations and the bottom of the vector represents the
148
+ right hand side of the implicit form of the dynamical equations of
149
+ motion.
150
+
151
+ comb_explicit_rhs : Matrix, shape(o, 1)
152
+ This vector represents the right hand side of the combined equations of
153
+ motion in explicit form (form [1] from above).
154
+
155
+ kin_explicit_rhs : Matrix, shape(m, 1)
156
+ This is the right hand side of the explicit form of the kinematical
157
+ equations of motion as can be seen in form [3] (the G matrix).
158
+
159
+ output_eqns : Dictionary
160
+ If output equations were given they are stored in a dictionary where
161
+ the key corresponds to the name given for the specific equation and
162
+ the value is the equation itself in symbolic form
163
+
164
+ bodies : Tuple
165
+ If the bodies in the system were given they are stored in a tuple for
166
+ future access
167
+
168
+ loads : Tuple
169
+ If the loads in the system were given they are stored in a tuple for
170
+ future access. This includes forces and torques where forces are given
171
+ by (point of application, force vector) and torques are given by
172
+ (reference frame acted upon, torque vector).
173
+
174
+ Example
175
+ =======
176
+
177
+ As a simple example, the dynamics of a simple pendulum will be input into a
178
+ SymbolicSystem object manually. First some imports will be needed and then
179
+ symbols will be set up for the length of the pendulum (l), mass at the end
180
+ of the pendulum (m), and a constant for gravity (g). ::
181
+
182
+ >>> from sympy import Matrix, sin, symbols
183
+ >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem
184
+ >>> l, m, g = symbols('l m g')
185
+
186
+ The system will be defined by an angle of theta from the vertical and a
187
+ generalized speed of omega will be used where omega = theta_dot. ::
188
+
189
+ >>> theta, omega = dynamicsymbols('theta omega')
190
+
191
+ Now the equations of motion are ready to be formed and passed to the
192
+ SymbolicSystem object. ::
193
+
194
+ >>> kin_explicit_rhs = Matrix([omega])
195
+ >>> dyn_implicit_mat = Matrix([l**2 * m])
196
+ >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)])
197
+ >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega],
198
+ ... dyn_implicit_mat)
199
+
200
+ Notes
201
+ =====
202
+
203
+ m : number of generalized speeds
204
+ n : number of generalized coordinates
205
+ o : number of states
206
+
207
+ """
208
+
209
+ def __init__(self, coord_states, right_hand_side, speeds=None,
210
+ mass_matrix=None, coordinate_derivatives=None, alg_con=None,
211
+ output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None,
212
+ loads=None):
213
+ """Initializes a SymbolicSystem object"""
214
+
215
+ # Extract information on speeds, coordinates and states
216
+ if speeds is None:
217
+ self._states = Matrix(coord_states)
218
+
219
+ if coord_idxs is None:
220
+ self._coordinates = None
221
+ else:
222
+ coords = [coord_states[i] for i in coord_idxs]
223
+ self._coordinates = Matrix(coords)
224
+
225
+ if speed_idxs is None:
226
+ self._speeds = None
227
+ else:
228
+ speeds_inter = [coord_states[i] for i in speed_idxs]
229
+ self._speeds = Matrix(speeds_inter)
230
+ else:
231
+ self._coordinates = Matrix(coord_states)
232
+ self._speeds = Matrix(speeds)
233
+ self._states = self._coordinates.col_join(self._speeds)
234
+
235
+ # Extract equations of motion form
236
+ if coordinate_derivatives is not None:
237
+ self._kin_explicit_rhs = coordinate_derivatives
238
+ self._dyn_implicit_rhs = right_hand_side
239
+ self._dyn_implicit_mat = mass_matrix
240
+ self._comb_implicit_rhs = None
241
+ self._comb_implicit_mat = None
242
+ self._comb_explicit_rhs = None
243
+ elif mass_matrix is not None:
244
+ self._kin_explicit_rhs = None
245
+ self._dyn_implicit_rhs = None
246
+ self._dyn_implicit_mat = None
247
+ self._comb_implicit_rhs = right_hand_side
248
+ self._comb_implicit_mat = mass_matrix
249
+ self._comb_explicit_rhs = None
250
+ else:
251
+ self._kin_explicit_rhs = None
252
+ self._dyn_implicit_rhs = None
253
+ self._dyn_implicit_mat = None
254
+ self._comb_implicit_rhs = None
255
+ self._comb_implicit_mat = None
256
+ self._comb_explicit_rhs = right_hand_side
257
+
258
+ # Set the remainder of the inputs as instance attributes
259
+ if alg_con is not None and coordinate_derivatives is not None:
260
+ alg_con = [i + len(coordinate_derivatives) for i in alg_con]
261
+ self._alg_con = alg_con
262
+ self.output_eqns = output_eqns
263
+
264
+ # Change the body and loads iterables to tuples if they are not tuples
265
+ # already
266
+ if not isinstance(bodies, tuple) and bodies is not None:
267
+ bodies = tuple(bodies)
268
+ if not isinstance(loads, tuple) and loads is not None:
269
+ loads = tuple(loads)
270
+ self._bodies = bodies
271
+ self._loads = loads
272
+
273
+ @property
274
+ def coordinates(self):
275
+ """Returns the column matrix of the generalized coordinates"""
276
+ if self._coordinates is None:
277
+ raise AttributeError("The coordinates were not specified.")
278
+ else:
279
+ return self._coordinates
280
+
281
+ @property
282
+ def speeds(self):
283
+ """Returns the column matrix of generalized speeds"""
284
+ if self._speeds is None:
285
+ raise AttributeError("The speeds were not specified.")
286
+ else:
287
+ return self._speeds
288
+
289
+ @property
290
+ def states(self):
291
+ """Returns the column matrix of the state variables"""
292
+ return self._states
293
+
294
+ @property
295
+ def alg_con(self):
296
+ """Returns a list with the indices of the rows containing algebraic
297
+ constraints in the combined form of the equations of motion"""
298
+ return self._alg_con
299
+
300
+ @property
301
+ def dyn_implicit_mat(self):
302
+ """Returns the matrix, M, corresponding to the dynamic equations in
303
+ implicit form, M x' = F, where the kinematical equations are not
304
+ included"""
305
+ if self._dyn_implicit_mat is None:
306
+ raise AttributeError("dyn_implicit_mat is not specified for "
307
+ "equations of motion form [1] or [2].")
308
+ else:
309
+ return self._dyn_implicit_mat
310
+
311
+ @property
312
+ def dyn_implicit_rhs(self):
313
+ """Returns the column matrix, F, corresponding to the dynamic equations
314
+ in implicit form, M x' = F, where the kinematical equations are not
315
+ included"""
316
+ if self._dyn_implicit_rhs is None:
317
+ raise AttributeError("dyn_implicit_rhs is not specified for "
318
+ "equations of motion form [1] or [2].")
319
+ else:
320
+ return self._dyn_implicit_rhs
321
+
322
+ @property
323
+ def comb_implicit_mat(self):
324
+ """Returns the matrix, M, corresponding to the equations of motion in
325
+ implicit form (form [2]), M x' = F, where the kinematical equations are
326
+ included"""
327
+ if self._comb_implicit_mat is None:
328
+ if self._dyn_implicit_mat is not None:
329
+ num_kin_eqns = len(self._kin_explicit_rhs)
330
+ num_dyn_eqns = len(self._dyn_implicit_rhs)
331
+ zeros1 = zeros(num_kin_eqns, num_dyn_eqns)
332
+ zeros2 = zeros(num_dyn_eqns, num_kin_eqns)
333
+ inter1 = eye(num_kin_eqns).row_join(zeros1)
334
+ inter2 = zeros2.row_join(self._dyn_implicit_mat)
335
+ self._comb_implicit_mat = inter1.col_join(inter2)
336
+ return self._comb_implicit_mat
337
+ else:
338
+ raise AttributeError("comb_implicit_mat is not specified for "
339
+ "equations of motion form [1].")
340
+ else:
341
+ return self._comb_implicit_mat
342
+
343
+ @property
344
+ def comb_implicit_rhs(self):
345
+ """Returns the column matrix, F, corresponding to the equations of
346
+ motion in implicit form (form [2]), M x' = F, where the kinematical
347
+ equations are included"""
348
+ if self._comb_implicit_rhs is None:
349
+ if self._dyn_implicit_rhs is not None:
350
+ kin_inter = self._kin_explicit_rhs
351
+ dyn_inter = self._dyn_implicit_rhs
352
+ self._comb_implicit_rhs = kin_inter.col_join(dyn_inter)
353
+ return self._comb_implicit_rhs
354
+ else:
355
+ raise AttributeError("comb_implicit_mat is not specified for "
356
+ "equations of motion in form [1].")
357
+ else:
358
+ return self._comb_implicit_rhs
359
+
360
+ def compute_explicit_form(self):
361
+ """If the explicit right hand side of the combined equations of motion
362
+ is to provided upon initialization, this method will calculate it. This
363
+ calculation can potentially take awhile to compute."""
364
+ if self._comb_explicit_rhs is not None:
365
+ raise AttributeError("comb_explicit_rhs is already formed.")
366
+
367
+ inter1 = getattr(self, 'kin_explicit_rhs', None)
368
+ if inter1 is not None:
369
+ inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs)
370
+ out = inter1.col_join(inter2)
371
+ else:
372
+ out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs)
373
+
374
+ self._comb_explicit_rhs = out
375
+
376
+ @property
377
+ def comb_explicit_rhs(self):
378
+ """Returns the right hand side of the equations of motion in explicit
379
+ form, x' = F, where the kinematical equations are included"""
380
+ if self._comb_explicit_rhs is None:
381
+ raise AttributeError("Please run .combute_explicit_form before "
382
+ "attempting to access comb_explicit_rhs.")
383
+ else:
384
+ return self._comb_explicit_rhs
385
+
386
+ @property
387
+ def kin_explicit_rhs(self):
388
+ """Returns the right hand side of the kinematical equations in explicit
389
+ form, q' = G"""
390
+ if self._kin_explicit_rhs is None:
391
+ raise AttributeError("kin_explicit_rhs is not specified for "
392
+ "equations of motion form [1] or [2].")
393
+ else:
394
+ return self._kin_explicit_rhs
395
+
396
+ def dynamic_symbols(self):
397
+ """Returns a column matrix containing all of the symbols in the system
398
+ that depend on time"""
399
+ # Create a list of all of the expressions in the equations of motion
400
+ if self._comb_explicit_rhs is None:
401
+ eom_expressions = (self.comb_implicit_mat[:] +
402
+ self.comb_implicit_rhs[:])
403
+ else:
404
+ eom_expressions = (self._comb_explicit_rhs[:])
405
+
406
+ functions_of_time = set()
407
+ for expr in eom_expressions:
408
+ functions_of_time = functions_of_time.union(
409
+ find_dynamicsymbols(expr))
410
+ functions_of_time = functions_of_time.union(self._states)
411
+
412
+ return tuple(functions_of_time)
413
+
414
+ def constant_symbols(self):
415
+ """Returns a column matrix containing all of the symbols in the system
416
+ that do not depend on time"""
417
+ # Create a list of all of the expressions in the equations of motion
418
+ if self._comb_explicit_rhs is None:
419
+ eom_expressions = (self.comb_implicit_mat[:] +
420
+ self.comb_implicit_rhs[:])
421
+ else:
422
+ eom_expressions = (self._comb_explicit_rhs[:])
423
+
424
+ constants = set()
425
+ for expr in eom_expressions:
426
+ constants = constants.union(expr.free_symbols)
427
+ constants.remove(dynamicsymbols._t)
428
+
429
+ return tuple(constants)
430
+
431
+ @property
432
+ def bodies(self):
433
+ """Returns the bodies in the system"""
434
+ if self._bodies is None:
435
+ raise AttributeError("bodies were not specified for the system.")
436
+ else:
437
+ return self._bodies
438
+
439
+ @property
440
+ def loads(self):
441
+ """Returns the loads in the system"""
442
+ if self._loads is None:
443
+ raise AttributeError("loads were not specified for the system.")
444
+ else:
445
+ return self._loads
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (197 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc ADDED
Binary file (39.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc ADDED
Binary file (8.35 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc ADDED
Binary file (5.45 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_method.cpython-310.pyc ADDED
Binary file (563 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_body.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import (Symbol, symbols, sin, cos, Matrix, zeros,
2
+ _simplify_matrix)
3
+ from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols, Dyadic
4
+ from sympy.physics.mechanics import inertia, Body
5
+ from sympy.testing.pytest import raises
6
+
7
+
8
+ def test_default():
9
+ body = Body('body')
10
+ assert body.name == 'body'
11
+ assert body.loads == []
12
+ point = Point('body_masscenter')
13
+ point.set_vel(body.frame, 0)
14
+ com = body.masscenter
15
+ frame = body.frame
16
+ assert com.vel(frame) == point.vel(frame)
17
+ assert body.mass == Symbol('body_mass')
18
+ ixx, iyy, izz = symbols('body_ixx body_iyy body_izz')
19
+ ixy, iyz, izx = symbols('body_ixy body_iyz body_izx')
20
+ assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx),
21
+ body.masscenter)
22
+
23
+
24
+ def test_custom_rigid_body():
25
+ # Body with RigidBody.
26
+ rigidbody_masscenter = Point('rigidbody_masscenter')
27
+ rigidbody_mass = Symbol('rigidbody_mass')
28
+ rigidbody_frame = ReferenceFrame('rigidbody_frame')
29
+ body_inertia = inertia(rigidbody_frame, 1, 0, 0)
30
+ rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
31
+ rigidbody_frame, body_inertia)
32
+ com = rigid_body.masscenter
33
+ frame = rigid_body.frame
34
+ rigidbody_masscenter.set_vel(rigidbody_frame, 0)
35
+ assert com.vel(frame) == rigidbody_masscenter.vel(frame)
36
+ assert com.pos_from(com) == rigidbody_masscenter.pos_from(com)
37
+
38
+ assert rigid_body.mass == rigidbody_mass
39
+ assert rigid_body.inertia == (body_inertia, rigidbody_masscenter)
40
+
41
+ assert rigid_body.is_rigidbody
42
+
43
+ assert hasattr(rigid_body, 'masscenter')
44
+ assert hasattr(rigid_body, 'mass')
45
+ assert hasattr(rigid_body, 'frame')
46
+ assert hasattr(rigid_body, 'inertia')
47
+
48
+
49
+ def test_particle_body():
50
+ # Body with Particle
51
+ particle_masscenter = Point('particle_masscenter')
52
+ particle_mass = Symbol('particle_mass')
53
+ particle_frame = ReferenceFrame('particle_frame')
54
+ particle_body = Body('particle_body', particle_masscenter, particle_mass,
55
+ particle_frame)
56
+ com = particle_body.masscenter
57
+ frame = particle_body.frame
58
+ particle_masscenter.set_vel(particle_frame, 0)
59
+ assert com.vel(frame) == particle_masscenter.vel(frame)
60
+ assert com.pos_from(com) == particle_masscenter.pos_from(com)
61
+
62
+ assert particle_body.mass == particle_mass
63
+ assert not hasattr(particle_body, "_inertia")
64
+ assert hasattr(particle_body, 'frame')
65
+ assert hasattr(particle_body, 'masscenter')
66
+ assert hasattr(particle_body, 'mass')
67
+ assert particle_body.inertia == (Dyadic(0), particle_body.masscenter)
68
+ assert particle_body.central_inertia == Dyadic(0)
69
+ assert not particle_body.is_rigidbody
70
+
71
+ particle_body.central_inertia = inertia(particle_frame, 1, 1, 1)
72
+ assert particle_body.central_inertia == inertia(particle_frame, 1, 1, 1)
73
+ assert particle_body.is_rigidbody
74
+
75
+ particle_body = Body('particle_body', mass=particle_mass)
76
+ assert not particle_body.is_rigidbody
77
+ point = particle_body.masscenter.locatenew('point', particle_body.x)
78
+ point_inertia = particle_mass * inertia(particle_body.frame, 0, 1, 1)
79
+ particle_body.inertia = (point_inertia, point)
80
+ assert particle_body.inertia == (point_inertia, point)
81
+ assert particle_body.central_inertia == Dyadic(0)
82
+ assert particle_body.is_rigidbody
83
+
84
+
85
+ def test_particle_body_add_force():
86
+ # Body with Particle
87
+ particle_masscenter = Point('particle_masscenter')
88
+ particle_mass = Symbol('particle_mass')
89
+ particle_frame = ReferenceFrame('particle_frame')
90
+ particle_body = Body('particle_body', particle_masscenter, particle_mass,
91
+ particle_frame)
92
+
93
+ a = Symbol('a')
94
+ force_vector = a * particle_body.frame.x
95
+ particle_body.apply_force(force_vector, particle_body.masscenter)
96
+ assert len(particle_body.loads) == 1
97
+ point = particle_body.masscenter.locatenew(
98
+ particle_body._name + '_point0', 0)
99
+ point.set_vel(particle_body.frame, 0)
100
+ force_point = particle_body.loads[0][0]
101
+
102
+ frame = particle_body.frame
103
+ assert force_point.vel(frame) == point.vel(frame)
104
+ assert force_point.pos_from(force_point) == point.pos_from(force_point)
105
+
106
+ assert particle_body.loads[0][1] == force_vector
107
+
108
+
109
+ def test_body_add_force():
110
+ # Body with RigidBody.
111
+ rigidbody_masscenter = Point('rigidbody_masscenter')
112
+ rigidbody_mass = Symbol('rigidbody_mass')
113
+ rigidbody_frame = ReferenceFrame('rigidbody_frame')
114
+ body_inertia = inertia(rigidbody_frame, 1, 0, 0)
115
+ rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
116
+ rigidbody_frame, body_inertia)
117
+
118
+ l = Symbol('l')
119
+ Fa = Symbol('Fa')
120
+ point = rigid_body.masscenter.locatenew(
121
+ 'rigidbody_body_point0',
122
+ l * rigid_body.frame.x)
123
+ point.set_vel(rigid_body.frame, 0)
124
+ force_vector = Fa * rigid_body.frame.z
125
+ # apply_force with point
126
+ rigid_body.apply_force(force_vector, point)
127
+ assert len(rigid_body.loads) == 1
128
+ force_point = rigid_body.loads[0][0]
129
+ frame = rigid_body.frame
130
+ assert force_point.vel(frame) == point.vel(frame)
131
+ assert force_point.pos_from(force_point) == point.pos_from(force_point)
132
+ assert rigid_body.loads[0][1] == force_vector
133
+ # apply_force without point
134
+ rigid_body.apply_force(force_vector)
135
+ assert len(rigid_body.loads) == 2
136
+ assert rigid_body.loads[1][1] == force_vector
137
+ # passing something else than point
138
+ raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0))
139
+ raises(TypeError, lambda: rigid_body.apply_force(0))
140
+
141
+ def test_body_add_torque():
142
+ body = Body('body')
143
+ torque_vector = body.frame.x
144
+ body.apply_torque(torque_vector)
145
+
146
+ assert len(body.loads) == 1
147
+ assert body.loads[0] == (body.frame, torque_vector)
148
+ raises(TypeError, lambda: body.apply_torque(0))
149
+
150
+ def test_body_masscenter_vel():
151
+ A = Body('A')
152
+ N = ReferenceFrame('N')
153
+ B = Body('B', frame=N)
154
+ A.masscenter.set_vel(N, N.z)
155
+ assert A.masscenter_vel(B) == N.z
156
+ assert A.masscenter_vel(N) == N.z
157
+
158
+ def test_body_ang_vel():
159
+ A = Body('A')
160
+ N = ReferenceFrame('N')
161
+ B = Body('B', frame=N)
162
+ A.frame.set_ang_vel(N, N.y)
163
+ assert A.ang_vel_in(B) == N.y
164
+ assert B.ang_vel_in(A) == -N.y
165
+ assert A.ang_vel_in(N) == N.y
166
+
167
+ def test_body_dcm():
168
+ A = Body('A')
169
+ B = Body('B')
170
+ A.frame.orient_axis(B.frame, B.frame.z, 10)
171
+ assert A.dcm(B) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
172
+ assert A.dcm(B.frame) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
173
+
174
+ def test_body_axis():
175
+ N = ReferenceFrame('N')
176
+ B = Body('B', frame=N)
177
+ assert B.x == N.x
178
+ assert B.y == N.y
179
+ assert B.z == N.z
180
+
181
+ def test_apply_force_multiple_one_point():
182
+ a, b = symbols('a b')
183
+ P = Point('P')
184
+ B = Body('B')
185
+ f1 = a*B.x
186
+ f2 = b*B.y
187
+ B.apply_force(f1, P)
188
+ assert B.loads == [(P, f1)]
189
+ B.apply_force(f2, P)
190
+ assert B.loads == [(P, f1+f2)]
191
+
192
+ def test_apply_force():
193
+ f, g = symbols('f g')
194
+ q, x, v1, v2 = dynamicsymbols('q x v1 v2')
195
+ P1 = Point('P1')
196
+ P2 = Point('P2')
197
+ B1 = Body('B1')
198
+ B2 = Body('B2')
199
+ N = ReferenceFrame('N')
200
+
201
+ P1.set_vel(B1.frame, v1*B1.x)
202
+ P2.set_vel(B2.frame, v2*B2.x)
203
+ force = f*q*N.z # time varying force
204
+
205
+ B1.apply_force(force, P1, B2, P2) #applying equal and opposite force on moving points
206
+ assert B1.loads == [(P1, force)]
207
+ assert B2.loads == [(P2, -force)]
208
+
209
+ g1 = B1.mass*g*N.y
210
+ g2 = B2.mass*g*N.y
211
+
212
+ B1.apply_force(g1) #applying gravity on B1 masscenter
213
+ B2.apply_force(g2) #applying gravity on B2 masscenter
214
+
215
+ assert B1.loads == [(P1,force), (B1.masscenter, g1)]
216
+ assert B2.loads == [(P2, -force), (B2.masscenter, g2)]
217
+
218
+ force2 = x*N.x
219
+
220
+ B1.apply_force(force2, reaction_body=B2) #Applying time varying force on masscenter
221
+
222
+ assert B1.loads == [(P1, force), (B1.masscenter, force2+g1)]
223
+ assert B2.loads == [(P2, -force), (B2.masscenter, -force2+g2)]
224
+
225
+ def test_apply_torque():
226
+ t = symbols('t')
227
+ q = dynamicsymbols('q')
228
+ B1 = Body('B1')
229
+ B2 = Body('B2')
230
+ N = ReferenceFrame('N')
231
+ torque = t*q*N.x
232
+
233
+ B1.apply_torque(torque, B2) #Applying equal and opposite torque
234
+ assert B1.loads == [(B1.frame, torque)]
235
+ assert B2.loads == [(B2.frame, -torque)]
236
+
237
+ torque2 = t*N.y
238
+ B1.apply_torque(torque2)
239
+ assert B1.loads == [(B1.frame, torque+torque2)]
240
+
241
+ def test_clear_load():
242
+ a = symbols('a')
243
+ P = Point('P')
244
+ B = Body('B')
245
+ force = a*B.z
246
+ B.apply_force(force, P)
247
+ assert B.loads == [(P, force)]
248
+ B.clear_loads()
249
+ assert B.loads == []
250
+
251
+ def test_remove_load():
252
+ P1 = Point('P1')
253
+ P2 = Point('P2')
254
+ B = Body('B')
255
+ f1 = B.x
256
+ f2 = B.y
257
+ B.apply_force(f1, P1)
258
+ B.apply_force(f2, P2)
259
+ assert B.loads == [(P1, f1), (P2, f2)]
260
+ B.remove_load(P2)
261
+ assert B.loads == [(P1, f1)]
262
+ B.apply_torque(f1.cross(f2))
263
+ assert B.loads == [(P1, f1), (B.frame, f1.cross(f2))]
264
+ B.remove_load()
265
+ assert B.loads == [(P1, f1)]
266
+
267
+ def test_apply_loads_on_multi_degree_freedom_holonomic_system():
268
+ """Example based on: https://pydy.readthedocs.io/en/latest/examples/multidof-holonomic.html"""
269
+ W = Body('W') #Wall
270
+ B = Body('B') #Block
271
+ P = Body('P') #Pendulum
272
+ b = Body('b') #bob
273
+ q1, q2 = dynamicsymbols('q1 q2') #generalized coordinates
274
+ k, c, g, kT = symbols('k c g kT') #constants
275
+ F, T = dynamicsymbols('F T') #Specified forces
276
+
277
+ #Applying forces
278
+ B.apply_force(F*W.x)
279
+ W.apply_force(k*q1*W.x, reaction_body=B) #Spring force
280
+ W.apply_force(c*q1.diff()*W.x, reaction_body=B) #dampner
281
+ P.apply_force(P.mass*g*W.y)
282
+ b.apply_force(b.mass*g*W.y)
283
+
284
+ #Applying torques
285
+ P.apply_torque(kT*q2*W.z, reaction_body=b)
286
+ P.apply_torque(T*W.z)
287
+
288
+ assert B.loads == [(B.masscenter, (F - k*q1 - c*q1.diff())*W.x)]
289
+ assert P.loads == [(P.masscenter, P.mass*g*W.y), (P.frame, (T + kT*q2)*W.z)]
290
+ assert b.loads == [(b.masscenter, b.mass*g*W.y), (b.frame, -kT*q2*W.z)]
291
+ assert W.loads == [(W.masscenter, (c*q1.diff() + k*q1)*W.x)]
292
+
293
+
294
+ def test_parallel_axis():
295
+ N = ReferenceFrame('N')
296
+ m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
297
+ Io = inertia(N, Ix, Iy, Iz)
298
+ # Test RigidBody
299
+ o = Point('o')
300
+ p = o.locatenew('p', a * N.x + b * N.y)
301
+ R = Body('R', masscenter=o, frame=N, mass=m, central_inertia=Io)
302
+ Ip = R.parallel_axis(p)
303
+ Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2,
304
+ Iz + m * (a**2 + b**2), ixy=-m * a * b)
305
+ assert Ip == Ip_expected
306
+ # Reference frame from which the parallel axis is viewed should not matter
307
+ A = ReferenceFrame('A')
308
+ A.orient_axis(N, N.z, 1)
309
+ assert _simplify_matrix(
310
+ (R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3)
311
+ # Test Particle
312
+ o = Point('o')
313
+ p = o.locatenew('p', a * N.x + b * N.y)
314
+ P = Body('P', masscenter=o, mass=m, frame=N)
315
+ Ip = P.parallel_axis(p, N)
316
+ Ip_expected = inertia(N, m * b ** 2, m * a ** 2, m * (a ** 2 + b ** 2),
317
+ ixy=-m * a * b)
318
+ assert not P.is_rigidbody
319
+ assert Ip == Ip_expected
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import sin, cos, tan, pi, symbols, Matrix, S, Function
2
+ from sympy.physics.mechanics import (Particle, Point, ReferenceFrame,
3
+ RigidBody)
4
+ from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
5
+ inertia, inertia_of_point_mass,
6
+ kinetic_energy, linear_momentum,
7
+ outer, potential_energy, msubs,
8
+ find_dynamicsymbols, Lagrangian)
9
+
10
+ from sympy.physics.mechanics.functions import (gravity, center_of_mass,
11
+ _validate_coordinates)
12
+ from sympy.testing.pytest import raises
13
+
14
+
15
+ q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
16
+ N = ReferenceFrame('N')
17
+ A = N.orientnew('A', 'Axis', [q1, N.z])
18
+ B = A.orientnew('B', 'Axis', [q2, A.x])
19
+ C = B.orientnew('C', 'Axis', [q3, B.y])
20
+
21
+
22
+ def test_inertia():
23
+ N = ReferenceFrame('N')
24
+ ixx, iyy, izz = symbols('ixx iyy izz')
25
+ ixy, iyz, izx = symbols('ixy iyz izx')
26
+ assert inertia(N, ixx, iyy, izz) == (ixx * (N.x | N.x) + iyy *
27
+ (N.y | N.y) + izz * (N.z | N.z))
28
+ assert inertia(N, 0, 0, 0) == 0 * (N.x | N.x)
29
+ raises(TypeError, lambda: inertia(0, 0, 0, 0))
30
+ assert inertia(N, ixx, iyy, izz, ixy, iyz, izx) == (ixx * (N.x | N.x) +
31
+ ixy * (N.x | N.y) + izx * (N.x | N.z) + ixy * (N.y | N.x) + iyy *
32
+ (N.y | N.y) + iyz * (N.y | N.z) + izx * (N.z | N.x) + iyz * (N.z |
33
+ N.y) + izz * (N.z | N.z))
34
+
35
+
36
+ def test_inertia_of_point_mass():
37
+ r, s, t, m = symbols('r s t m')
38
+ N = ReferenceFrame('N')
39
+
40
+ px = r * N.x
41
+ I = inertia_of_point_mass(m, px, N)
42
+ assert I == m * r**2 * (N.y | N.y) + m * r**2 * (N.z | N.z)
43
+
44
+ py = s * N.y
45
+ I = inertia_of_point_mass(m, py, N)
46
+ assert I == m * s**2 * (N.x | N.x) + m * s**2 * (N.z | N.z)
47
+
48
+ pz = t * N.z
49
+ I = inertia_of_point_mass(m, pz, N)
50
+ assert I == m * t**2 * (N.x | N.x) + m * t**2 * (N.y | N.y)
51
+
52
+ p = px + py + pz
53
+ I = inertia_of_point_mass(m, p, N)
54
+ assert I == (m * (s**2 + t**2) * (N.x | N.x) -
55
+ m * r * s * (N.x | N.y) -
56
+ m * r * t * (N.x | N.z) -
57
+ m * r * s * (N.y | N.x) +
58
+ m * (r**2 + t**2) * (N.y | N.y) -
59
+ m * s * t * (N.y | N.z) -
60
+ m * r * t * (N.z | N.x) -
61
+ m * s * t * (N.z | N.y) +
62
+ m * (r**2 + s**2) * (N.z | N.z))
63
+
64
+
65
+ def test_linear_momentum():
66
+ N = ReferenceFrame('N')
67
+ Ac = Point('Ac')
68
+ Ac.set_vel(N, 25 * N.y)
69
+ I = outer(N.x, N.x)
70
+ A = RigidBody('A', Ac, N, 20, (I, Ac))
71
+ P = Point('P')
72
+ Pa = Particle('Pa', P, 1)
73
+ Pa.point.set_vel(N, 10 * N.x)
74
+ raises(TypeError, lambda: linear_momentum(A, A, Pa))
75
+ raises(TypeError, lambda: linear_momentum(N, N, Pa))
76
+ assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y
77
+
78
+
79
+ def test_angular_momentum_and_linear_momentum():
80
+ """A rod with length 2l, centroidal inertia I, and mass M along with a
81
+ particle of mass m fixed to the end of the rod rotate with an angular rate
82
+ of omega about point O which is fixed to the non-particle end of the rod.
83
+ The rod's reference frame is A and the inertial frame is N."""
84
+ m, M, l, I = symbols('m, M, l, I')
85
+ omega = dynamicsymbols('omega')
86
+ N = ReferenceFrame('N')
87
+ a = ReferenceFrame('a')
88
+ O = Point('O')
89
+ Ac = O.locatenew('Ac', l * N.x)
90
+ P = Ac.locatenew('P', l * N.x)
91
+ O.set_vel(N, 0 * N.x)
92
+ a.set_ang_vel(N, omega * N.z)
93
+ Ac.v2pt_theory(O, N, a)
94
+ P.v2pt_theory(O, N, a)
95
+ Pa = Particle('Pa', P, m)
96
+ A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac))
97
+ expected = 2 * m * omega * l * N.y + M * l * omega * N.y
98
+ assert linear_momentum(N, A, Pa) == expected
99
+ raises(TypeError, lambda: angular_momentum(N, N, A, Pa))
100
+ raises(TypeError, lambda: angular_momentum(O, O, A, Pa))
101
+ raises(TypeError, lambda: angular_momentum(O, N, O, Pa))
102
+ expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z
103
+ assert angular_momentum(O, N, A, Pa) == expected
104
+
105
+
106
+ def test_kinetic_energy():
107
+ m, M, l1 = symbols('m M l1')
108
+ omega = dynamicsymbols('omega')
109
+ N = ReferenceFrame('N')
110
+ O = Point('O')
111
+ O.set_vel(N, 0 * N.x)
112
+ Ac = O.locatenew('Ac', l1 * N.x)
113
+ P = Ac.locatenew('P', l1 * N.x)
114
+ a = ReferenceFrame('a')
115
+ a.set_ang_vel(N, omega * N.z)
116
+ Ac.v2pt_theory(O, N, a)
117
+ P.v2pt_theory(O, N, a)
118
+ Pa = Particle('Pa', P, m)
119
+ I = outer(N.z, N.z)
120
+ A = RigidBody('A', Ac, a, M, (I, Ac))
121
+ raises(TypeError, lambda: kinetic_energy(Pa, Pa, A))
122
+ raises(TypeError, lambda: kinetic_energy(N, N, A))
123
+ assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2
124
+ + 2*l1**2*m*omega**2 + omega**2/2)).expand()
125
+
126
+
127
+ def test_potential_energy():
128
+ m, M, l1, g, h, H = symbols('m M l1 g h H')
129
+ omega = dynamicsymbols('omega')
130
+ N = ReferenceFrame('N')
131
+ O = Point('O')
132
+ O.set_vel(N, 0 * N.x)
133
+ Ac = O.locatenew('Ac', l1 * N.x)
134
+ P = Ac.locatenew('P', l1 * N.x)
135
+ a = ReferenceFrame('a')
136
+ a.set_ang_vel(N, omega * N.z)
137
+ Ac.v2pt_theory(O, N, a)
138
+ P.v2pt_theory(O, N, a)
139
+ Pa = Particle('Pa', P, m)
140
+ I = outer(N.z, N.z)
141
+ A = RigidBody('A', Ac, a, M, (I, Ac))
142
+ Pa.potential_energy = m * g * h
143
+ A.potential_energy = M * g * H
144
+ assert potential_energy(A, Pa) == m * g * h + M * g * H
145
+
146
+
147
+ def test_Lagrangian():
148
+ M, m, g, h = symbols('M m g h')
149
+ N = ReferenceFrame('N')
150
+ O = Point('O')
151
+ O.set_vel(N, 0 * N.x)
152
+ P = O.locatenew('P', 1 * N.x)
153
+ P.set_vel(N, 10 * N.x)
154
+ Pa = Particle('Pa', P, 1)
155
+ Ac = O.locatenew('Ac', 2 * N.y)
156
+ Ac.set_vel(N, 5 * N.y)
157
+ a = ReferenceFrame('a')
158
+ a.set_ang_vel(N, 10 * N.z)
159
+ I = outer(N.z, N.z)
160
+ A = RigidBody('A', Ac, a, 20, (I, Ac))
161
+ Pa.potential_energy = m * g * h
162
+ A.potential_energy = M * g * h
163
+ raises(TypeError, lambda: Lagrangian(A, A, Pa))
164
+ raises(TypeError, lambda: Lagrangian(N, N, Pa))
165
+
166
+
167
+ def test_msubs():
168
+ a, b = symbols('a, b')
169
+ x, y, z = dynamicsymbols('x, y, z')
170
+ # Test simple substitution
171
+ expr = Matrix([[a*x + b, x*y.diff() + y],
172
+ [x.diff().diff(), z + sin(z.diff())]])
173
+ sol = Matrix([[a + b, y],
174
+ [x.diff().diff(), 1]])
175
+ sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0}
176
+ assert msubs(expr, sd) == sol
177
+ # Test smart substitution
178
+ expr = cos(x + y)*tan(x + y) + b*x.diff()
179
+ sd = {x: 0, y: pi/2, x.diff(): 1}
180
+ assert msubs(expr, sd, smart=True) == b + 1
181
+ N = ReferenceFrame('N')
182
+ v = x*N.x + y*N.y
183
+ d = x*(N.x|N.x) + y*(N.y|N.y)
184
+ v_sol = 1*N.y
185
+ d_sol = 1*(N.y|N.y)
186
+ sd = {x: 0, y: 1}
187
+ assert msubs(v, sd) == v_sol
188
+ assert msubs(d, sd) == d_sol
189
+
190
+
191
+ def test_find_dynamicsymbols():
192
+ a, b = symbols('a, b')
193
+ x, y, z = dynamicsymbols('x, y, z')
194
+ expr = Matrix([[a*x + b, x*y.diff() + y],
195
+ [x.diff().diff(), z + sin(z.diff())]])
196
+ # Test finding all dynamicsymbols
197
+ sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()}
198
+ assert find_dynamicsymbols(expr) == sol
199
+ # Test finding all but those in sym_list
200
+ exclude_list = [x, y, z]
201
+ sol = {y.diff(), x.diff().diff(), z.diff()}
202
+ assert find_dynamicsymbols(expr, exclude=exclude_list) == sol
203
+ # Test finding all dynamicsymbols in a vector with a given reference frame
204
+ d, e, f = dynamicsymbols('d, e, f')
205
+ A = ReferenceFrame('A')
206
+ v = d * A.x + e * A.y + f * A.z
207
+ sol = {d, e, f}
208
+ assert find_dynamicsymbols(v, reference_frame=A) == sol
209
+ # Test if a ValueError is raised on supplying only a vector as input
210
+ raises(ValueError, lambda: find_dynamicsymbols(v))
211
+
212
+
213
+ def test_gravity():
214
+ N = ReferenceFrame('N')
215
+ m, M, g = symbols('m M g')
216
+ F1, F2 = dynamicsymbols('F1 F2')
217
+ po = Point('po')
218
+ pa = Particle('pa', po, m)
219
+ A = ReferenceFrame('A')
220
+ P = Point('P')
221
+ I = outer(A.x, A.x)
222
+ B = RigidBody('B', P, A, M, (I, P))
223
+ forceList = [(po, F1), (P, F2)]
224
+ forceList.extend(gravity(g*N.y, pa, B))
225
+ l = [(po, F1), (P, F2), (po, g*m*N.y), (P, g*M*N.y)]
226
+
227
+ for i in range(len(l)):
228
+ for j in range(len(l[i])):
229
+ assert forceList[i][j] == l[i][j]
230
+
231
+ # This function tests the center_of_mass() function
232
+ # that was added in PR #14758 to compute the center of
233
+ # mass of a system of bodies.
234
+ def test_center_of_mass():
235
+ a = ReferenceFrame('a')
236
+ m = symbols('m', real=True)
237
+ p1 = Particle('p1', Point('p1_pt'), S.One)
238
+ p2 = Particle('p2', Point('p2_pt'), S(2))
239
+ p3 = Particle('p3', Point('p3_pt'), S(3))
240
+ p4 = Particle('p4', Point('p4_pt'), m)
241
+ b_f = ReferenceFrame('b_f')
242
+ b_cm = Point('b_cm')
243
+ mb = symbols('mb')
244
+ b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
245
+ p2.point.set_pos(p1.point, a.x)
246
+ p3.point.set_pos(p1.point, a.x + a.y)
247
+ p4.point.set_pos(p1.point, a.y)
248
+ b.masscenter.set_pos(p1.point, a.y + a.z)
249
+ point_o=Point('o')
250
+ point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
251
+ expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
252
+ assert point_o.pos_from(p1.point)-expr == 0
253
+
254
+
255
+ def test_validate_coordinates():
256
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4 u1:4')
257
+ s1, s2, s3 = symbols('s1:4')
258
+ # Test normal
259
+ _validate_coordinates([q1, q2, q3], [u1, u2, u3])
260
+ # Test not equal number of coordinates and speeds
261
+ _validate_coordinates([q1, q2])
262
+ _validate_coordinates([q1, q2], [u1])
263
+ _validate_coordinates(speeds=[u1, u2])
264
+ # Test duplicate
265
+ _validate_coordinates([q1, q2, q2], [u1, u2, u3], check_duplicates=False)
266
+ raises(ValueError, lambda: _validate_coordinates(
267
+ [q1, q2, q2], [u1, u2, u3]))
268
+ _validate_coordinates([q1, q2, q3], [u1, u2, u2], check_duplicates=False)
269
+ raises(ValueError, lambda: _validate_coordinates(
270
+ [q1, q2, q3], [u1, u2, u2], check_duplicates=True))
271
+ raises(ValueError, lambda: _validate_coordinates(
272
+ [q1, q2, q3], [q1, u2, u3], check_duplicates=True))
273
+ # Test is_dynamicsymbols
274
+ _validate_coordinates([q1 + q2, q3], is_dynamicsymbols=False)
275
+ raises(ValueError, lambda: _validate_coordinates([q1 + q2, q3]))
276
+ _validate_coordinates([s1, q1, q2], [0, u1, u2], is_dynamicsymbols=False)
277
+ raises(ValueError, lambda: _validate_coordinates(
278
+ [s1, q1, q2], [0, u1, u2], is_dynamicsymbols=True))
279
+ _validate_coordinates([s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=False)
280
+ raises(ValueError, lambda: _validate_coordinates(
281
+ [s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=True))
282
+ # Test normal function
283
+ t = dynamicsymbols._t
284
+ a = symbols('a')
285
+ f1, f2 = symbols('f1:3', cls=Function)
286
+ _validate_coordinates([f1(a), f2(a)], is_dynamicsymbols=False)
287
+ raises(ValueError, lambda: _validate_coordinates([f1(a), f2(a)]))
288
+ raises(ValueError, lambda: _validate_coordinates(speeds=[f1(a), f2(a)]))
289
+ dynamicsymbols._t = a
290
+ _validate_coordinates([f1(a), f2(a)])
291
+ raises(ValueError, lambda: _validate_coordinates([f1(t), f2(t)]))
292
+ dynamicsymbols._t = t
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py ADDED
@@ -0,0 +1,1144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand_mul
2
+ from sympy.core.numbers import pi
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.trigonometric import (cos, sin)
6
+ from sympy.core.backend import Matrix, _simplify_matrix, eye, zeros
7
+ from sympy.core.symbol import symbols
8
+ from sympy.physics.mechanics import (dynamicsymbols, Body, JointsMethod,
9
+ PinJoint, PrismaticJoint, CylindricalJoint,
10
+ PlanarJoint, SphericalJoint, WeldJoint)
11
+ from sympy.physics.mechanics.joint import Joint
12
+ from sympy.physics.vector import Vector, ReferenceFrame, Point
13
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
14
+
15
+
16
+ Vector.simp = True
17
+ t = dynamicsymbols._t # type: ignore
18
+
19
+
20
+ def _generate_body(interframe=False):
21
+ N = ReferenceFrame('N')
22
+ A = ReferenceFrame('A')
23
+ P = Body('P', frame=N)
24
+ C = Body('C', frame=A)
25
+ if interframe:
26
+ Pint, Cint = ReferenceFrame('P_int'), ReferenceFrame('C_int')
27
+ Pint.orient_axis(N, N.x, pi)
28
+ Cint.orient_axis(A, A.y, -pi / 2)
29
+ return N, A, P, C, Pint, Cint
30
+ return N, A, P, C
31
+
32
+
33
+ def test_Joint():
34
+ parent = Body('parent')
35
+ child = Body('child')
36
+ raises(TypeError, lambda: Joint('J', parent, child))
37
+
38
+
39
+ def test_coordinate_generation():
40
+ q, u, qj, uj = dynamicsymbols('q u q_J u_J')
41
+ q0j, q1j, q2j, q3j, u0j, u1j, u2j, u3j = dynamicsymbols('q0:4_J u0:4_J')
42
+ q0, q1, q2, q3, u0, u1, u2, u3 = dynamicsymbols('q0:4 u0:4')
43
+ _, _, P, C = _generate_body()
44
+ # Using PinJoint to access Joint's coordinate generation method
45
+ J = PinJoint('J', P, C)
46
+ # Test single given
47
+ assert J._fill_coordinate_list(q, 1) == Matrix([q])
48
+ assert J._fill_coordinate_list([u], 1) == Matrix([u])
49
+ assert J._fill_coordinate_list([u], 1, offset=2) == Matrix([u])
50
+ # Test None
51
+ assert J._fill_coordinate_list(None, 1) == Matrix([qj])
52
+ assert J._fill_coordinate_list([None], 1) == Matrix([qj])
53
+ assert J._fill_coordinate_list([q0, None, None], 3) == Matrix(
54
+ [q0, q1j, q2j])
55
+ # Test autofill
56
+ assert J._fill_coordinate_list(None, 3) == Matrix([q0j, q1j, q2j])
57
+ assert J._fill_coordinate_list([], 3) == Matrix([q0j, q1j, q2j])
58
+ # Test offset
59
+ assert J._fill_coordinate_list([], 3, offset=1) == Matrix([q1j, q2j, q3j])
60
+ assert J._fill_coordinate_list([q1, None, q3], 3, offset=1) == Matrix(
61
+ [q1, q2j, q3])
62
+ assert J._fill_coordinate_list(None, 2, offset=2) == Matrix([q2j, q3j])
63
+ # Test label
64
+ assert J._fill_coordinate_list(None, 1, 'u') == Matrix([uj])
65
+ assert J._fill_coordinate_list([], 3, 'u') == Matrix([u0j, u1j, u2j])
66
+ # Test single numbering
67
+ assert J._fill_coordinate_list(None, 1, number_single=True) == Matrix([q0j])
68
+ assert J._fill_coordinate_list([], 1, 'u', 2, True) == Matrix([u2j])
69
+ assert J._fill_coordinate_list([], 3, 'q') == Matrix([q0j, q1j, q2j])
70
+ # Test invalid number of coordinates supplied
71
+ raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 1))
72
+ raises(ValueError, lambda: J._fill_coordinate_list([u0, u1, None], 2, 'u'))
73
+ raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 3))
74
+ # Test incorrect coordinate type
75
+ raises(TypeError, lambda: J._fill_coordinate_list([q0, symbols('q1')], 2))
76
+ raises(TypeError, lambda: J._fill_coordinate_list([q0 + q1, q1], 2))
77
+ # Test if derivative as generalized speed is allowed
78
+ _, _, P, C = _generate_body()
79
+ PinJoint('J', P, C, q1, q1.diff(t))
80
+ # Test duplicate coordinates
81
+ _, _, P, C = _generate_body()
82
+ raises(ValueError, lambda: SphericalJoint('J', P, C, [q1j, None, None]))
83
+ raises(ValueError, lambda: SphericalJoint('J', P, C, speeds=[u0, u0, u1]))
84
+
85
+
86
+ def test_pin_joint():
87
+ P = Body('P')
88
+ C = Body('C')
89
+ l, m = symbols('l m')
90
+ q, u = dynamicsymbols('q_J, u_J')
91
+ Pj = PinJoint('J', P, C)
92
+ assert Pj.name == 'J'
93
+ assert Pj.parent == P
94
+ assert Pj.child == C
95
+ assert Pj.coordinates == Matrix([q])
96
+ assert Pj.speeds == Matrix([u])
97
+ assert Pj.kdes == Matrix([u - q.diff(t)])
98
+ assert Pj.joint_axis == P.frame.x
99
+ assert Pj.child_point.pos_from(C.masscenter) == Vector(0)
100
+ assert Pj.parent_point.pos_from(P.masscenter) == Vector(0)
101
+ assert Pj.parent_point.pos_from(Pj._child_point) == Vector(0)
102
+ assert C.masscenter.pos_from(P.masscenter) == Vector(0)
103
+ assert Pj.parent_interframe == P.frame
104
+ assert Pj.child_interframe == C.frame
105
+ assert Pj.__str__() == 'PinJoint: J parent: P child: C'
106
+
107
+ P1 = Body('P1')
108
+ C1 = Body('C1')
109
+ Pint = ReferenceFrame('P_int')
110
+ Pint.orient_axis(P1.frame, P1.y, pi / 2)
111
+ J1 = PinJoint('J1', P1, C1, parent_point=l*P1.frame.x,
112
+ child_point=m*C1.frame.y, joint_axis=P1.frame.z,
113
+ parent_interframe=Pint)
114
+ assert J1._joint_axis == P1.frame.z
115
+ assert J1._child_point.pos_from(C1.masscenter) == m * C1.frame.y
116
+ assert J1._parent_point.pos_from(P1.masscenter) == l * P1.frame.x
117
+ assert J1._parent_point.pos_from(J1._child_point) == Vector(0)
118
+ assert (P1.masscenter.pos_from(C1.masscenter) ==
119
+ -l*P1.frame.x + m*C1.frame.y)
120
+ assert J1.parent_interframe == Pint
121
+ assert J1.child_interframe == C1.frame
122
+
123
+ q, u = dynamicsymbols('q, u')
124
+ N, A, P, C, Pint, Cint = _generate_body(True)
125
+ parent_point = P.masscenter.locatenew('parent_point', N.x + N.y)
126
+ child_point = C.masscenter.locatenew('child_point', C.y + C.z)
127
+ J = PinJoint('J', P, C, q, u, parent_point=parent_point,
128
+ child_point=child_point, parent_interframe=Pint,
129
+ child_interframe=Cint, joint_axis=N.z)
130
+ assert J.joint_axis == N.z
131
+ assert J.parent_point.vel(N) == 0
132
+ assert J.parent_point == parent_point
133
+ assert J.child_point == child_point
134
+ assert J.child_point.pos_from(P.masscenter) == N.x + N.y
135
+ assert J.parent_point.pos_from(C.masscenter) == C.y + C.z
136
+ assert C.masscenter.pos_from(P.masscenter) == N.x + N.y - C.y - C.z
137
+ assert C.masscenter.vel(N).express(N) == (u * sin(q) - u * cos(q)) * N.x + (
138
+ -u * sin(q) - u * cos(q)) * N.y
139
+ assert J.parent_interframe == Pint
140
+ assert J.child_interframe == Cint
141
+
142
+
143
+ def test_pin_joint_double_pendulum():
144
+ q1, q2 = dynamicsymbols('q1 q2')
145
+ u1, u2 = dynamicsymbols('u1 u2')
146
+ m, l = symbols('m l')
147
+ N = ReferenceFrame('N')
148
+ A = ReferenceFrame('A')
149
+ B = ReferenceFrame('B')
150
+ C = Body('C', frame=N) # ceiling
151
+ PartP = Body('P', frame=A, mass=m)
152
+ PartR = Body('R', frame=B, mass=m)
153
+
154
+ J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
155
+ child_point=-l*A.x, joint_axis=C.frame.z)
156
+ J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
157
+ child_point=-l*B.x, joint_axis=PartP.frame.z)
158
+
159
+ # Check orientation
160
+ assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0],
161
+ [sin(q1), cos(q1), 0], [0, 0, 1]])
162
+ assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0],
163
+ [sin(q2), cos(q2), 0], [0, 0, 1]])
164
+ assert _simplify_matrix(N.dcm(B)) == Matrix([[cos(q1 + q2), -sin(q1 + q2), 0],
165
+ [sin(q1 + q2), cos(q1 + q2), 0],
166
+ [0, 0, 1]])
167
+
168
+ # Check Angular Velocity
169
+ assert A.ang_vel_in(N) == u1 * N.z
170
+ assert B.ang_vel_in(A) == u2 * A.z
171
+ assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z
172
+
173
+ # Check kde
174
+ assert J1.kdes == Matrix([u1 - q1.diff(t)])
175
+ assert J2.kdes == Matrix([u2 - q2.diff(t)])
176
+
177
+ # Check Linear Velocity
178
+ assert PartP.masscenter.vel(N) == l*u1*A.y
179
+ assert PartR.masscenter.vel(A) == l*u2*B.y
180
+ assert PartR.masscenter.vel(N) == l*u1*A.y + l*(u1 + u2)*B.y
181
+
182
+
183
+ def test_pin_joint_chaos_pendulum():
184
+ mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h')
185
+ theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
186
+ N = ReferenceFrame('N')
187
+ A = ReferenceFrame('A')
188
+ B = ReferenceFrame('B')
189
+ lA = (lB - h / 2) / 2
190
+ lC = (lB/2 + h/4)
191
+ rod = Body('rod', frame=A, mass=mA)
192
+ plate = Body('plate', mass=mB, frame=B)
193
+ C = Body('C', frame=N)
194
+ J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
195
+ child_point=lA*A.z, joint_axis=N.y)
196
+ J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
197
+ parent_point=lC*A.z, joint_axis=A.z)
198
+
199
+ # Check orientation
200
+ assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)],
201
+ [0, 1, 0],
202
+ [sin(theta), 0, cos(theta)]])
203
+ assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0],
204
+ [sin(phi), cos(phi), 0],
205
+ [0, 0, 1]])
206
+ assert B.dcm(N) == Matrix([
207
+ [cos(phi)*cos(theta), sin(phi), -sin(theta)*cos(phi)],
208
+ [-sin(phi)*cos(theta), cos(phi), sin(phi)*sin(theta)],
209
+ [sin(theta), 0, cos(theta)]])
210
+
211
+ # Check Angular Velocity
212
+ assert A.ang_vel_in(N) == omega*N.y
213
+ assert A.ang_vel_in(B) == -alpha*A.z
214
+ assert N.ang_vel_in(B) == -omega*N.y - alpha*A.z
215
+
216
+ # Check kde
217
+ assert J1.kdes == Matrix([omega - theta.diff(t)])
218
+ assert J2.kdes == Matrix([alpha - phi.diff(t)])
219
+
220
+ # Check pos of masscenters
221
+ assert C.masscenter.pos_from(rod.masscenter) == lA*A.z
222
+ assert rod.masscenter.pos_from(plate.masscenter) == - lC * A.z
223
+
224
+ # Check Linear Velocities
225
+ assert rod.masscenter.vel(N) == (h/4 - lB/2)*omega*A.x
226
+ assert plate.masscenter.vel(N) == ((h/4 - lB/2)*omega +
227
+ (h/4 + lB/2)*omega)*A.x
228
+
229
+
230
+ def test_pin_joint_interframe():
231
+ q, u = dynamicsymbols('q, u')
232
+ # Check not connected
233
+ N, A, P, C = _generate_body()
234
+ Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint')
235
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint))
236
+ raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint))
237
+ # Check not fixed interframe
238
+ Pint.orient_axis(N, N.z, q)
239
+ Cint.orient_axis(A, A.z, q)
240
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint))
241
+ raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint))
242
+ # Check only parent_interframe
243
+ N, A, P, C = _generate_body()
244
+ Pint = ReferenceFrame('Pint')
245
+ Pint.orient_body_fixed(N, (pi / 4, pi, pi / 3), 'xyz')
246
+ PinJoint('J', P, C, q, u, parent_point=N.x, child_point=-C.y,
247
+ parent_interframe=Pint, joint_axis=Pint.x)
248
+ assert _simplify_matrix(N.dcm(A)) - Matrix([
249
+ [-1 / 2, sqrt(3) * cos(q) / 2, -sqrt(3) * sin(q) / 2],
250
+ [sqrt(6) / 4, sqrt(2) * (2 * sin(q) + cos(q)) / 4,
251
+ sqrt(2) * (-sin(q) + 2 * cos(q)) / 4],
252
+ [sqrt(6) / 4, sqrt(2) * (-2 * sin(q) + cos(q)) / 4,
253
+ -sqrt(2) * (sin(q) + 2 * cos(q)) / 4]]) == zeros(3)
254
+ assert A.ang_vel_in(N) == u * Pint.x
255
+ assert C.masscenter.pos_from(P.masscenter) == N.x + A.y
256
+ assert C.masscenter.vel(N) == u * A.z
257
+ assert P.masscenter.vel(Pint) == Vector(0)
258
+ assert C.masscenter.vel(Pint) == u * A.z
259
+ # Check only child_interframe
260
+ N, A, P, C = _generate_body()
261
+ Cint = ReferenceFrame('Cint')
262
+ Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz')
263
+ PinJoint('J', P, C, q, u, parent_point=-N.z, child_point=C.x,
264
+ child_interframe=Cint, joint_axis=P.x + P.z)
265
+ assert _simplify_matrix(N.dcm(A)) == Matrix([
266
+ [-sqrt(2) * sin(q) / 2,
267
+ -sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4,
268
+ sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4],
269
+ [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4,
270
+ (-sqrt(2) + sqrt(6)) * sin(q) / 4],
271
+ [sqrt(2) * sin(q) / 2,
272
+ sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4,
273
+ sqrt(3) * (1 - cos(q)) / 4 + cos(q) / 4 + S(1) / 4]])
274
+ assert A.ang_vel_in(N) == sqrt(2) * u / 2 * N.x + sqrt(2) * u / 2 * N.z
275
+ assert C.masscenter.pos_from(P.masscenter) == - N.z - A.x
276
+ assert C.masscenter.vel(N).simplify() == (
277
+ -sqrt(6) - sqrt(2)) * u / 4 * A.y + (
278
+ -sqrt(2) + sqrt(6)) * u / 4 * A.z
279
+ assert C.masscenter.vel(Cint) == Vector(0)
280
+ # Check combination
281
+ N, A, P, C = _generate_body()
282
+ Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint')
283
+ Pint.orient_body_fixed(N, (-pi / 2, pi, pi / 2), 'xyz')
284
+ Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz')
285
+ PinJoint('J', P, C, q, u, parent_point=N.x - N.y, child_point=-C.z,
286
+ parent_interframe=Pint, child_interframe=Cint,
287
+ joint_axis=Pint.x + Pint.z)
288
+ assert _simplify_matrix(N.dcm(A)) == Matrix([
289
+ [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4,
290
+ (-sqrt(2) + sqrt(6)) * sin(q) / 4],
291
+ [-sqrt(2) * sin(q) / 2,
292
+ -sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4,
293
+ sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4],
294
+ [sqrt(2) * sin(q) / 2,
295
+ sqrt(3) * (cos(q) - 1) / 4 + cos(q) / 4 + S(1) / 4,
296
+ -sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4]])
297
+ assert A.ang_vel_in(N) == sqrt(2) * u / 2 * Pint.x + sqrt(
298
+ 2) * u / 2 * Pint.z
299
+ assert C.masscenter.pos_from(P.masscenter) == N.x - N.y + A.z
300
+ N_v_C = (-sqrt(2) + sqrt(6)) * u / 4 * A.x
301
+ assert C.masscenter.vel(N).simplify() == N_v_C
302
+ assert C.masscenter.vel(Pint).simplify() == N_v_C
303
+ assert C.masscenter.vel(Cint) == Vector(0)
304
+
305
+
306
+ def test_pin_joint_joint_axis():
307
+ q, u = dynamicsymbols('q, u')
308
+ # Check parent as reference
309
+ N, A, P, C, Pint, Cint = _generate_body(True)
310
+ pin = PinJoint('J', P, C, q, u, parent_interframe=Pint,
311
+ child_interframe=Cint, joint_axis=P.y)
312
+ assert pin.joint_axis == P.y
313
+ assert N.dcm(A) == Matrix([[sin(q), 0, cos(q)], [0, -1, 0],
314
+ [cos(q), 0, -sin(q)]])
315
+ # Check parent_interframe as reference
316
+ N, A, P, C, Pint, Cint = _generate_body(True)
317
+ pin = PinJoint('J', P, C, q, u, parent_interframe=Pint,
318
+ child_interframe=Cint, joint_axis=Pint.y)
319
+ assert pin.joint_axis == Pint.y
320
+ assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0],
321
+ [cos(q), 0, sin(q)]])
322
+ # Check combination of joint_axis with interframes supplied as vectors (2x)
323
+ N, A, P, C = _generate_body()
324
+ pin = PinJoint('J', P, C, q, u, parent_interframe=N.z,
325
+ child_interframe=-C.z, joint_axis=N.z)
326
+ assert pin.joint_axis == N.z
327
+ assert N.dcm(A) == Matrix([[-cos(q), -sin(q), 0], [-sin(q), cos(q), 0],
328
+ [0, 0, -1]])
329
+ N, A, P, C = _generate_body()
330
+ pin = PinJoint('J', P, C, q, u, parent_interframe=N.z,
331
+ child_interframe=-C.z, joint_axis=N.x)
332
+ assert pin.joint_axis == N.x
333
+ assert N.dcm(A) == Matrix([[-1, 0, 0], [0, cos(q), sin(q)],
334
+ [0, sin(q), -cos(q)]])
335
+ # Check time varying axis
336
+ N, A, P, C, Pint, Cint = _generate_body(True)
337
+ raises(ValueError, lambda: PinJoint('J', P, C,
338
+ joint_axis=cos(q) * N.x + sin(q) * N.y))
339
+ # Check joint_axis provided in child frame
340
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=C.x))
341
+ # Check some invalid combinations
342
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=P.x + C.y))
343
+ raises(ValueError, lambda: PinJoint(
344
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
345
+ joint_axis=Pint.x + C.y))
346
+ raises(ValueError, lambda: PinJoint(
347
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
348
+ joint_axis=P.x + Cint.y))
349
+ # Check valid special combination
350
+ N, A, P, C, Pint, Cint = _generate_body(True)
351
+ PinJoint('J', P, C, parent_interframe=Pint, child_interframe=Cint,
352
+ joint_axis=Pint.x + P.y)
353
+ # Check invalid zero vector
354
+ raises(Exception, lambda: PinJoint(
355
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
356
+ joint_axis=Vector(0)))
357
+ raises(Exception, lambda: PinJoint(
358
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
359
+ joint_axis=P.y + Pint.y))
360
+
361
+
362
+ def test_pin_joint_arbitrary_axis():
363
+ q, u = dynamicsymbols('q_J, u_J')
364
+
365
+ # When the bodies are attached though masscenters but axes are opposite.
366
+ N, A, P, C = _generate_body()
367
+ PinJoint('J', P, C, child_interframe=-A.x)
368
+
369
+ assert (-A.x).angle_between(N.x) == 0
370
+ assert -A.x.express(N) == N.x
371
+ assert A.dcm(N) == Matrix([[-1, 0, 0],
372
+ [0, -cos(q), -sin(q)],
373
+ [0, -sin(q), cos(q)]])
374
+ assert A.ang_vel_in(N) == u*N.x
375
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
376
+ assert C.masscenter.pos_from(P.masscenter) == 0
377
+ assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == 0
378
+ assert C.masscenter.vel(N) == 0
379
+
380
+ # When axes are different and parent joint is at masscenter but child joint
381
+ # is at a unit vector from child masscenter.
382
+ N, A, P, C = _generate_body()
383
+ PinJoint('J', P, C, child_interframe=A.y, child_point=A.x)
384
+
385
+ assert A.y.angle_between(N.x) == 0 # Axis are aligned
386
+ assert A.y.express(N) == N.x
387
+ assert A.dcm(N) == Matrix([[0, -cos(q), -sin(q)],
388
+ [1, 0, 0],
389
+ [0, -sin(q), cos(q)]])
390
+ assert A.ang_vel_in(N) == u*N.x
391
+ assert A.ang_vel_in(N).express(A) == u * A.y
392
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
393
+ assert A.ang_vel_in(N).cross(A.y) == 0
394
+ assert C.masscenter.vel(N) == u*A.z
395
+ assert C.masscenter.pos_from(P.masscenter) == -A.x
396
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
397
+ cos(q)*N.y + sin(q)*N.z)
398
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
399
+
400
+ # Similar to previous case but wrt parent body
401
+ N, A, P, C = _generate_body()
402
+ PinJoint('J', P, C, parent_interframe=N.y, parent_point=N.x)
403
+
404
+ assert N.y.angle_between(A.x) == 0 # Axis are aligned
405
+ assert N.y.express(A) == A.x
406
+ assert A.dcm(N) == Matrix([[0, 1, 0],
407
+ [-cos(q), 0, sin(q)],
408
+ [sin(q), 0, cos(q)]])
409
+ assert A.ang_vel_in(N) == u*N.y
410
+ assert A.ang_vel_in(N).express(A) == u*A.x
411
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
412
+ angle = A.ang_vel_in(N).angle_between(A.x)
413
+ assert angle.xreplace({u: 1}) == 0
414
+ assert C.masscenter.vel(N) == 0
415
+ assert C.masscenter.pos_from(P.masscenter) == N.x
416
+
417
+ # Both joint pos id defined but different axes
418
+ N, A, P, C = _generate_body()
419
+ PinJoint('J', P, C, parent_point=N.x, child_point=A.x,
420
+ child_interframe=A.x + A.y)
421
+ assert expand_mul(N.x.angle_between(A.x + A.y)) == 0 # Axis are aligned
422
+ assert (A.x + A.y).express(N).simplify() == sqrt(2)*N.x
423
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
424
+ [sqrt(2)/2, -sqrt(2)*cos(q)/2, -sqrt(2)*sin(q)/2],
425
+ [sqrt(2)/2, sqrt(2)*cos(q)/2, sqrt(2)*sin(q)/2],
426
+ [0, -sin(q), cos(q)]])
427
+ assert A.ang_vel_in(N) == u*N.x
428
+ assert (A.ang_vel_in(N).express(A).simplify() ==
429
+ (u*A.x + u*A.y)/sqrt(2))
430
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
431
+ angle = A.ang_vel_in(N).angle_between(A.x + A.y)
432
+ assert angle.xreplace({u: 1}) == 0
433
+ assert C.masscenter.vel(N).simplify() == (u * A.z)/sqrt(2)
434
+ assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
435
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
436
+ (1 - sqrt(2)/2)*N.x + sqrt(2)*cos(q)/2*N.y +
437
+ sqrt(2)*sin(q)/2*N.z)
438
+ assert (C.masscenter.vel(N).express(N).simplify() ==
439
+ -sqrt(2)*u*sin(q)/2*N.y + sqrt(2)*u*cos(q)/2*N.z)
440
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
441
+
442
+ N, A, P, C = _generate_body()
443
+ PinJoint('J', P, C, parent_point=N.x, child_point=A.x,
444
+ child_interframe=A.x + A.y - A.z)
445
+ assert expand_mul(N.x.angle_between(A.x + A.y - A.z)) == 0 # Axis aligned
446
+ assert (A.x + A.y - A.z).express(N).simplify() == sqrt(3)*N.x
447
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
448
+ [sqrt(3)/3, -sqrt(6)*sin(q + pi/4)/3,
449
+ sqrt(6)*cos(q + pi/4)/3],
450
+ [sqrt(3)/3, sqrt(6)*cos(q + pi/12)/3,
451
+ sqrt(6)*sin(q + pi/12)/3],
452
+ [-sqrt(3)/3, sqrt(6)*cos(q + 5*pi/12)/3,
453
+ sqrt(6)*sin(q + 5*pi/12)/3]])
454
+ assert A.ang_vel_in(N) == u*N.x
455
+ assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y -
456
+ u*A.z)/sqrt(3)
457
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
458
+ angle = A.ang_vel_in(N).angle_between(A.x + A.y-A.z)
459
+ assert angle.xreplace({u: 1}) == 0
460
+ assert C.masscenter.vel(N).simplify() == (u*A.y + u*A.z)/sqrt(3)
461
+ assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
462
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
463
+ (1 - sqrt(3)/3)*N.x + sqrt(6)*sin(q + pi/4)/3*N.y -
464
+ sqrt(6)*cos(q + pi/4)/3*N.z)
465
+ assert (C.masscenter.vel(N).express(N).simplify() ==
466
+ sqrt(6)*u*cos(q + pi/4)/3*N.y +
467
+ sqrt(6)*u*sin(q + pi/4)/3*N.z)
468
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
469
+
470
+ N, A, P, C = _generate_body()
471
+ m, n = symbols('m n')
472
+ PinJoint('J', P, C, parent_point=m * N.x, child_point=n * A.x,
473
+ child_interframe=A.x + A.y - A.z,
474
+ parent_interframe=N.x - N.y + N.z)
475
+ angle = (N.x - N.y + N.z).angle_between(A.x + A.y - A.z)
476
+ assert expand_mul(angle) == 0 # Axis are aligned
477
+ assert ((A.x-A.y+A.z).express(N).simplify() ==
478
+ (-4*cos(q)/3 - S(1)/3)*N.x + (S(1)/3 - 4*sin(q + pi/6)/3)*N.y +
479
+ (4*cos(q + pi/3)/3 - S(1)/3)*N.z)
480
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
481
+ [S(1)/3 - 2*cos(q)/3, -2*sin(q + pi/6)/3 - S(1)/3,
482
+ 2*cos(q + pi/3)/3 + S(1)/3],
483
+ [2*cos(q + pi/3)/3 + S(1)/3, 2*cos(q)/3 - S(1)/3,
484
+ 2*sin(q + pi/6)/3 + S(1)/3],
485
+ [-2*sin(q + pi/6)/3 - S(1)/3, 2*cos(q + pi/3)/3 + S(1)/3,
486
+ 2*cos(q)/3 - S(1)/3]])
487
+ assert A.ang_vel_in(N) == (u*N.x - u*N.y + u*N.z)/sqrt(3)
488
+ assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y -
489
+ u*A.z)/sqrt(3)
490
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
491
+ angle = A.ang_vel_in(N).angle_between(A.x+A.y-A.z)
492
+ assert angle.xreplace({u: 1}) == 0
493
+ assert (C.masscenter.vel(N).simplify() ==
494
+ sqrt(3)*n*u/3*A.y + sqrt(3)*n*u/3*A.z)
495
+ assert C.masscenter.pos_from(P.masscenter) == m*N.x - n*A.x
496
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
497
+ (m + n*(2*cos(q) - 1)/3)*N.x + n*(2*sin(q + pi/6) +
498
+ 1)/3*N.y - n*(2*cos(q + pi/3) + 1)/3*N.z)
499
+ assert (C.masscenter.vel(N).express(N).simplify() ==
500
+ - 2*n*u*sin(q)/3*N.x + 2*n*u*cos(q + pi/6)/3*N.y +
501
+ 2*n*u*sin(q + pi/3)/3*N.z)
502
+ assert C.masscenter.vel(N).dot(N.x - N.y + N.z).simplify() == 0
503
+
504
+
505
+ def test_create_aligned_frame_pi():
506
+ N, A, P, C = _generate_body()
507
+ f = Joint._create_aligned_interframe(P, -P.x, P.x)
508
+ assert f.z == P.z
509
+ f = Joint._create_aligned_interframe(P, -P.y, P.y)
510
+ assert f.x == P.x
511
+ f = Joint._create_aligned_interframe(P, -P.z, P.z)
512
+ assert f.y == P.y
513
+ f = Joint._create_aligned_interframe(P, -P.x - P.y, P.x + P.y)
514
+ assert f.z == P.z
515
+ f = Joint._create_aligned_interframe(P, -P.y - P.z, P.y + P.z)
516
+ assert f.x == P.x
517
+ f = Joint._create_aligned_interframe(P, -P.x - P.z, P.x + P.z)
518
+ assert f.y == P.y
519
+ f = Joint._create_aligned_interframe(P, -P.x - P.y - P.z, P.x + P.y + P.z)
520
+ assert f.y - f.z == P.y - P.z
521
+
522
+
523
+ def test_pin_joint_axis():
524
+ q, u = dynamicsymbols('q u')
525
+ # Test default joint axis
526
+ N, A, P, C, Pint, Cint = _generate_body(True)
527
+ J = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint)
528
+ assert J.joint_axis == Pint.x
529
+ # Test for the same joint axis expressed in different frames
530
+ N_R_A = Matrix([[0, sin(q), cos(q)],
531
+ [0, -cos(q), sin(q)],
532
+ [1, 0, 0]])
533
+ N, A, P, C, Pint, Cint = _generate_body(True)
534
+ PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint,
535
+ joint_axis=N.z)
536
+ assert N.dcm(A) == N_R_A
537
+ N, A, P, C, Pint, Cint = _generate_body(True)
538
+ PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint,
539
+ joint_axis=-Pint.z)
540
+ assert N.dcm(A) == N_R_A
541
+ # Test time varying joint axis
542
+ N, A, P, C, Pint, Cint = _generate_body(True)
543
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=q * N.z))
544
+
545
+
546
+ def test_locate_joint_pos():
547
+ # Test Vector and default
548
+ N, A, P, C = _generate_body()
549
+ joint = PinJoint('J', P, C, parent_point=N.y + N.z)
550
+ assert joint.parent_point.name == 'J_P_joint'
551
+ assert joint.parent_point.pos_from(P.masscenter) == N.y + N.z
552
+ assert joint.child_point == C.masscenter
553
+ # Test Point objects
554
+ N, A, P, C = _generate_body()
555
+ parent_point = P.masscenter.locatenew('p', N.y + N.z)
556
+ joint = PinJoint('J', P, C, parent_point=parent_point,
557
+ child_point=C.masscenter)
558
+ assert joint.parent_point == parent_point
559
+ assert joint.child_point == C.masscenter
560
+ # Check invalid type
561
+ N, A, P, C = _generate_body()
562
+ raises(TypeError,
563
+ lambda: PinJoint('J', P, C, parent_point=N.x.to_matrix(N)))
564
+ # Test time varying positions
565
+ q = dynamicsymbols('q')
566
+ N, A, P, C = _generate_body()
567
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_point=q * N.x))
568
+ N, A, P, C = _generate_body()
569
+ child_point = C.masscenter.locatenew('p', q * A.y)
570
+ raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point))
571
+ # Test undefined position
572
+ child_point = Point('p')
573
+ raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point))
574
+
575
+
576
+ def test_locate_joint_frame():
577
+ # Test rotated frame and default
578
+ N, A, P, C = _generate_body()
579
+ parent_interframe = ReferenceFrame('int_frame')
580
+ parent_interframe.orient_axis(N, N.z, 1)
581
+ joint = PinJoint('J', P, C, parent_interframe=parent_interframe)
582
+ assert joint.parent_interframe == parent_interframe
583
+ assert joint.parent_interframe.ang_vel_in(N) == 0
584
+ assert joint.child_interframe == A
585
+ # Test time varying orientations
586
+ q = dynamicsymbols('q')
587
+ N, A, P, C = _generate_body()
588
+ parent_interframe = ReferenceFrame('int_frame')
589
+ parent_interframe.orient_axis(N, N.z, q)
590
+ raises(ValueError,
591
+ lambda: PinJoint('J', P, C, parent_interframe=parent_interframe))
592
+ # Test undefined frame
593
+ N, A, P, C = _generate_body()
594
+ child_interframe = ReferenceFrame('int_frame')
595
+ child_interframe.orient_axis(N, N.z, 1) # Defined with respect to parent
596
+ raises(ValueError,
597
+ lambda: PinJoint('J', P, C, child_interframe=child_interframe))
598
+
599
+
600
+ def test_sliding_joint():
601
+ _, _, P, C = _generate_body()
602
+ q, u = dynamicsymbols('q_S, u_S')
603
+ S = PrismaticJoint('S', P, C)
604
+ assert S.name == 'S'
605
+ assert S.parent == P
606
+ assert S.child == C
607
+ assert S.coordinates == Matrix([q])
608
+ assert S.speeds == Matrix([u])
609
+ assert S.kdes == Matrix([u - q.diff(t)])
610
+ assert S.joint_axis == P.frame.x
611
+ assert S.child_point.pos_from(C.masscenter) == Vector(0)
612
+ assert S.parent_point.pos_from(P.masscenter) == Vector(0)
613
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.x
614
+ assert P.masscenter.pos_from(C.masscenter) == - q * P.frame.x
615
+ assert C.masscenter.vel(P.frame) == u * P.frame.x
616
+ assert P.ang_vel_in(C) == 0
617
+ assert C.ang_vel_in(P) == 0
618
+ assert S.__str__() == 'PrismaticJoint: S parent: P child: C'
619
+
620
+ N, A, P, C = _generate_body()
621
+ l, m = symbols('l m')
622
+ Pint = ReferenceFrame('P_int')
623
+ Pint.orient_axis(P.frame, P.y, pi / 2)
624
+ S = PrismaticJoint('S', P, C, parent_point=l * P.frame.x,
625
+ child_point=m * C.frame.y, joint_axis=P.frame.z,
626
+ parent_interframe=Pint)
627
+
628
+ assert S.joint_axis == P.frame.z
629
+ assert S.child_point.pos_from(C.masscenter) == m * C.frame.y
630
+ assert S.parent_point.pos_from(P.masscenter) == l * P.frame.x
631
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z
632
+ assert P.masscenter.pos_from(C.masscenter) == - l*N.x - q*N.z + m*A.y
633
+ assert C.masscenter.vel(P.frame) == u * P.frame.z
634
+ assert P.masscenter.vel(Pint) == Vector(0)
635
+ assert C.ang_vel_in(P) == 0
636
+ assert P.ang_vel_in(C) == 0
637
+
638
+ _, _, P, C = _generate_body()
639
+ Pint = ReferenceFrame('P_int')
640
+ Pint.orient_axis(P.frame, P.y, pi / 2)
641
+ S = PrismaticJoint('S', P, C, parent_point=l * P.frame.z,
642
+ child_point=m * C.frame.x, joint_axis=P.frame.z,
643
+ parent_interframe=Pint)
644
+ assert S.joint_axis == P.frame.z
645
+ assert S.child_point.pos_from(C.masscenter) == m * C.frame.x
646
+ assert S.parent_point.pos_from(P.masscenter) == l * P.frame.z
647
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z
648
+ assert P.masscenter.pos_from(C.masscenter) == (-l - q)*P.frame.z + m*C.frame.x
649
+ assert C.masscenter.vel(P.frame) == u * P.frame.z
650
+ assert C.ang_vel_in(P) == 0
651
+ assert P.ang_vel_in(C) == 0
652
+
653
+
654
+ def test_sliding_joint_arbitrary_axis():
655
+ q, u = dynamicsymbols('q_S, u_S')
656
+
657
+ N, A, P, C = _generate_body()
658
+ PrismaticJoint('S', P, C, child_interframe=-A.x)
659
+
660
+ assert (-A.x).angle_between(N.x) == 0
661
+ assert -A.x.express(N) == N.x
662
+ assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])
663
+ assert C.masscenter.pos_from(P.masscenter) == q * N.x
664
+ assert C.masscenter.pos_from(P.masscenter).express(A).simplify() == -q * A.x
665
+ assert C.masscenter.vel(N) == u * N.x
666
+ assert C.masscenter.vel(N).express(A) == -u * A.x
667
+ assert A.ang_vel_in(N) == 0
668
+ assert N.ang_vel_in(A) == 0
669
+
670
+ #When axes are different and parent joint is at masscenter but child joint is at a unit vector from
671
+ #child masscenter.
672
+ N, A, P, C = _generate_body()
673
+ PrismaticJoint('S', P, C, child_interframe=A.y, child_point=A.x)
674
+
675
+ assert A.y.angle_between(N.x) == 0 #Axis are aligned
676
+ assert A.y.express(N) == N.x
677
+ assert A.dcm(N) == Matrix([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
678
+ assert C.masscenter.vel(N) == u * N.x
679
+ assert C.masscenter.vel(N).express(A) == u * A.y
680
+ assert C.masscenter.pos_from(P.masscenter) == q*N.x - A.x
681
+ assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == q*N.x + N.y
682
+ assert A.ang_vel_in(N) == 0
683
+ assert N.ang_vel_in(A) == 0
684
+
685
+ #Similar to previous case but wrt parent body
686
+ N, A, P, C = _generate_body()
687
+ PrismaticJoint('S', P, C, parent_interframe=N.y, parent_point=N.x)
688
+
689
+ assert N.y.angle_between(A.x) == 0 #Axis are aligned
690
+ assert N.y.express(A) == A.x
691
+ assert A.dcm(N) == Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])
692
+ assert C.masscenter.vel(N) == u * N.y
693
+ assert C.masscenter.vel(N).express(A) == u * A.x
694
+ assert C.masscenter.pos_from(P.masscenter) == N.x + q*N.y
695
+ assert A.ang_vel_in(N) == 0
696
+ assert N.ang_vel_in(A) == 0
697
+
698
+ #Both joint pos is defined but different axes
699
+ N, A, P, C = _generate_body()
700
+ PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x,
701
+ child_interframe=A.x + A.y)
702
+ assert N.x.angle_between(A.x + A.y) == 0 #Axis are aligned
703
+ assert (A.x + A.y).express(N) == sqrt(2)*N.x
704
+ assert A.dcm(N) == Matrix([[sqrt(2)/2, -sqrt(2)/2, 0], [sqrt(2)/2, sqrt(2)/2, 0], [0, 0, 1]])
705
+ assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x
706
+ assert C.masscenter.pos_from(P.masscenter).express(N) == (q - sqrt(2)/2 + 1)*N.x + sqrt(2)/2*N.y
707
+ assert C.masscenter.vel(N).express(A) == u * (A.x + A.y)/sqrt(2)
708
+ assert C.masscenter.vel(N) == u*N.x
709
+ assert A.ang_vel_in(N) == 0
710
+ assert N.ang_vel_in(A) == 0
711
+
712
+ N, A, P, C = _generate_body()
713
+ PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x,
714
+ child_interframe=A.x + A.y - A.z)
715
+ assert N.x.angle_between(A.x + A.y - A.z) == 0 #Axis are aligned
716
+ assert (A.x + A.y - A.z).express(N) == sqrt(3)*N.x
717
+ assert _simplify_matrix(A.dcm(N)) == Matrix([[sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3],
718
+ [sqrt(3)/3, sqrt(3)/6 + S(1)/2, S(1)/2 - sqrt(3)/6],
719
+ [-sqrt(3)/3, S(1)/2 - sqrt(3)/6, sqrt(3)/6 + S(1)/2]])
720
+ assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x
721
+ assert C.masscenter.pos_from(P.masscenter).express(N) == \
722
+ (q - sqrt(3)/3 + 1)*N.x + sqrt(3)/3*N.y - sqrt(3)/3*N.z
723
+ assert C.masscenter.vel(N) == u*N.x
724
+ assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z
725
+ assert A.ang_vel_in(N) == 0
726
+ assert N.ang_vel_in(A) == 0
727
+
728
+ N, A, P, C = _generate_body()
729
+ m, n = symbols('m n')
730
+ PrismaticJoint('S', P, C, parent_point=m*N.x, child_point=n*A.x,
731
+ child_interframe=A.x + A.y - A.z,
732
+ parent_interframe=N.x - N.y + N.z)
733
+ # 0 angle means that the axis are aligned
734
+ assert (N.x-N.y+N.z).angle_between(A.x+A.y-A.z).simplify() == 0
735
+ assert (A.x+A.y-A.z).express(N) == N.x - N.y + N.z
736
+ assert _simplify_matrix(A.dcm(N)) == Matrix([[-S(1)/3, -S(2)/3, S(2)/3],
737
+ [S(2)/3, S(1)/3, S(2)/3],
738
+ [-S(2)/3, S(2)/3, S(1)/3]])
739
+ assert C.masscenter.pos_from(P.masscenter) == \
740
+ (m + sqrt(3)*q/3)*N.x - sqrt(3)*q/3*N.y + sqrt(3)*q/3*N.z - n*A.x
741
+ assert C.masscenter.pos_from(P.masscenter).express(N) == \
742
+ (m + n/3 + sqrt(3)*q/3)*N.x + (2*n/3 - sqrt(3)*q/3)*N.y + (-2*n/3 + sqrt(3)*q/3)*N.z
743
+ assert C.masscenter.vel(N) == sqrt(3)*u/3*N.x - sqrt(3)*u/3*N.y + sqrt(3)*u/3*N.z
744
+ assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z
745
+ assert A.ang_vel_in(N) == 0
746
+ assert N.ang_vel_in(A) == 0
747
+
748
+
749
+ def test_cylindrical_joint():
750
+ N, A, P, C = _generate_body()
751
+ q0_def, q1_def, u0_def, u1_def = dynamicsymbols('q0:2_J, u0:2_J')
752
+ Cj = CylindricalJoint('J', P, C)
753
+ assert Cj.name == 'J'
754
+ assert Cj.parent == P
755
+ assert Cj.child == C
756
+ assert Cj.coordinates == Matrix([q0_def, q1_def])
757
+ assert Cj.speeds == Matrix([u0_def, u1_def])
758
+ assert Cj.rotation_coordinate == q0_def
759
+ assert Cj.translation_coordinate == q1_def
760
+ assert Cj.rotation_speed == u0_def
761
+ assert Cj.translation_speed == u1_def
762
+ assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t)])
763
+ assert Cj.joint_axis == N.x
764
+ assert Cj.child_point.pos_from(C.masscenter) == Vector(0)
765
+ assert Cj.parent_point.pos_from(P.masscenter) == Vector(0)
766
+ assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.x
767
+ assert C.masscenter.pos_from(P.masscenter) == q1_def * N.x
768
+ assert Cj.child_point.vel(N) == u1_def * N.x
769
+ assert A.ang_vel_in(N) == u0_def * N.x
770
+ assert Cj.parent_interframe == N
771
+ assert Cj.child_interframe == A
772
+ assert Cj.__str__() == 'CylindricalJoint: J parent: P child: C'
773
+
774
+ q0, q1, u0, u1 = dynamicsymbols('q0:2, u0:2')
775
+ l, m = symbols('l, m')
776
+ N, A, P, C, Pint, Cint = _generate_body(True)
777
+ Cj = CylindricalJoint('J', P, C, rotation_coordinate=q0, rotation_speed=u0,
778
+ translation_speed=u1, parent_point=m * N.x,
779
+ child_point=l * A.y, parent_interframe=Pint,
780
+ child_interframe=Cint, joint_axis=2 * N.z)
781
+ assert Cj.coordinates == Matrix([q0, q1_def])
782
+ assert Cj.speeds == Matrix([u0, u1])
783
+ assert Cj.rotation_coordinate == q0
784
+ assert Cj.translation_coordinate == q1_def
785
+ assert Cj.rotation_speed == u0
786
+ assert Cj.translation_speed == u1
787
+ assert Cj.kdes == Matrix([u0 - q0.diff(t), u1 - q1_def.diff(t)])
788
+ assert Cj.joint_axis == 2 * N.z
789
+ assert Cj.child_point.pos_from(C.masscenter) == l * A.y
790
+ assert Cj.parent_point.pos_from(P.masscenter) == m * N.x
791
+ assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.z
792
+ assert C.masscenter.pos_from(
793
+ P.masscenter) == m * N.x + q1_def * N.z - l * A.y
794
+ assert C.masscenter.vel(N) == u1 * N.z - u0 * l * A.z
795
+ assert A.ang_vel_in(N) == u0 * N.z
796
+
797
+
798
+ def test_planar_joint():
799
+ N, A, P, C = _generate_body()
800
+ q0_def, q1_def, q2_def = dynamicsymbols('q0:3_J')
801
+ u0_def, u1_def, u2_def = dynamicsymbols('u0:3_J')
802
+ Cj = PlanarJoint('J', P, C)
803
+ assert Cj.name == 'J'
804
+ assert Cj.parent == P
805
+ assert Cj.child == C
806
+ assert Cj.coordinates == Matrix([q0_def, q1_def, q2_def])
807
+ assert Cj.speeds == Matrix([u0_def, u1_def, u2_def])
808
+ assert Cj.rotation_coordinate == q0_def
809
+ assert Cj.planar_coordinates == Matrix([q1_def, q2_def])
810
+ assert Cj.rotation_speed == u0_def
811
+ assert Cj.planar_speeds == Matrix([u1_def, u2_def])
812
+ assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t),
813
+ u2_def - q2_def.diff(t)])
814
+ assert Cj.rotation_axis == N.x
815
+ assert Cj.planar_vectors == [N.y, N.z]
816
+ assert Cj.child_point.pos_from(C.masscenter) == Vector(0)
817
+ assert Cj.parent_point.pos_from(P.masscenter) == Vector(0)
818
+ r_P_C = q1_def * N.y + q2_def * N.z
819
+ assert Cj.parent_point.pos_from(Cj.child_point) == -r_P_C
820
+ assert C.masscenter.pos_from(P.masscenter) == r_P_C
821
+ assert Cj.child_point.vel(N) == u1_def * N.y + u2_def * N.z
822
+ assert A.ang_vel_in(N) == u0_def * N.x
823
+ assert Cj.parent_interframe == N
824
+ assert Cj.child_interframe == A
825
+ assert Cj.__str__() == 'PlanarJoint: J parent: P child: C'
826
+
827
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
828
+ l, m = symbols('l, m')
829
+ N, A, P, C, Pint, Cint = _generate_body(True)
830
+ Cj = PlanarJoint('J', P, C, rotation_coordinate=q0,
831
+ planar_coordinates=[q1, q2], planar_speeds=[u1, u2],
832
+ parent_point=m * N.x, child_point=l * A.y,
833
+ parent_interframe=Pint, child_interframe=Cint)
834
+ assert Cj.coordinates == Matrix([q0, q1, q2])
835
+ assert Cj.speeds == Matrix([u0_def, u1, u2])
836
+ assert Cj.rotation_coordinate == q0
837
+ assert Cj.planar_coordinates == Matrix([q1, q2])
838
+ assert Cj.rotation_speed == u0_def
839
+ assert Cj.planar_speeds == Matrix([u1, u2])
840
+ assert Cj.kdes == Matrix([u0_def - q0.diff(t), u1 - q1.diff(t),
841
+ u2 - q2.diff(t)])
842
+ assert Cj.rotation_axis == Pint.x
843
+ assert Cj.planar_vectors == [Pint.y, Pint.z]
844
+ assert Cj.child_point.pos_from(C.masscenter) == l * A.y
845
+ assert Cj.parent_point.pos_from(P.masscenter) == m * N.x
846
+ assert Cj.parent_point.pos_from(Cj.child_point) == q1 * N.y + q2 * N.z
847
+ assert C.masscenter.pos_from(
848
+ P.masscenter) == m * N.x - q1 * N.y - q2 * N.z - l * A.y
849
+ assert C.masscenter.vel(N) == -u1 * N.y - u2 * N.z + u0_def * l * A.x
850
+ assert A.ang_vel_in(N) == u0_def * N.x
851
+
852
+
853
+ def test_planar_joint_advanced():
854
+ # Tests whether someone is able to just specify two normals, which will form
855
+ # the rotation axis seen from the parent and child body.
856
+ # This specific example is a block on a slope, which has that same slope of
857
+ # 30 degrees, so in the zero configuration the frames of the parent and
858
+ # child are actually aligned.
859
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
860
+ l1, l2 = symbols('l1:3')
861
+ N, A, P, C = _generate_body()
862
+ J = PlanarJoint('J', P, C, q0, [q1, q2], u0, [u1, u2],
863
+ parent_point=l1 * N.z,
864
+ child_point=-l2 * C.z,
865
+ parent_interframe=N.z + N.y / sqrt(3),
866
+ child_interframe=A.z + A.y / sqrt(3))
867
+ assert J.rotation_axis.express(N) == (N.z + N.y / sqrt(3)).normalize()
868
+ assert J.rotation_axis.express(A) == (A.z + A.y / sqrt(3)).normalize()
869
+ assert J.rotation_axis.angle_between(N.z) == pi / 6
870
+ assert N.dcm(A).xreplace({q0: 0, q1: 0, q2: 0}) == eye(3)
871
+ N_R_A = Matrix([
872
+ [cos(q0), -sqrt(3) * sin(q0) / 2, sin(q0) / 2],
873
+ [sqrt(3) * sin(q0) / 2, 3 * cos(q0) / 4 + 1 / 4,
874
+ sqrt(3) * (1 - cos(q0)) / 4],
875
+ [-sin(q0) / 2, sqrt(3) * (1 - cos(q0)) / 4, cos(q0) / 4 + 3 / 4]])
876
+ # N.dcm(A) == N_R_A did not work
877
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
878
+
879
+
880
+ def test_spherical_joint():
881
+ N, A, P, C = _generate_body()
882
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3_S, u0:3_S')
883
+ S = SphericalJoint('S', P, C)
884
+ assert S.name == 'S'
885
+ assert S.parent == P
886
+ assert S.child == C
887
+ assert S.coordinates == Matrix([q0, q1, q2])
888
+ assert S.speeds == Matrix([u0, u1, u2])
889
+ assert S.kdes == Matrix([u0 - q0.diff(t), u1 - q1.diff(t), u2 - q2.diff(t)])
890
+ assert S.child_point.pos_from(C.masscenter) == Vector(0)
891
+ assert S.parent_point.pos_from(P.masscenter) == Vector(0)
892
+ assert S.parent_point.pos_from(S.child_point) == Vector(0)
893
+ assert P.masscenter.pos_from(C.masscenter) == Vector(0)
894
+ assert C.masscenter.vel(N) == Vector(0)
895
+ assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + (
896
+ u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + (
897
+ -u0 * sin(q1) - u2) * A.z
898
+ assert C.ang_vel_in(P) == (u0 * cos(q1) * cos(q2) + u1 * sin(q2)) * A.x + (
899
+ -u0 * sin(q2) * cos(q1) + u1 * cos(q2)) * A.y + (
900
+ u0 * sin(q1) + u2) * A.z
901
+ assert S.__str__() == 'SphericalJoint: S parent: P child: C'
902
+ assert S._rot_type == 'BODY'
903
+ assert S._rot_order == 123
904
+ assert S._amounts is None
905
+
906
+
907
+ def test_spherical_joint_speeds_as_derivative_terms():
908
+ # This tests checks whether the system remains valid if the user chooses to
909
+ # pass the derivative of the generalized coordinates as generalized speeds
910
+ q0, q1, q2 = dynamicsymbols('q0:3')
911
+ u0, u1, u2 = dynamicsymbols('q0:3', 1)
912
+ N, A, P, C = _generate_body()
913
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2])
914
+ assert S.coordinates == Matrix([q0, q1, q2])
915
+ assert S.speeds == Matrix([u0, u1, u2])
916
+ assert S.kdes == Matrix([0, 0, 0])
917
+ assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + (
918
+ u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + (
919
+ -u0 * sin(q1) - u2) * A.z
920
+
921
+
922
+ def test_spherical_joint_coords():
923
+ q0s, q1s, q2s, u0s, u1s, u2s = dynamicsymbols('q0:3_S, u0:3_S')
924
+ q0, q1, q2, q3, u0, u1, u2, u4 = dynamicsymbols('q0:4, u0:4')
925
+ # Test coordinates as list
926
+ N, A, P, C = _generate_body()
927
+ S = SphericalJoint('S', P, C, [q0, q1, q2], [u0, u1, u2])
928
+ assert S.coordinates == Matrix([q0, q1, q2])
929
+ assert S.speeds == Matrix([u0, u1, u2])
930
+ # Test coordinates as Matrix
931
+ N, A, P, C = _generate_body()
932
+ S = SphericalJoint('S', P, C, Matrix([q0, q1, q2]),
933
+ Matrix([u0, u1, u2]))
934
+ assert S.coordinates == Matrix([q0, q1, q2])
935
+ assert S.speeds == Matrix([u0, u1, u2])
936
+ # Test too few generalized coordinates
937
+ N, A, P, C = _generate_body()
938
+ raises(ValueError,
939
+ lambda: SphericalJoint('S', P, C, Matrix([q0, q1]), Matrix([u0])))
940
+ # Test too many generalized coordinates
941
+ raises(ValueError, lambda: SphericalJoint(
942
+ 'S', P, C, Matrix([q0, q1, q2, q3]), Matrix([u0, u1, u2])))
943
+ raises(ValueError, lambda: SphericalJoint(
944
+ 'S', P, C, Matrix([q0, q1, q2]), Matrix([u0, u1, u2, u4])))
945
+
946
+
947
+ def test_spherical_joint_orient_body():
948
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
949
+ N_R_A = Matrix([
950
+ [-sin(q1), -sin(q2) * cos(q1), cos(q1) * cos(q2)],
951
+ [-sin(q0) * cos(q1), sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2),
952
+ -sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0)],
953
+ [cos(q0) * cos(q1), -sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0),
954
+ -sin(q0) * sin(q2) + sin(q1) * cos(q0) * cos(q2)]])
955
+ N_w_A = Matrix([[-u0 * sin(q1) - u2],
956
+ [-u0 * sin(q2) * cos(q1) + u1 * cos(q2)],
957
+ [u0 * cos(q1) * cos(q2) + u1 * sin(q2)]])
958
+ N_v_Co = Matrix([
959
+ [-sqrt(2) * (u0 * cos(q2 + pi / 4) * cos(q1) + u1 * sin(q2 + pi / 4))],
960
+ [-u0 * sin(q1) - u2], [-u0 * sin(q1) - u2]])
961
+ # Test default rot_type='BODY', rot_order=123
962
+ N, A, P, C, Pint, Cint = _generate_body(True)
963
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
964
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
965
+ parent_interframe=Pint, child_interframe=Cint,
966
+ rot_type='body', rot_order=123)
967
+ assert S._rot_type.upper() == 'BODY'
968
+ assert S._rot_order == 123
969
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
970
+ assert A.ang_vel_in(N).to_matrix(A) == N_w_A
971
+ assert C.masscenter.vel(N).to_matrix(A) == N_v_Co
972
+ # Test change of amounts
973
+ N, A, P, C, Pint, Cint = _generate_body(True)
974
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
975
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
976
+ parent_interframe=Pint, child_interframe=Cint,
977
+ rot_type='BODY', amounts=(q1, q0, q2), rot_order=123)
978
+ switch_order = lambda expr: expr.xreplace(
979
+ {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2})
980
+ assert S._rot_type.upper() == 'BODY'
981
+ assert S._rot_order == 123
982
+ assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3)
983
+ assert A.ang_vel_in(N).to_matrix(A) == switch_order(N_w_A)
984
+ assert C.masscenter.vel(N).to_matrix(A) == switch_order(N_v_Co)
985
+ # Test different rot_order
986
+ N, A, P, C, Pint, Cint = _generate_body(True)
987
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
988
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
989
+ parent_interframe=Pint, child_interframe=Cint,
990
+ rot_type='BodY', rot_order='yxz')
991
+ assert S._rot_type.upper() == 'BODY'
992
+ assert S._rot_order == 'yxz'
993
+ assert _simplify_matrix(N.dcm(A) - Matrix([
994
+ [-sin(q0) * cos(q1), sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0),
995
+ sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)],
996
+ [-sin(q1), -cos(q1) * cos(q2), -sin(q2) * cos(q1)],
997
+ [cos(q0) * cos(q1), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
998
+ sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0)]])) == zeros(3)
999
+ assert A.ang_vel_in(N).to_matrix(A) == Matrix([
1000
+ [u0 * sin(q1) - u2], [u0 * cos(q1) * cos(q2) - u1 * sin(q2)],
1001
+ [u0 * sin(q2) * cos(q1) + u1 * cos(q2)]])
1002
+ assert C.masscenter.vel(N).to_matrix(A) == Matrix([
1003
+ [-sqrt(2) * (u0 * sin(q2 + pi / 4) * cos(q1) + u1 * cos(q2 + pi / 4))],
1004
+ [u0 * sin(q1) - u2], [u0 * sin(q1) - u2]])
1005
+
1006
+
1007
+ def test_spherical_joint_orient_space():
1008
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
1009
+ N_R_A = Matrix([
1010
+ [-sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
1011
+ sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0), cos(q1) * cos(q2)],
1012
+ [-sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0),
1013
+ -sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2), -sin(q2) * cos(q1)],
1014
+ [cos(q0) * cos(q1), -sin(q0) * cos(q1), sin(q1)]])
1015
+ N_w_A = Matrix([
1016
+ [u1 * sin(q0) - u2 * cos(q0) * cos(q1)],
1017
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)], [u0 - u2 * sin(q1)]])
1018
+ N_v_Co = Matrix([
1019
+ [u0 - u2 * sin(q1)], [u0 - u2 * sin(q1)],
1020
+ [sqrt(2) * (-u1 * sin(q0 + pi / 4) + u2 * cos(q0 + pi / 4) * cos(q1))]])
1021
+ # Test default rot_type='BODY', rot_order=123
1022
+ N, A, P, C, Pint, Cint = _generate_body(True)
1023
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1024
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1025
+ parent_interframe=Pint, child_interframe=Cint,
1026
+ rot_type='space', rot_order=123)
1027
+ assert S._rot_type.upper() == 'SPACE'
1028
+ assert S._rot_order == 123
1029
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
1030
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == N_w_A
1031
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == N_v_Co
1032
+ # Test change of amounts
1033
+ switch_order = lambda expr: expr.xreplace(
1034
+ {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2})
1035
+ N, A, P, C, Pint, Cint = _generate_body(True)
1036
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1037
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1038
+ parent_interframe=Pint, child_interframe=Cint,
1039
+ rot_type='SPACE', amounts=(q1, q0, q2), rot_order=123)
1040
+ assert S._rot_type.upper() == 'SPACE'
1041
+ assert S._rot_order == 123
1042
+ assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3)
1043
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == switch_order(N_w_A)
1044
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == switch_order(N_v_Co)
1045
+ # Test different rot_order
1046
+ N, A, P, C, Pint, Cint = _generate_body(True)
1047
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1048
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1049
+ parent_interframe=Pint, child_interframe=Cint,
1050
+ rot_type='SPaCe', rot_order='zxy')
1051
+ assert S._rot_type.upper() == 'SPACE'
1052
+ assert S._rot_order == 'zxy'
1053
+ assert _simplify_matrix(N.dcm(A) - Matrix([
1054
+ [-sin(q2) * cos(q1), -sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0),
1055
+ sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)],
1056
+ [-sin(q1), -cos(q0) * cos(q1), -sin(q0) * cos(q1)],
1057
+ [cos(q1) * cos(q2), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
1058
+ -sin(q0) * sin(q1) * cos(q2) + sin(q2) * cos(q0)]]))
1059
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A) - Matrix([
1060
+ [-u0 + u2 * sin(q1)], [-u1 * sin(q0) + u2 * cos(q0) * cos(q1)],
1061
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)]])) == zeros(3, 1)
1062
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A) - Matrix([
1063
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)],
1064
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)],
1065
+ [u0 + u1 * sin(q0) - u2 * sin(q1) -
1066
+ u2 * cos(q0) * cos(q1)]])) == zeros(3, 1)
1067
+
1068
+
1069
+ def test_weld_joint():
1070
+ _, _, P, C = _generate_body()
1071
+ W = WeldJoint('W', P, C)
1072
+ assert W.name == 'W'
1073
+ assert W.parent == P
1074
+ assert W.child == C
1075
+ assert W.coordinates == Matrix()
1076
+ assert W.speeds == Matrix()
1077
+ assert W.kdes == Matrix(1, 0, []).T
1078
+ assert P.dcm(C) == eye(3)
1079
+ assert W.child_point.pos_from(C.masscenter) == Vector(0)
1080
+ assert W.parent_point.pos_from(P.masscenter) == Vector(0)
1081
+ assert W.parent_point.pos_from(W.child_point) == Vector(0)
1082
+ assert P.masscenter.pos_from(C.masscenter) == Vector(0)
1083
+ assert C.masscenter.vel(P.frame) == Vector(0)
1084
+ assert P.ang_vel_in(C) == 0
1085
+ assert C.ang_vel_in(P) == 0
1086
+ assert W.__str__() == 'WeldJoint: W parent: P child: C'
1087
+
1088
+ N, A, P, C = _generate_body()
1089
+ l, m = symbols('l m')
1090
+ Pint = ReferenceFrame('P_int')
1091
+ Pint.orient_axis(P.frame, P.y, pi / 2)
1092
+ W = WeldJoint('W', P, C, parent_point=l * P.frame.x,
1093
+ child_point=m * C.frame.y, parent_interframe=Pint)
1094
+
1095
+ assert W.child_point.pos_from(C.masscenter) == m * C.frame.y
1096
+ assert W.parent_point.pos_from(P.masscenter) == l * P.frame.x
1097
+ assert W.parent_point.pos_from(W.child_point) == Vector(0)
1098
+ assert P.masscenter.pos_from(C.masscenter) == - l * N.x + m * A.y
1099
+ assert C.masscenter.vel(P.frame) == Vector(0)
1100
+ assert P.masscenter.vel(Pint) == Vector(0)
1101
+ assert C.ang_vel_in(P) == 0
1102
+ assert P.ang_vel_in(C) == 0
1103
+ assert P.x == A.z
1104
+
1105
+ JointsMethod(P, W) # Tests #10770
1106
+
1107
+
1108
+ def test_deprecated_parent_child_axis():
1109
+ q, u = dynamicsymbols('q_J, u_J')
1110
+ N, A, P, C = _generate_body()
1111
+ with warns_deprecated_sympy():
1112
+ PinJoint('J', P, C, child_axis=-A.x)
1113
+ assert (-A.x).angle_between(N.x) == 0
1114
+ assert -A.x.express(N) == N.x
1115
+ assert A.dcm(N) == Matrix([[-1, 0, 0],
1116
+ [0, -cos(q), -sin(q)],
1117
+ [0, -sin(q), cos(q)]])
1118
+ assert A.ang_vel_in(N) == u * N.x
1119
+ assert A.ang_vel_in(N).magnitude() == sqrt(u ** 2)
1120
+
1121
+ N, A, P, C = _generate_body()
1122
+ with warns_deprecated_sympy():
1123
+ PrismaticJoint('J', P, C, parent_axis=P.x + P.y)
1124
+ assert (A.x).angle_between(N.x + N.y) == 0
1125
+ assert A.x.express(N) == (N.x + N.y) / sqrt(2)
1126
+ assert A.dcm(N) == Matrix([[sqrt(2) / 2, sqrt(2) / 2, 0],
1127
+ [-sqrt(2) / 2, sqrt(2) / 2, 0], [0, 0, 1]])
1128
+ assert A.ang_vel_in(N) == Vector(0)
1129
+
1130
+
1131
+ def test_deprecated_joint_pos():
1132
+ N, A, P, C = _generate_body()
1133
+ with warns_deprecated_sympy():
1134
+ pin = PinJoint('J', P, C, parent_joint_pos=N.x + N.y,
1135
+ child_joint_pos=C.y - C.z)
1136
+ assert pin.parent_point.pos_from(P.masscenter) == N.x + N.y
1137
+ assert pin.child_point.pos_from(C.masscenter) == C.y - C.z
1138
+
1139
+ N, A, P, C = _generate_body()
1140
+ with warns_deprecated_sympy():
1141
+ slider = PrismaticJoint('J', P, C, parent_joint_pos=N.z + N.y,
1142
+ child_joint_pos=C.y - C.x)
1143
+ assert slider.parent_point.pos_from(P.masscenter) == N.z + N.y
1144
+ assert slider.child_point.pos_from(C.masscenter) == C.y - C.x
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand
2
+ from sympy.core.symbol import symbols
3
+ from sympy.functions.elementary.trigonometric import (cos, sin)
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.simplify.trigsimp import trigsimp
6
+ from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod,
7
+ PrismaticJoint, LagrangesMethod, inertia)
8
+ from sympy.physics.vector import dynamicsymbols, ReferenceFrame
9
+ from sympy.testing.pytest import raises
10
+ from sympy.core.backend import zeros
11
+ from sympy.utilities.lambdify import lambdify
12
+ from sympy.solvers.solvers import solve
13
+
14
+
15
+ t = dynamicsymbols._t # type: ignore
16
+
17
+
18
+ def test_jointsmethod():
19
+ P = Body('P')
20
+ C = Body('C')
21
+ Pin = PinJoint('P1', P, C)
22
+ C_ixx, g = symbols('C_ixx g')
23
+ q, u = dynamicsymbols('q_P1, u_P1')
24
+ P.apply_force(g*P.y)
25
+ method = JointsMethod(P, Pin)
26
+ assert method.frame == P.frame
27
+ assert method.bodies == [C, P]
28
+ assert method.loads == [(P.masscenter, g*P.frame.y)]
29
+ assert method.q == Matrix([q])
30
+ assert method.u == Matrix([u])
31
+ assert method.kdes == Matrix([u - q.diff()])
32
+ soln = method.form_eoms()
33
+ assert soln == Matrix([[-C_ixx*u.diff()]])
34
+ assert method.forcing_full == Matrix([[u], [0]])
35
+ assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]])
36
+ assert isinstance(method.method, KanesMethod)
37
+
38
+ def test_jointmethod_duplicate_coordinates_speeds():
39
+ P = Body('P')
40
+ C = Body('C')
41
+ T = Body('T')
42
+ q, u = dynamicsymbols('q u')
43
+ P1 = PinJoint('P1', P, C, q)
44
+ P2 = PrismaticJoint('P2', C, T, q)
45
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
46
+
47
+ P1 = PinJoint('P1', P, C, speeds=u)
48
+ P2 = PrismaticJoint('P2', C, T, speeds=u)
49
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
50
+
51
+ P1 = PinJoint('P1', P, C, q, u)
52
+ P2 = PrismaticJoint('P2', C, T, q, u)
53
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
54
+
55
+ def test_complete_simple_double_pendulum():
56
+ q1, q2 = dynamicsymbols('q1 q2')
57
+ u1, u2 = dynamicsymbols('u1 u2')
58
+ m, l, g = symbols('m l g')
59
+ C = Body('C') # ceiling
60
+ PartP = Body('P', mass=m)
61
+ PartR = Body('R', mass=m)
62
+ J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
63
+ child_point=-l*PartP.x, joint_axis=C.z)
64
+ J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
65
+ child_point=-l*PartR.x, joint_axis=PartP.z)
66
+
67
+ PartP.apply_force(m*g*C.x)
68
+ PartR.apply_force(m*g*C.x)
69
+
70
+ method = JointsMethod(C, J1, J2)
71
+ method.form_eoms()
72
+
73
+ assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0],
74
+ [0, 1, 0, 0],
75
+ [0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m],
76
+ [0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]])
77
+ assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) -
78
+ g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)],
79
+ [-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]]))
80
+
81
+ def test_two_dof_joints():
82
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
83
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
84
+ W = Body('W')
85
+ B1 = Body('B1', mass=m)
86
+ B2 = Body('B2', mass=m)
87
+ J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1)
88
+ J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2)
89
+ W.apply_force(k1*q1*W.x, reaction_body=B1)
90
+ W.apply_force(c1*u1*W.x, reaction_body=B1)
91
+ B1.apply_force(k2*q2*W.x, reaction_body=B2)
92
+ B1.apply_force(c2*u2*W.x, reaction_body=B2)
93
+ method = JointsMethod(W, J1, J2)
94
+ method.form_eoms()
95
+ MM = method.mass_matrix
96
+ forcing = method.forcing
97
+ rhs = MM.LUsolve(forcing)
98
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
99
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
100
+ c2 * u2) / m)
101
+
102
+ def test_simple_pedulum():
103
+ l, m, g = symbols('l m g')
104
+ C = Body('C')
105
+ b = Body('b', mass=m)
106
+ q = dynamicsymbols('q')
107
+ P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q,
108
+ child_point=-l * b.x, joint_axis=C.z)
109
+ b.potential_energy = - m * g * l * cos(q)
110
+ method = JointsMethod(C, P)
111
+ method.form_eoms(LagrangesMethod)
112
+ rhs = method.rhs()
113
+ assert rhs[1] == -g*sin(q)/l
114
+
115
+ def test_chaos_pendulum():
116
+ #https://www.pydy.org/examples/chaos_pendulum.html
117
+ mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g')
118
+ theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
119
+
120
+ A = ReferenceFrame('A')
121
+ B = ReferenceFrame('B')
122
+
123
+ rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0))
124
+ plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz))
125
+ C = Body('C')
126
+ J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
127
+ child_point=-lA * rod.z, joint_axis=C.y)
128
+ J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
129
+ parent_point=(lB - lA) * rod.z, joint_axis=rod.z)
130
+
131
+ rod.apply_force(mA*g*C.z)
132
+ plate.apply_force(mB*g*C.z)
133
+
134
+ method = JointsMethod(C, J1, J2)
135
+ method.form_eoms()
136
+
137
+ MM = method.mass_matrix
138
+ forcing = method.forcing
139
+ rhs = MM.LUsolve(forcing)
140
+ xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) *
141
+ cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx *
142
+ sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB)
143
+ assert (rhs[0] - xd).simplify() == 0
144
+ xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz
145
+ assert (rhs[1] - xd).simplify() == 0
146
+
147
+ def test_four_bar_linkage_with_manual_constraints():
148
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4, u1:4')
149
+ l1, l2, l3, l4, rho = symbols('l1:5, rho')
150
+
151
+ N = ReferenceFrame('N')
152
+ inertias = [inertia(N, 0, 0, rho * l ** 3 / 12) for l in (l1, l2, l3, l4)]
153
+ link1 = Body('Link1', frame=N, mass=rho * l1, central_inertia=inertias[0])
154
+ link2 = Body('Link2', mass=rho * l2, central_inertia=inertias[1])
155
+ link3 = Body('Link3', mass=rho * l3, central_inertia=inertias[2])
156
+ link4 = Body('Link4', mass=rho * l4, central_inertia=inertias[3])
157
+
158
+ joint1 = PinJoint(
159
+ 'J1', link1, link2, coordinates=q1, speeds=u1, joint_axis=link1.z,
160
+ parent_point=l1 / 2 * link1.x, child_point=-l2 / 2 * link2.x)
161
+ joint2 = PinJoint(
162
+ 'J2', link2, link3, coordinates=q2, speeds=u2, joint_axis=link2.z,
163
+ parent_point=l2 / 2 * link2.x, child_point=-l3 / 2 * link3.x)
164
+ joint3 = PinJoint(
165
+ 'J3', link3, link4, coordinates=q3, speeds=u3, joint_axis=link3.z,
166
+ parent_point=l3 / 2 * link3.x, child_point=-l4 / 2 * link4.x)
167
+
168
+ loop = link4.masscenter.pos_from(link1.masscenter) \
169
+ + l1 / 2 * link1.x + l4 / 2 * link4.x
170
+
171
+ fh = Matrix([loop.dot(link1.x), loop.dot(link1.y)])
172
+
173
+ method = JointsMethod(link1, joint1, joint2, joint3)
174
+
175
+ t = dynamicsymbols._t
176
+ qdots = solve(method.kdes, [q1.diff(t), q2.diff(t), q3.diff(t)])
177
+ fhd = fh.diff(t).subs(qdots)
178
+
179
+ kane = KanesMethod(method.frame, q_ind=[q1], u_ind=[u1],
180
+ q_dependent=[q2, q3], u_dependent=[u2, u3],
181
+ kd_eqs=method.kdes, configuration_constraints=fh,
182
+ velocity_constraints=fhd, forcelist=method.loads,
183
+ bodies=method.bodies)
184
+ fr, frs = kane.kanes_equations()
185
+ assert fr == zeros(1)
186
+
187
+ # Numerically check the mass- and forcing-matrix
188
+ p = Matrix([l1, l2, l3, l4, rho])
189
+ q = Matrix([q1, q2, q3])
190
+ u = Matrix([u1, u2, u3])
191
+ eval_m = lambdify((q, p), kane.mass_matrix)
192
+ eval_f = lambdify((q, u, p), kane.forcing)
193
+ eval_fhd = lambdify((q, u, p), fhd)
194
+
195
+ p_vals = [0.13, 0.24, 0.21, 0.34, 997]
196
+ q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # Satisfies fh
197
+ u_vals = [0.2, -0.17963733938852067, 0.1309060540601612] # Satisfies fhd
198
+ mass_check = Matrix([[3.452709815256506e+01, 7.003948798374735e+00,
199
+ -4.939690970641498e+00],
200
+ [-2.203792703880936e-14, 2.071702479957077e-01,
201
+ 2.842917573033711e-01],
202
+ [-1.300000000000123e-01, -8.836934896046506e-03,
203
+ 1.864891330060847e-01]])
204
+ forcing_check = Matrix([[-0.031211821321648],
205
+ [-0.00066022608181],
206
+ [0.001813559741243]])
207
+ eps = 1e-10
208
+ assert all(abs(x) < eps for x in eval_fhd(q_vals, u_vals, p_vals))
209
+ assert all(abs(x) < eps for x in
210
+ (Matrix(eval_m(q_vals, p_vals)) - mass_check))
211
+ assert all(abs(x) < eps for x in
212
+ (Matrix(eval_f(q_vals, u_vals, p_vals)) - forcing_check))
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import solve
2
+ from sympy.core.backend import (cos, expand, Matrix, sin, symbols, tan, sqrt, S,
3
+ zeros, eye)
4
+ from sympy.simplify.simplify import simplify
5
+ from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
6
+ RigidBody, KanesMethod, inertia, Particle,
7
+ dot)
8
+ from sympy.testing.pytest import raises
9
+ from sympy.core.backend import USE_SYMENGINE
10
+
11
+
12
+ def test_invalid_coordinates():
13
+ # Simple pendulum, but use symbols instead of dynamicsymbols
14
+ l, m, g = symbols('l m g')
15
+ q, u = symbols('q u') # Generalized coordinate
16
+ kd = [q.diff(dynamicsymbols._t) - u]
17
+ N, O = ReferenceFrame('N'), Point('O')
18
+ O.set_vel(N, 0)
19
+ P = Particle('P', Point('P'), m)
20
+ P.point.set_pos(O, l * (sin(q) * N.x - cos(q) * N.y))
21
+ F = (P.point, -m * g * N.y)
22
+ raises(ValueError, lambda: KanesMethod(N, [q], [u], kd, bodies=[P],
23
+ forcelist=[F]))
24
+
25
+
26
+ def test_one_dof():
27
+ # This is for a 1 dof spring-mass-damper case.
28
+ # It is described in more detail in the KanesMethod docstring.
29
+ q, u = dynamicsymbols('q u')
30
+ qd, ud = dynamicsymbols('q u', 1)
31
+ m, c, k = symbols('m c k')
32
+ N = ReferenceFrame('N')
33
+ P = Point('P')
34
+ P.set_vel(N, u * N.x)
35
+
36
+ kd = [qd - u]
37
+ FL = [(P, (-k * q - c * u) * N.x)]
38
+ pa = Particle('pa', P, m)
39
+ BL = [pa]
40
+
41
+ KM = KanesMethod(N, [q], [u], kd)
42
+ KM.kanes_equations(BL, FL)
43
+
44
+ assert KM.bodies == BL
45
+ assert KM.loads == FL
46
+
47
+ MM = KM.mass_matrix
48
+ forcing = KM.forcing
49
+ rhs = MM.inv() * forcing
50
+ assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
51
+
52
+ assert simplify(KM.rhs() -
53
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
54
+
55
+ assert (KM.linearize(A_and_B=True, )[0] == Matrix([[0, 1], [-k/m, -c/m]]))
56
+
57
+
58
+ def test_two_dof():
59
+ # This is for a 2 d.o.f., 2 particle spring-mass-damper.
60
+ # The first coordinate is the displacement of the first particle, and the
61
+ # second is the relative displacement between the first and second
62
+ # particles. Speeds are defined as the time derivatives of the particles.
63
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
64
+ q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
65
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
66
+ N = ReferenceFrame('N')
67
+ P1 = Point('P1')
68
+ P2 = Point('P2')
69
+ P1.set_vel(N, u1 * N.x)
70
+ P2.set_vel(N, (u1 + u2) * N.x)
71
+ # Note we multiply the kinematic equation by an arbitrary factor
72
+ # to test the implicit vs explicit kinematics attribute
73
+ kd = [q1d/2 - u1/2, 2*q2d - 2*u2]
74
+
75
+ # Now we create the list of forces, then assign properties to each
76
+ # particle, then create a list of all particles.
77
+ FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
78
+ q2 - c2 * u2) * N.x)]
79
+ pa1 = Particle('pa1', P1, m)
80
+ pa2 = Particle('pa2', P2, m)
81
+ BL = [pa1, pa2]
82
+
83
+ # Finally we create the KanesMethod object, specify the inertial frame,
84
+ # pass relevant information, and form Fr & Fr*. Then we calculate the mass
85
+ # matrix and forcing terms, and finally solve for the udots.
86
+ KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
87
+ KM.kanes_equations(BL, FL)
88
+ MM = KM.mass_matrix
89
+ forcing = KM.forcing
90
+ rhs = MM.inv() * forcing
91
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
92
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
93
+ c2 * u2) / m)
94
+
95
+ # Check that the explicit form is the default and kinematic mass matrix is identity
96
+ assert KM.explicit_kinematics
97
+ assert KM.mass_matrix_kin == eye(2)
98
+
99
+ # Check that for the implicit form the mass matrix is not identity
100
+ KM.explicit_kinematics = False
101
+ assert KM.mass_matrix_kin == Matrix([[S(1)/2, 0], [0, 2]])
102
+
103
+ # Check that whether using implicit or explicit kinematics the RHS
104
+ # equations are consistent with the matrix form
105
+ for explicit_kinematics in [False, True]:
106
+ KM.explicit_kinematics = explicit_kinematics
107
+ assert simplify(KM.rhs() -
108
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(4, 1)
109
+
110
+ # Make sure an error is raised if nonlinear kinematic differential
111
+ # equations are supplied.
112
+ kd = [q1d - u1**2, sin(q2d) - cos(u2)]
113
+ raises(ValueError, lambda: KanesMethod(N, q_ind=[q1, q2],
114
+ u_ind=[u1, u2], kd_eqs=kd))
115
+
116
+ def test_pend():
117
+ q, u = dynamicsymbols('q u')
118
+ qd, ud = dynamicsymbols('q u', 1)
119
+ m, l, g = symbols('m l g')
120
+ N = ReferenceFrame('N')
121
+ P = Point('P')
122
+ P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
123
+ kd = [qd - u]
124
+
125
+ FL = [(P, m * g * N.x)]
126
+ pa = Particle('pa', P, m)
127
+ BL = [pa]
128
+
129
+ KM = KanesMethod(N, [q], [u], kd)
130
+ KM.kanes_equations(BL, FL)
131
+ MM = KM.mass_matrix
132
+ forcing = KM.forcing
133
+ rhs = MM.inv() * forcing
134
+ rhs.simplify()
135
+ assert expand(rhs[0]) == expand(-g / l * sin(q))
136
+ assert simplify(KM.rhs() -
137
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
138
+
139
+
140
+ def test_rolling_disc():
141
+ # Rolling Disc Example
142
+ # Here the rolling disc is formed from the contact point up, removing the
143
+ # need to introduce generalized speeds. Only 3 configuration and three
144
+ # speed variables are need to describe this system, along with the disc's
145
+ # mass and radius, and the local gravity (note that mass will drop out).
146
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
147
+ q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
148
+ r, m, g = symbols('r m g')
149
+
150
+ # The kinematics are formed by a series of simple rotations. Each simple
151
+ # rotation creates a new frame, and the next rotation is defined by the new
152
+ # frame's basis vectors. This example uses a 3-1-2 series of rotations, or
153
+ # Z, X, Y series of rotations. Angular velocity for this is defined using
154
+ # the second frame's basis (the lean frame).
155
+ N = ReferenceFrame('N')
156
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
157
+ L = Y.orientnew('L', 'Axis', [q2, Y.x])
158
+ R = L.orientnew('R', 'Axis', [q3, L.y])
159
+ w_R_N_qd = R.ang_vel_in(N)
160
+ R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
161
+
162
+ # This is the translational kinematics. We create a point with no velocity
163
+ # in N; this is the contact point between the disc and ground. Next we form
164
+ # the position vector from the contact point to the disc's center of mass.
165
+ # Finally we form the velocity and acceleration of the disc.
166
+ C = Point('C')
167
+ C.set_vel(N, 0)
168
+ Dmc = C.locatenew('Dmc', r * L.z)
169
+ Dmc.v2pt_theory(C, N, R)
170
+
171
+ # This is a simple way to form the inertia dyadic.
172
+ I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
173
+
174
+ # Kinematic differential equations; how the generalized coordinate time
175
+ # derivatives relate to generalized speeds.
176
+ kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
177
+
178
+ # Creation of the force list; it is the gravitational force at the mass
179
+ # center of the disc. Then we create the disc by assigning a Point to the
180
+ # center of mass attribute, a ReferenceFrame to the frame attribute, and mass
181
+ # and inertia. Then we form the body list.
182
+ ForceList = [(Dmc, - m * g * Y.z)]
183
+ BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
184
+ BodyList = [BodyD]
185
+
186
+ # Finally we form the equations of motion, using the same steps we did
187
+ # before. Specify inertial frame, supply generalized speeds, supply
188
+ # kinematic differential equation dictionary, compute Fr from the force
189
+ # list and Fr* from the body list, compute the mass matrix and forcing
190
+ # terms, then solve for the u dots (time derivatives of the generalized
191
+ # speeds).
192
+ KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd)
193
+ KM.kanes_equations(BodyList, ForceList)
194
+ MM = KM.mass_matrix
195
+ forcing = KM.forcing
196
+ rhs = MM.inv() * forcing
197
+ kdd = KM.kindiffdict()
198
+ rhs = rhs.subs(kdd)
199
+ rhs.simplify()
200
+ assert rhs.expand() == Matrix([(6*u2*u3*r - u3**2*r*tan(q2) +
201
+ 4*g*sin(q2))/(5*r), -2*u1*u3/3, u1*(-2*u2 + u3*tan(q2))]).expand()
202
+ assert simplify(KM.rhs() -
203
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(6, 1)
204
+
205
+ # This code tests our output vs. benchmark values. When r=g=m=1, the
206
+ # critical speed (where all eigenvalues of the linearized equations are 0)
207
+ # is 1 / sqrt(3) for the upright case.
208
+ A = KM.linearize(A_and_B=True)[0]
209
+ A_upright = A.subs({r: 1, g: 1, m: 1}).subs({q1: 0, q2: 0, q3: 0, u1: 0, u3: 0})
210
+ import sympy
211
+ assert sympy.sympify(A_upright.subs({u2: 1 / sqrt(3)})).eigenvals() == {S.Zero: 6}
212
+
213
+
214
+ def test_aux():
215
+ # Same as above, except we have 2 auxiliary speeds for the ground contact
216
+ # point, which is known to be zero. In one case, we go through then
217
+ # substitute the aux. speeds in at the end (they are zero, as well as their
218
+ # derivative), in the other case, we use the built-in auxiliary speed part
219
+ # of KanesMethod. The equations from each should be the same.
220
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
221
+ q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
222
+ u4, u5, f1, f2 = dynamicsymbols('u4, u5, f1, f2')
223
+ u4d, u5d = dynamicsymbols('u4, u5', 1)
224
+ r, m, g = symbols('r m g')
225
+
226
+ N = ReferenceFrame('N')
227
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
228
+ L = Y.orientnew('L', 'Axis', [q2, Y.x])
229
+ R = L.orientnew('R', 'Axis', [q3, L.y])
230
+ w_R_N_qd = R.ang_vel_in(N)
231
+ R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
232
+
233
+ C = Point('C')
234
+ C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
235
+ Dmc = C.locatenew('Dmc', r * L.z)
236
+ Dmc.v2pt_theory(C, N, R)
237
+ Dmc.a2pt_theory(C, N, R)
238
+
239
+ I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
240
+
241
+ kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
242
+
243
+ ForceList = [(Dmc, - m * g * Y.z), (C, f1 * L.x + f2 * (Y.z ^ L.x))]
244
+ BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
245
+ BodyList = [BodyD]
246
+
247
+ KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3, u4, u5],
248
+ kd_eqs=kd)
249
+ (fr, frstar) = KM.kanes_equations(BodyList, ForceList)
250
+ fr = fr.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
251
+ frstar = frstar.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
252
+
253
+ KM2 = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd,
254
+ u_auxiliary=[u4, u5])
255
+ (fr2, frstar2) = KM2.kanes_equations(BodyList, ForceList)
256
+ fr2 = fr2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
257
+ frstar2 = frstar2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
258
+
259
+ frstar.simplify()
260
+ frstar2.simplify()
261
+
262
+ assert (fr - fr2).expand() == Matrix([0, 0, 0, 0, 0])
263
+ assert (frstar - frstar2).expand() == Matrix([0, 0, 0, 0, 0])
264
+
265
+
266
+ def test_parallel_axis():
267
+ # This is for a 2 dof inverted pendulum on a cart.
268
+ # This tests the parallel axis code in KanesMethod. The inertia of the
269
+ # pendulum is defined about the hinge, not about the center of mass.
270
+
271
+ # Defining the constants and knowns of the system
272
+ gravity = symbols('g')
273
+ k, ls = symbols('k ls')
274
+ a, mA, mC = symbols('a mA mC')
275
+ F = dynamicsymbols('F')
276
+ Ix, Iy, Iz = symbols('Ix Iy Iz')
277
+
278
+ # Declaring the Generalized coordinates and speeds
279
+ q1, q2 = dynamicsymbols('q1 q2')
280
+ q1d, q2d = dynamicsymbols('q1 q2', 1)
281
+ u1, u2 = dynamicsymbols('u1 u2')
282
+ u1d, u2d = dynamicsymbols('u1 u2', 1)
283
+
284
+ # Creating reference frames
285
+ N = ReferenceFrame('N')
286
+ A = ReferenceFrame('A')
287
+
288
+ A.orient(N, 'Axis', [-q2, N.z])
289
+ A.set_ang_vel(N, -u2 * N.z)
290
+
291
+ # Origin of Newtonian reference frame
292
+ O = Point('O')
293
+
294
+ # Creating and Locating the positions of the cart, C, and the
295
+ # center of mass of the pendulum, A
296
+ C = O.locatenew('C', q1 * N.x)
297
+ Ao = C.locatenew('Ao', a * A.y)
298
+
299
+ # Defining velocities of the points
300
+ O.set_vel(N, 0)
301
+ C.set_vel(N, u1 * N.x)
302
+ Ao.v2pt_theory(C, N, A)
303
+ Cart = Particle('Cart', C, mC)
304
+ Pendulum = RigidBody('Pendulum', Ao, A, mA, (inertia(A, Ix, Iy, Iz), C))
305
+
306
+ # kinematical differential equations
307
+
308
+ kindiffs = [q1d - u1, q2d - u2]
309
+
310
+ bodyList = [Cart, Pendulum]
311
+
312
+ forceList = [(Ao, -N.y * gravity * mA),
313
+ (C, -N.y * gravity * mC),
314
+ (C, -N.x * k * (q1 - ls)),
315
+ (C, N.x * F)]
316
+
317
+ km = KanesMethod(N, [q1, q2], [u1, u2], kindiffs)
318
+ (fr, frstar) = km.kanes_equations(bodyList, forceList)
319
+ mm = km.mass_matrix_full
320
+ assert mm[3, 3] == Iz
321
+
322
+ def test_input_format():
323
+ # 1 dof problem from test_one_dof
324
+ q, u = dynamicsymbols('q u')
325
+ qd, ud = dynamicsymbols('q u', 1)
326
+ m, c, k = symbols('m c k')
327
+ N = ReferenceFrame('N')
328
+ P = Point('P')
329
+ P.set_vel(N, u * N.x)
330
+
331
+ kd = [qd - u]
332
+ FL = [(P, (-k * q - c * u) * N.x)]
333
+ pa = Particle('pa', P, m)
334
+ BL = [pa]
335
+
336
+ KM = KanesMethod(N, [q], [u], kd)
337
+ # test for input format kane.kanes_equations((body1, body2, particle1))
338
+ assert KM.kanes_equations(BL)[0] == Matrix([0])
339
+ # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2))
340
+ assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0])
341
+ # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None)
342
+ assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0])
343
+ # test for input format kane.kanes_equations(bodies=(body1, body 2))
344
+ assert KM.kanes_equations(BL)[0] == Matrix([0])
345
+ # test for input format kane.kanes_equations(bodies=(body1, body2), loads=[])
346
+ assert KM.kanes_equations(BL, [])[0] == Matrix([0])
347
+ # test for error raised when a wrong force list (in this case a string) is provided
348
+ raises(ValueError, lambda: KM._form_fr('bad input'))
349
+
350
+ # 1 dof problem from test_one_dof with FL & BL in instance
351
+ KM = KanesMethod(N, [q], [u], kd, bodies=BL, forcelist=FL)
352
+ assert KM.kanes_equations()[0] == Matrix([-c*u - k*q])
353
+
354
+ # 2 dof problem from test_two_dof
355
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
356
+ q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
357
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
358
+ N = ReferenceFrame('N')
359
+ P1 = Point('P1')
360
+ P2 = Point('P2')
361
+ P1.set_vel(N, u1 * N.x)
362
+ P2.set_vel(N, (u1 + u2) * N.x)
363
+ kd = [q1d - u1, q2d - u2]
364
+
365
+ FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
366
+ q2 - c2 * u2) * N.x))
367
+ pa1 = Particle('pa1', P1, m)
368
+ pa2 = Particle('pa2', P2, m)
369
+ BL = (pa1, pa2)
370
+
371
+ KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
372
+ # test for input format
373
+ # kane.kanes_equations((body1, body2), (load1, load2))
374
+ KM.kanes_equations(BL, FL)
375
+ MM = KM.mass_matrix
376
+ forcing = KM.forcing
377
+ rhs = MM.inv() * forcing
378
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
379
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
380
+ c2 * u2) / m)
381
+
382
+
383
+ def test_implicit_kinematics():
384
+ # Test that implicit kinematics can handle complicated
385
+ # equations that explicit form struggles with
386
+ # See https://github.com/sympy/sympy/issues/22626
387
+
388
+ # Inertial frame
389
+ NED = ReferenceFrame('NED')
390
+ NED_o = Point('NED_o')
391
+ NED_o.set_vel(NED, 0)
392
+
393
+ # body frame
394
+ q_att = dynamicsymbols('lambda_0:4', real=True)
395
+ B = NED.orientnew('B', 'Quaternion', q_att)
396
+
397
+ # Generalized coordinates
398
+ q_pos = dynamicsymbols('B_x:z')
399
+ B_cm = NED_o.locatenew('B_cm', q_pos[0]*B.x + q_pos[1]*B.y + q_pos[2]*B.z)
400
+
401
+ q_ind = q_att[1:] + q_pos
402
+ q_dep = [q_att[0]]
403
+
404
+ kinematic_eqs = []
405
+
406
+ # Generalized velocities
407
+ B_ang_vel = B.ang_vel_in(NED)
408
+ P, Q, R = dynamicsymbols('P Q R')
409
+ B.set_ang_vel(NED, P*B.x + Q*B.y + R*B.z)
410
+
411
+ B_ang_vel_kd = (B.ang_vel_in(NED) - B_ang_vel).simplify()
412
+
413
+ # Equating the two gives us the kinematic equation
414
+ kinematic_eqs += [
415
+ B_ang_vel_kd & B.x,
416
+ B_ang_vel_kd & B.y,
417
+ B_ang_vel_kd & B.z
418
+ ]
419
+
420
+ B_cm_vel = B_cm.vel(NED)
421
+ U, V, W = dynamicsymbols('U V W')
422
+ B_cm.set_vel(NED, U*B.x + V*B.y + W*B.z)
423
+
424
+ # Compute the velocity of the point using the two methods
425
+ B_ref_vel_kd = (B_cm.vel(NED) - B_cm_vel)
426
+
427
+ # taking dot product with unit vectors to get kinematic equations
428
+ # relating body coordinates and velocities
429
+
430
+ # Note, there is a choice to dot with NED.xyz here. That makes
431
+ # the implicit form have some bigger terms but is still fine, the
432
+ # explicit form still struggles though
433
+ kinematic_eqs += [
434
+ B_ref_vel_kd & B.x,
435
+ B_ref_vel_kd & B.y,
436
+ B_ref_vel_kd & B.z,
437
+ ]
438
+
439
+ u_ind = [U, V, W, P, Q, R]
440
+
441
+ # constraints
442
+ q_att_vec = Matrix(q_att)
443
+ config_cons = [(q_att_vec.T*q_att_vec)[0] - 1] #unit norm
444
+ kinematic_eqs = kinematic_eqs + [(q_att_vec.T * q_att_vec.diff())[0]]
445
+
446
+ try:
447
+ KM = KanesMethod(NED, q_ind, u_ind,
448
+ q_dependent= q_dep,
449
+ kd_eqs = kinematic_eqs,
450
+ configuration_constraints = config_cons,
451
+ velocity_constraints= [],
452
+ u_dependent= [], #no dependent speeds
453
+ u_auxiliary = [], # No auxiliary speeds
454
+ explicit_kinematics = False # implicit kinematics
455
+ )
456
+ except Exception as e:
457
+ # symengine struggles with these kinematic equations
458
+ if USE_SYMENGINE and 'Matrix is rank deficient' in str(e):
459
+ return
460
+ else:
461
+ raise e
462
+
463
+ # mass and inertia dyadic relative to CM
464
+ M_B = symbols('M_B')
465
+ J_B = inertia(B, *[S(f'J_B_{ax}')*(1 if ax[0] == ax[1] else -1)
466
+ for ax in ['xx', 'yy', 'zz', 'xy', 'yz', 'xz']])
467
+ J_B = J_B.subs({S('J_B_xy'): 0, S('J_B_yz'): 0})
468
+ RB = RigidBody('RB', B_cm, B, M_B, (J_B, B_cm))
469
+
470
+ rigid_bodies = [RB]
471
+ # Forces
472
+ force_list = [
473
+ #gravity pointing down
474
+ (RB.masscenter, RB.mass*S('g')*NED.z),
475
+ #generic forces and torques in body frame(inputs)
476
+ (RB.frame, dynamicsymbols('T_z')*B.z),
477
+ (RB.masscenter, dynamicsymbols('F_z')*B.z)
478
+ ]
479
+
480
+ KM.kanes_equations(rigid_bodies, force_list)
481
+
482
+ # Expecting implicit form to be less than 5% of the flops
483
+ n_ops_implicit = sum(
484
+ [x.count_ops() for x in KM.forcing_full] +
485
+ [x.count_ops() for x in KM.mass_matrix_full]
486
+ )
487
+ # Save implicit kinematic matrices to use later
488
+ mass_matrix_kin_implicit = KM.mass_matrix_kin
489
+ forcing_kin_implicit = KM.forcing_kin
490
+
491
+ KM.explicit_kinematics = True
492
+ n_ops_explicit = sum(
493
+ [x.count_ops() for x in KM.forcing_full] +
494
+ [x.count_ops() for x in KM.mass_matrix_full]
495
+ )
496
+ forcing_kin_explicit = KM.forcing_kin
497
+
498
+ assert n_ops_implicit / n_ops_explicit < .05
499
+
500
+ # Ideally we would check that implicit and explicit equations give the same result as done in test_one_dof
501
+ # But the whole raison-d'etre of the implicit equations is to deal with problems such
502
+ # as this one where the explicit form is too complicated to handle, especially the angular part
503
+ # (i.e. tests would be too slow)
504
+ # Instead, we check that the kinematic equations are correct using more fundamental tests:
505
+ #
506
+ # (1) that we recover the kinematic equations we have provided
507
+ assert (mass_matrix_kin_implicit * KM.q.diff() - forcing_kin_implicit) == Matrix(kinematic_eqs)
508
+
509
+ # (2) that rate of quaternions matches what 'textbook' solutions give
510
+ # Note that we just use the explicit kinematics for the linear velocities
511
+ # as they are not as complicated as the angular ones
512
+ qdot_candidate = forcing_kin_explicit
513
+
514
+ quat_dot_textbook = Matrix([
515
+ [0, -P, -Q, -R],
516
+ [P, 0, R, -Q],
517
+ [Q, -R, 0, P],
518
+ [R, Q, -P, 0],
519
+ ]) * q_att_vec / 2
520
+
521
+ # Again, if we don't use this "textbook" solution
522
+ # sympy will struggle to deal with the terms related to quaternion rates
523
+ # due to the number of operations involved
524
+ qdot_candidate[-1] = quat_dot_textbook[0] # lambda_0, note the [-1] as sympy's Kane puts the dependent coordinate last
525
+ qdot_candidate[0] = quat_dot_textbook[1] # lambda_1
526
+ qdot_candidate[1] = quat_dot_textbook[2] # lambda_2
527
+ qdot_candidate[2] = quat_dot_textbook[3] # lambda_3
528
+
529
+ # sub the config constraint in the candidate solution and compare to the implicit rhs
530
+ lambda_0_sol = solve(config_cons[0], q_att_vec[0])[1]
531
+ lhs_candidate = simplify(mass_matrix_kin_implicit * qdot_candidate).subs({q_att_vec[0]: lambda_0_sol})
532
+ assert lhs_candidate == forcing_kin_implicit
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane2.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import cos, Matrix, sin, zeros, tan, pi, symbols
2
+ from sympy.simplify.simplify import simplify
3
+ from sympy.simplify.trigsimp import trigsimp
4
+ from sympy.solvers.solvers import solve
5
+ from sympy.physics.mechanics import (cross, dot, dynamicsymbols,
6
+ find_dynamicsymbols, KanesMethod, inertia,
7
+ inertia_of_point_mass, Point,
8
+ ReferenceFrame, RigidBody)
9
+
10
+
11
+ def test_aux_dep():
12
+ # This test is about rolling disc dynamics, comparing the results found
13
+ # with KanesMethod to those found when deriving the equations "manually"
14
+ # with SymPy.
15
+ # The terms Fr, Fr*, and Fr*_steady are all compared between the two
16
+ # methods. Here, Fr*_steady refers to the generalized inertia forces for an
17
+ # equilibrium configuration.
18
+ # Note: comparing to the test of test_rolling_disc() in test_kane.py, this
19
+ # test also tests auxiliary speeds and configuration and motion constraints
20
+ #, seen in the generalized dependent coordinates q[3], and depend speeds
21
+ # u[3], u[4] and u[5].
22
+
23
+
24
+ # First, manual derivation of Fr, Fr_star, Fr_star_steady.
25
+
26
+ # Symbols for time and constant parameters.
27
+ # Symbols for contact forces: Fx, Fy, Fz.
28
+ t, r, m, g, I, J = symbols('t r m g I J')
29
+ Fx, Fy, Fz = symbols('Fx Fy Fz')
30
+
31
+ # Configuration variables and their time derivatives:
32
+ # q[0] -- yaw
33
+ # q[1] -- lean
34
+ # q[2] -- spin
35
+ # q[3] -- dot(-r*B.z, A.z) -- distance from ground plane to disc center in
36
+ # A.z direction
37
+ # Generalized speeds and their time derivatives:
38
+ # u[0] -- disc angular velocity component, disc fixed x direction
39
+ # u[1] -- disc angular velocity component, disc fixed y direction
40
+ # u[2] -- disc angular velocity component, disc fixed z direction
41
+ # u[3] -- disc velocity component, A.x direction
42
+ # u[4] -- disc velocity component, A.y direction
43
+ # u[5] -- disc velocity component, A.z direction
44
+ # Auxiliary generalized speeds:
45
+ # ua[0] -- contact point auxiliary generalized speed, A.x direction
46
+ # ua[1] -- contact point auxiliary generalized speed, A.y direction
47
+ # ua[2] -- contact point auxiliary generalized speed, A.z direction
48
+ q = dynamicsymbols('q:4')
49
+ qd = [qi.diff(t) for qi in q]
50
+ u = dynamicsymbols('u:6')
51
+ ud = [ui.diff(t) for ui in u]
52
+ ud_zero = dict(zip(ud, [0.]*len(ud)))
53
+ ua = dynamicsymbols('ua:3')
54
+ ua_zero = dict(zip(ua, [0.]*len(ua))) # noqa:F841
55
+
56
+ # Reference frames:
57
+ # Yaw intermediate frame: A.
58
+ # Lean intermediate frame: B.
59
+ # Disc fixed frame: C.
60
+ N = ReferenceFrame('N')
61
+ A = N.orientnew('A', 'Axis', [q[0], N.z])
62
+ B = A.orientnew('B', 'Axis', [q[1], A.x])
63
+ C = B.orientnew('C', 'Axis', [q[2], B.y])
64
+
65
+ # Angular velocity and angular acceleration of disc fixed frame
66
+ # u[0], u[1] and u[2] are generalized independent speeds.
67
+ C.set_ang_vel(N, u[0]*B.x + u[1]*B.y + u[2]*B.z)
68
+ C.set_ang_acc(N, C.ang_vel_in(N).diff(t, B)
69
+ + cross(B.ang_vel_in(N), C.ang_vel_in(N)))
70
+
71
+ # Velocity and acceleration of points:
72
+ # Disc-ground contact point: P.
73
+ # Center of disc: O, defined from point P with depend coordinate: q[3]
74
+ # u[3], u[4] and u[5] are generalized dependent speeds.
75
+ P = Point('P')
76
+ P.set_vel(N, ua[0]*A.x + ua[1]*A.y + ua[2]*A.z)
77
+ O = P.locatenew('O', q[3]*A.z + r*sin(q[1])*A.y)
78
+ O.set_vel(N, u[3]*A.x + u[4]*A.y + u[5]*A.z)
79
+ O.set_acc(N, O.vel(N).diff(t, A) + cross(A.ang_vel_in(N), O.vel(N)))
80
+
81
+ # Kinematic differential equations:
82
+ # Two equalities: one is w_c_n_qd = C.ang_vel_in(N) in three coordinates
83
+ # directions of B, for qd0, qd1 and qd2.
84
+ # the other is v_o_n_qd = O.vel(N) in A.z direction for qd3.
85
+ # Then, solve for dq/dt's in terms of u's: qd_kd.
86
+ w_c_n_qd = qd[0]*A.z + qd[1]*B.x + qd[2]*B.y
87
+ v_o_n_qd = O.pos_from(P).diff(t, A) + cross(A.ang_vel_in(N), O.pos_from(P))
88
+ kindiffs = Matrix([dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B] +
89
+ [dot(v_o_n_qd - O.vel(N), A.z)])
90
+ qd_kd = solve(kindiffs, qd) # noqa:F841
91
+
92
+ # Values of generalized speeds during a steady turn for later substitution
93
+ # into the Fr_star_steady.
94
+ steady_conditions = solve(kindiffs.subs({qd[1] : 0, qd[3] : 0}), u)
95
+ steady_conditions.update({qd[1] : 0, qd[3] : 0})
96
+
97
+ # Partial angular velocities and velocities.
98
+ partial_w_C = [C.ang_vel_in(N).diff(ui, N) for ui in u + ua]
99
+ partial_v_O = [O.vel(N).diff(ui, N) for ui in u + ua]
100
+ partial_v_P = [P.vel(N).diff(ui, N) for ui in u + ua]
101
+
102
+ # Configuration constraint: f_c, the projection of radius r in A.z direction
103
+ # is q[3].
104
+ # Velocity constraints: f_v, for u3, u4 and u5.
105
+ # Acceleration constraints: f_a.
106
+ f_c = Matrix([dot(-r*B.z, A.z) - q[3]])
107
+ f_v = Matrix([dot(O.vel(N) - (P.vel(N) + cross(C.ang_vel_in(N),
108
+ O.pos_from(P))), ai).expand() for ai in A])
109
+ v_o_n = cross(C.ang_vel_in(N), O.pos_from(P))
110
+ a_o_n = v_o_n.diff(t, A) + cross(A.ang_vel_in(N), v_o_n)
111
+ f_a = Matrix([dot(O.acc(N) - a_o_n, ai) for ai in A]) # noqa:F841
112
+
113
+ # Solve for constraint equations in the form of
114
+ # u_dependent = A_rs * [u_i; u_aux].
115
+ # First, obtain constraint coefficient matrix: M_v * [u; ua] = 0;
116
+ # Second, taking u[0], u[1], u[2] as independent,
117
+ # taking u[3], u[4], u[5] as dependent,
118
+ # rearranging the matrix of M_v to be A_rs for u_dependent.
119
+ # Third, u_aux ==0 for u_dep, and resulting dictionary of u_dep_dict.
120
+ M_v = zeros(3, 9)
121
+ for i in range(3):
122
+ for j, ui in enumerate(u + ua):
123
+ M_v[i, j] = f_v[i].diff(ui)
124
+
125
+ M_v_i = M_v[:, :3]
126
+ M_v_d = M_v[:, 3:6]
127
+ M_v_aux = M_v[:, 6:]
128
+ M_v_i_aux = M_v_i.row_join(M_v_aux)
129
+ A_rs = - M_v_d.inv() * M_v_i_aux
130
+
131
+ u_dep = A_rs[:, :3] * Matrix(u[:3])
132
+ u_dep_dict = dict(zip(u[3:], u_dep))
133
+
134
+ # Active forces: F_O acting on point O; F_P acting on point P.
135
+ # Generalized active forces (unconstrained): Fr_u = F_point * pv_point.
136
+ F_O = m*g*A.z
137
+ F_P = Fx * A.x + Fy * A.y + Fz * A.z
138
+ Fr_u = Matrix([dot(F_O, pv_o) + dot(F_P, pv_p) for pv_o, pv_p in
139
+ zip(partial_v_O, partial_v_P)])
140
+
141
+ # Inertia force: R_star_O.
142
+ # Inertia of disc: I_C_O, where J is a inertia component about principal axis.
143
+ # Inertia torque: T_star_C.
144
+ # Generalized inertia forces (unconstrained): Fr_star_u.
145
+ R_star_O = -m*O.acc(N)
146
+ I_C_O = inertia(B, I, J, I)
147
+ T_star_C = -(dot(I_C_O, C.ang_acc_in(N)) \
148
+ + cross(C.ang_vel_in(N), dot(I_C_O, C.ang_vel_in(N))))
149
+ Fr_star_u = Matrix([dot(R_star_O, pv) + dot(T_star_C, pav) for pv, pav in
150
+ zip(partial_v_O, partial_w_C)])
151
+
152
+ # Form nonholonomic Fr: Fr_c, and nonholonomic Fr_star: Fr_star_c.
153
+ # Also, nonholonomic Fr_star in steady turning condition: Fr_star_steady.
154
+ Fr_c = Fr_u[:3, :].col_join(Fr_u[6:, :]) + A_rs.T * Fr_u[3:6, :]
155
+ Fr_star_c = Fr_star_u[:3, :].col_join(Fr_star_u[6:, :])\
156
+ + A_rs.T * Fr_star_u[3:6, :]
157
+ Fr_star_steady = Fr_star_c.subs(ud_zero).subs(u_dep_dict)\
158
+ .subs(steady_conditions).subs({q[3]: -r*cos(q[1])}).expand()
159
+
160
+
161
+ # Second, using KaneMethod in mechanics for fr, frstar and frstar_steady.
162
+
163
+ # Rigid Bodies: disc, with inertia I_C_O.
164
+ iner_tuple = (I_C_O, O)
165
+ disc = RigidBody('disc', O, C, m, iner_tuple)
166
+ bodyList = [disc]
167
+
168
+ # Generalized forces: Gravity: F_o; Auxiliary forces: F_p.
169
+ F_o = (O, F_O)
170
+ F_p = (P, F_P)
171
+ forceList = [F_o, F_p]
172
+
173
+ # KanesMethod.
174
+ kane = KanesMethod(
175
+ N, q_ind= q[:3], u_ind= u[:3], kd_eqs=kindiffs,
176
+ q_dependent=q[3:], configuration_constraints = f_c,
177
+ u_dependent=u[3:], velocity_constraints= f_v,
178
+ u_auxiliary=ua
179
+ )
180
+
181
+ # fr, frstar, frstar_steady and kdd(kinematic differential equations).
182
+ (fr, frstar)= kane.kanes_equations(bodyList, forceList)
183
+ frstar_steady = frstar.subs(ud_zero).subs(u_dep_dict).subs(steady_conditions)\
184
+ .subs({q[3]: -r*cos(q[1])}).expand()
185
+ kdd = kane.kindiffdict()
186
+
187
+ assert Matrix(Fr_c).expand() == fr.expand()
188
+ assert Matrix(Fr_star_c.subs(kdd)).expand() == frstar.expand()
189
+ assert (simplify(Matrix(Fr_star_steady).expand()) ==
190
+ simplify(frstar_steady.expand()))
191
+
192
+ syms_in_forcing = find_dynamicsymbols(kane.forcing)
193
+ for qdi in qd:
194
+ assert qdi not in syms_in_forcing
195
+
196
+
197
+ def test_non_central_inertia():
198
+ # This tests that the calculation of Fr* does not depend the point
199
+ # about which the inertia of a rigid body is defined. This test solves
200
+ # exercises 8.12, 8.17 from Kane 1985.
201
+
202
+ # Declare symbols
203
+ q1, q2, q3 = dynamicsymbols('q1:4')
204
+ q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
205
+ u1, u2, u3, u4, u5 = dynamicsymbols('u1:6')
206
+ u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
207
+ a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
208
+ Q1, Q2, Q3 = symbols('Q1, Q2 Q3')
209
+ IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
210
+
211
+ # Reference Frames
212
+ F = ReferenceFrame('F')
213
+ P = F.orientnew('P', 'axis', [-theta, F.y])
214
+ A = P.orientnew('A', 'axis', [q1, P.x])
215
+ A.set_ang_vel(F, u1*A.x + u3*A.z)
216
+ # define frames for wheels
217
+ B = A.orientnew('B', 'axis', [q2, A.z])
218
+ C = A.orientnew('C', 'axis', [q3, A.z])
219
+ B.set_ang_vel(A, u4 * A.z)
220
+ C.set_ang_vel(A, u5 * A.z)
221
+
222
+ # define points D, S*, Q on frame A and their velocities
223
+ pD = Point('D')
224
+ pD.set_vel(A, 0)
225
+ # u3 will not change v_D_F since wheels are still assumed to roll without slip.
226
+ pD.set_vel(F, u2 * A.y)
227
+
228
+ pS_star = pD.locatenew('S*', e*A.y)
229
+ pQ = pD.locatenew('Q', f*A.y - R*A.x)
230
+ for p in [pS_star, pQ]:
231
+ p.v2pt_theory(pD, F, A)
232
+
233
+ # masscenters of bodies A, B, C
234
+ pA_star = pD.locatenew('A*', a*A.y)
235
+ pB_star = pD.locatenew('B*', b*A.z)
236
+ pC_star = pD.locatenew('C*', -b*A.z)
237
+ for p in [pA_star, pB_star, pC_star]:
238
+ p.v2pt_theory(pD, F, A)
239
+
240
+ # points of B, C touching the plane P
241
+ pB_hat = pB_star.locatenew('B^', -R*A.x)
242
+ pC_hat = pC_star.locatenew('C^', -R*A.x)
243
+ pB_hat.v2pt_theory(pB_star, F, B)
244
+ pC_hat.v2pt_theory(pC_star, F, C)
245
+
246
+ # the velocities of B^, C^ are zero since B, C are assumed to roll without slip
247
+ kde = [q1d - u1, q2d - u4, q3d - u5]
248
+ vc = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
249
+
250
+ # inertias of bodies A, B, C
251
+ # IA22, IA23, IA33 are not specified in the problem statement, but are
252
+ # necessary to define an inertia object. Although the values of
253
+ # IA22, IA23, IA33 are not known in terms of the variables given in the
254
+ # problem statement, they do not appear in the general inertia terms.
255
+ inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
256
+ inertia_B = inertia(B, K, K, J)
257
+ inertia_C = inertia(C, K, K, J)
258
+
259
+ # define the rigid bodies A, B, C
260
+ rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
261
+ rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
262
+ rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
263
+
264
+ km = KanesMethod(F, q_ind=[q1, q2, q3], u_ind=[u1, u2], kd_eqs=kde,
265
+ u_dependent=[u4, u5], velocity_constraints=vc,
266
+ u_auxiliary=[u3])
267
+
268
+ forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
269
+ bodies = [rbA, rbB, rbC]
270
+ fr, fr_star = km.kanes_equations(bodies, forces)
271
+ vc_map = solve(vc, [u4, u5])
272
+
273
+ # KanesMethod returns the negative of Fr, Fr* as defined in Kane1985.
274
+ fr_star_expected = Matrix([
275
+ -(IA + 2*J*b**2/R**2 + 2*K +
276
+ mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
277
+ -(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
278
+ 0])
279
+ t = trigsimp(fr_star.subs(vc_map).subs({u3: 0})).doit().expand()
280
+ assert ((fr_star_expected - t).expand() == zeros(3, 1))
281
+
282
+ # define inertias of rigid bodies A, B, C about point D
283
+ # I_S/O = I_S/S* + I_S*/O
284
+ bodies2 = []
285
+ for rb, I_star in zip([rbA, rbB, rbC], [inertia_A, inertia_B, inertia_C]):
286
+ I = I_star + inertia_of_point_mass(rb.mass,
287
+ rb.masscenter.pos_from(pD),
288
+ rb.frame)
289
+ bodies2.append(RigidBody('', rb.masscenter, rb.frame, rb.mass,
290
+ (I, pD)))
291
+ fr2, fr_star2 = km.kanes_equations(bodies2, forces)
292
+
293
+ t = trigsimp(fr_star2.subs(vc_map).subs({u3: 0})).doit()
294
+ assert (fr_star_expected - t).expand() == zeros(3, 1)
295
+
296
+ def test_sub_qdot():
297
+ # This test solves exercises 8.12, 8.17 from Kane 1985 and defines
298
+ # some velocities in terms of q, qdot.
299
+
300
+ ## --- Declare symbols ---
301
+ q1, q2, q3 = dynamicsymbols('q1:4')
302
+ q1d, q2d, q3d = dynamicsymbols('q1:4', level=1)
303
+ u1, u2, u3 = dynamicsymbols('u1:4')
304
+ u_prime, R, M, g, e, f, theta = symbols('u\' R, M, g, e, f, theta')
305
+ a, b, mA, mB, IA, J, K, t = symbols('a b mA mB IA J K t')
306
+ IA22, IA23, IA33 = symbols('IA22 IA23 IA33')
307
+ Q1, Q2, Q3 = symbols('Q1 Q2 Q3')
308
+
309
+ # --- Reference Frames ---
310
+ F = ReferenceFrame('F')
311
+ P = F.orientnew('P', 'axis', [-theta, F.y])
312
+ A = P.orientnew('A', 'axis', [q1, P.x])
313
+ A.set_ang_vel(F, u1*A.x + u3*A.z)
314
+ # define frames for wheels
315
+ B = A.orientnew('B', 'axis', [q2, A.z])
316
+ C = A.orientnew('C', 'axis', [q3, A.z])
317
+
318
+ ## --- define points D, S*, Q on frame A and their velocities ---
319
+ pD = Point('D')
320
+ pD.set_vel(A, 0)
321
+ # u3 will not change v_D_F since wheels are still assumed to roll w/o slip
322
+ pD.set_vel(F, u2 * A.y)
323
+
324
+ pS_star = pD.locatenew('S*', e*A.y)
325
+ pQ = pD.locatenew('Q', f*A.y - R*A.x)
326
+ # masscenters of bodies A, B, C
327
+ pA_star = pD.locatenew('A*', a*A.y)
328
+ pB_star = pD.locatenew('B*', b*A.z)
329
+ pC_star = pD.locatenew('C*', -b*A.z)
330
+ for p in [pS_star, pQ, pA_star, pB_star, pC_star]:
331
+ p.v2pt_theory(pD, F, A)
332
+
333
+ # points of B, C touching the plane P
334
+ pB_hat = pB_star.locatenew('B^', -R*A.x)
335
+ pC_hat = pC_star.locatenew('C^', -R*A.x)
336
+ pB_hat.v2pt_theory(pB_star, F, B)
337
+ pC_hat.v2pt_theory(pC_star, F, C)
338
+
339
+ # --- relate qdot, u ---
340
+ # the velocities of B^, C^ are zero since B, C are assumed to roll w/o slip
341
+ kde = [dot(p.vel(F), A.y) for p in [pB_hat, pC_hat]]
342
+ kde += [u1 - q1d]
343
+ kde_map = solve(kde, [q1d, q2d, q3d])
344
+ for k, v in list(kde_map.items()):
345
+ kde_map[k.diff(t)] = v.diff(t)
346
+
347
+ # inertias of bodies A, B, C
348
+ # IA22, IA23, IA33 are not specified in the problem statement, but are
349
+ # necessary to define an inertia object. Although the values of
350
+ # IA22, IA23, IA33 are not known in terms of the variables given in the
351
+ # problem statement, they do not appear in the general inertia terms.
352
+ inertia_A = inertia(A, IA, IA22, IA33, 0, IA23, 0)
353
+ inertia_B = inertia(B, K, K, J)
354
+ inertia_C = inertia(C, K, K, J)
355
+
356
+ # define the rigid bodies A, B, C
357
+ rbA = RigidBody('rbA', pA_star, A, mA, (inertia_A, pA_star))
358
+ rbB = RigidBody('rbB', pB_star, B, mB, (inertia_B, pB_star))
359
+ rbC = RigidBody('rbC', pC_star, C, mB, (inertia_C, pC_star))
360
+
361
+ ## --- use kanes method ---
362
+ km = KanesMethod(F, [q1, q2, q3], [u1, u2], kd_eqs=kde, u_auxiliary=[u3])
363
+
364
+ forces = [(pS_star, -M*g*F.x), (pQ, Q1*A.x + Q2*A.y + Q3*A.z)]
365
+ bodies = [rbA, rbB, rbC]
366
+
367
+ # Q2 = -u_prime * u2 * Q1 / sqrt(u2**2 + f**2 * u1**2)
368
+ # -u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2) = R / Q1 * Q2
369
+ fr_expected = Matrix([
370
+ f*Q3 + M*g*e*sin(theta)*cos(q1),
371
+ Q2 + M*g*sin(theta)*sin(q1),
372
+ e*M*g*cos(theta) - Q1*f - Q2*R])
373
+ #Q1 * (f - u_prime * R * u2 / sqrt(u2**2 + f**2 * u1**2)))])
374
+ fr_star_expected = Matrix([
375
+ -(IA + 2*J*b**2/R**2 + 2*K +
376
+ mA*a**2 + 2*mB*b**2) * u1.diff(t) - mA*a*u1*u2,
377
+ -(mA + 2*mB +2*J/R**2) * u2.diff(t) + mA*a*u1**2,
378
+ 0])
379
+
380
+ fr, fr_star = km.kanes_equations(bodies, forces)
381
+ assert (fr.expand() == fr_expected.expand())
382
+ assert ((fr_star_expected - trigsimp(fr_star)).expand() == zeros(3, 1))
383
+
384
+ def test_sub_qdot2():
385
+ # This test solves exercises 8.3 from Kane 1985 and defines
386
+ # all velocities in terms of q, qdot. We check that the generalized active
387
+ # forces are correctly computed if u terms are only defined in the
388
+ # kinematic differential equations.
389
+ #
390
+ # This functionality was added in PR 8948. Without qdot/u substitution, the
391
+ # KanesMethod constructor will fail during the constraint initialization as
392
+ # the B matrix will be poorly formed and inversion of the dependent part
393
+ # will fail.
394
+
395
+ g, m, Px, Py, Pz, R, t = symbols('g m Px Py Pz R t')
396
+ q = dynamicsymbols('q:5')
397
+ qd = dynamicsymbols('q:5', level=1)
398
+ u = dynamicsymbols('u:5')
399
+
400
+ ## Define inertial, intermediate, and rigid body reference frames
401
+ A = ReferenceFrame('A')
402
+ B_prime = A.orientnew('B_prime', 'Axis', [q[0], A.z])
403
+ B = B_prime.orientnew('B', 'Axis', [pi/2 - q[1], B_prime.x])
404
+ C = B.orientnew('C', 'Axis', [q[2], B.z])
405
+
406
+ ## Define points of interest and their velocities
407
+ pO = Point('O')
408
+ pO.set_vel(A, 0)
409
+
410
+ # R is the point in plane H that comes into contact with disk C.
411
+ pR = pO.locatenew('R', q[3]*A.x + q[4]*A.y)
412
+ pR.set_vel(A, pR.pos_from(pO).diff(t, A))
413
+ pR.set_vel(B, 0)
414
+
415
+ # C^ is the point in disk C that comes into contact with plane H.
416
+ pC_hat = pR.locatenew('C^', 0)
417
+ pC_hat.set_vel(C, 0)
418
+
419
+ # C* is the point at the center of disk C.
420
+ pCs = pC_hat.locatenew('C*', R*B.y)
421
+ pCs.set_vel(C, 0)
422
+ pCs.set_vel(B, 0)
423
+
424
+ # calculate velocites of points C* and C^ in frame A
425
+ pCs.v2pt_theory(pR, A, B) # points C* and R are fixed in frame B
426
+ pC_hat.v2pt_theory(pCs, A, C) # points C* and C^ are fixed in frame C
427
+
428
+ ## Define forces on each point of the system
429
+ R_C_hat = Px*A.x + Py*A.y + Pz*A.z
430
+ R_Cs = -m*g*A.z
431
+ forces = [(pC_hat, R_C_hat), (pCs, R_Cs)]
432
+
433
+ ## Define kinematic differential equations
434
+ # let ui = omega_C_A & bi (i = 1, 2, 3)
435
+ # u4 = qd4, u5 = qd5
436
+ u_expr = [C.ang_vel_in(A) & uv for uv in B]
437
+ u_expr += qd[3:]
438
+ kde = [ui - e for ui, e in zip(u, u_expr)]
439
+ km1 = KanesMethod(A, q, u, kde)
440
+ fr1, _ = km1.kanes_equations([], forces)
441
+
442
+ ## Calculate generalized active forces if we impose the condition that the
443
+ # disk C is rolling without slipping
444
+ u_indep = u[:3]
445
+ u_dep = list(set(u) - set(u_indep))
446
+ vc = [pC_hat.vel(A) & uv for uv in [A.x, A.y]]
447
+ km2 = KanesMethod(A, q, u_indep, kde,
448
+ u_dependent=u_dep, velocity_constraints=vc)
449
+ fr2, _ = km2.kanes_equations([], forces)
450
+
451
+ fr1_expected = Matrix([
452
+ -R*g*m*sin(q[1]),
453
+ -R*(Px*cos(q[0]) + Py*sin(q[0]))*tan(q[1]),
454
+ R*(Px*cos(q[0]) + Py*sin(q[0])),
455
+ Px,
456
+ Py])
457
+ fr2_expected = Matrix([
458
+ -R*g*m*sin(q[1]),
459
+ 0,
460
+ 0])
461
+ assert (trigsimp(fr1.expand()) == trigsimp(fr1_expected.expand()))
462
+ assert (trigsimp(fr2.expand()) == trigsimp(fr2_expected.expand()))
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane3.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.evalf import evalf
2
+ from sympy.core.numbers import pi
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.trigonometric import acos, sin, cos
6
+ from sympy.matrices.dense import Matrix
7
+ from sympy.physics.mechanics import (ReferenceFrame, dynamicsymbols,
8
+ KanesMethod, inertia, msubs, Point, RigidBody, dot)
9
+ from sympy.testing.pytest import slow, ON_CI, skip
10
+
11
+
12
+ @slow
13
+ def test_bicycle():
14
+ if ON_CI:
15
+ skip("Too slow for CI.")
16
+ # Code to get equations of motion for a bicycle modeled as in:
17
+ # J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized
18
+ # dynamics equations for the balance and steer of a bicycle: a benchmark
19
+ # and review. Proceedings of The Royal Society (2007) 463, 1955-1982
20
+ # doi: 10.1098/rspa.2007.1857
21
+
22
+ # Note that this code has been crudely ported from Autolev, which is the
23
+ # reason for some of the unusual naming conventions. It was purposefully as
24
+ # similar as possible in order to aide debugging.
25
+
26
+ # Declare Coordinates & Speeds
27
+ # Simple definitions for qdots - qd = u
28
+ # Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame
29
+ # ang. rate (spinning motion), frame ang. rate (pitching motion), steering
30
+ # frame ang. rate, and front wheel ang. rate (spinning motion).
31
+ # Wheel positions are ignorable coordinates, so they are not introduced.
32
+ q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5')
33
+ q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1)
34
+ u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6')
35
+ u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1)
36
+
37
+ # Declare System's Parameters
38
+ WFrad, WRrad, htangle, forkoffset = symbols('WFrad WRrad htangle forkoffset')
39
+ forklength, framelength, forkcg1 = symbols('forklength framelength forkcg1')
40
+ forkcg3, framecg1, framecg3, Iwr11 = symbols('forkcg3 framecg1 framecg3 Iwr11')
41
+ Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11')
42
+ Iframe22, Iframe33, Iframe31, Ifork11 = symbols('Iframe22 Iframe33 Iframe31 Ifork11')
43
+ Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g')
44
+ mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr')
45
+
46
+ # Set up reference frames for the system
47
+ # N - inertial
48
+ # Y - yaw
49
+ # R - roll
50
+ # WR - rear wheel, rotation angle is ignorable coordinate so not oriented
51
+ # Frame - bicycle frame
52
+ # TempFrame - statically rotated frame for easier reference inertia definition
53
+ # Fork - bicycle fork
54
+ # TempFork - statically rotated frame for easier reference inertia definition
55
+ # WF - front wheel, again posses a ignorable coordinate
56
+ N = ReferenceFrame('N')
57
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
58
+ R = Y.orientnew('R', 'Axis', [q2, Y.x])
59
+ Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y])
60
+ WR = ReferenceFrame('WR')
61
+ TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y])
62
+ Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x])
63
+ TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y])
64
+ WF = ReferenceFrame('WF')
65
+
66
+ # Kinematics of the Bicycle First block of code is forming the positions of
67
+ # the relevant points
68
+ # rear wheel contact -> rear wheel mass center -> frame mass center +
69
+ # frame/fork connection -> fork mass center + front wheel mass center ->
70
+ # front wheel contact point
71
+ WR_cont = Point('WR_cont')
72
+ WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z)
73
+ Steer = WR_mc.locatenew('Steer', framelength * Frame.z)
74
+ Frame_mc = WR_mc.locatenew('Frame_mc', - framecg1 * Frame.x
75
+ + framecg3 * Frame.z)
76
+ Fork_mc = Steer.locatenew('Fork_mc', - forkcg1 * Fork.x
77
+ + forkcg3 * Fork.z)
78
+ WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z)
79
+ WF_cont = WF_mc.locatenew('WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y -
80
+ Y.z).normalize())
81
+
82
+ # Set the angular velocity of each frame.
83
+ # Angular accelerations end up being calculated automatically by
84
+ # differentiating the angular velocities when first needed.
85
+ # u1 is yaw rate
86
+ # u2 is roll rate
87
+ # u3 is rear wheel rate
88
+ # u4 is frame pitch rate
89
+ # u5 is fork steer rate
90
+ # u6 is front wheel rate
91
+ Y.set_ang_vel(N, u1 * Y.z)
92
+ R.set_ang_vel(Y, u2 * R.x)
93
+ WR.set_ang_vel(Frame, u3 * Frame.y)
94
+ Frame.set_ang_vel(R, u4 * Frame.y)
95
+ Fork.set_ang_vel(Frame, u5 * Fork.x)
96
+ WF.set_ang_vel(Fork, u6 * Fork.y)
97
+
98
+ # Form the velocities of the previously defined points, using the 2 - point
99
+ # theorem (written out by hand here). Accelerations again are calculated
100
+ # automatically when first needed.
101
+ WR_cont.set_vel(N, 0)
102
+ WR_mc.v2pt_theory(WR_cont, N, WR)
103
+ Steer.v2pt_theory(WR_mc, N, Frame)
104
+ Frame_mc.v2pt_theory(WR_mc, N, Frame)
105
+ Fork_mc.v2pt_theory(Steer, N, Fork)
106
+ WF_mc.v2pt_theory(Steer, N, Fork)
107
+ WF_cont.v2pt_theory(WF_mc, N, WF)
108
+
109
+ # Sets the inertias of each body. Uses the inertia frame to construct the
110
+ # inertia dyadics. Wheel inertias are only defined by principle moments of
111
+ # inertia, and are in fact constant in the frame and fork reference frames;
112
+ # it is for this reason that the orientations of the wheels does not need
113
+ # to be defined. The frame and fork inertias are defined in the 'Temp'
114
+ # frames which are fixed to the appropriate body frames; this is to allow
115
+ # easier input of the reference values of the benchmark paper. Note that
116
+ # due to slightly different orientations, the products of inertia need to
117
+ # have their signs flipped; this is done later when entering the numerical
118
+ # value.
119
+
120
+ Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc)
121
+ Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc)
122
+ WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc)
123
+ WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc)
124
+
125
+ # Declaration of the RigidBody containers. ::
126
+
127
+ BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I)
128
+ BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I)
129
+ BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I)
130
+ BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I)
131
+
132
+ # The kinematic differential equations; they are defined quite simply. Each
133
+ # entry in this list is equal to zero.
134
+ kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5]
135
+
136
+ # The nonholonomic constraints are the velocity of the front wheel contact
137
+ # point dotted into the X, Y, and Z directions; the yaw frame is used as it
138
+ # is "closer" to the front wheel (1 less DCM connecting them). These
139
+ # constraints force the velocity of the front wheel contact point to be 0
140
+ # in the inertial frame; the X and Y direction constraints enforce a
141
+ # "no-slip" condition, and the Z direction constraint forces the front
142
+ # wheel contact point to not move away from the ground frame, essentially
143
+ # replicating the holonomic constraint which does not allow the frame pitch
144
+ # to change in an invalid fashion.
145
+
146
+ conlist_speed = [WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z]
147
+
148
+ # The holonomic constraint is that the position from the rear wheel contact
149
+ # point to the front wheel contact point when dotted into the
150
+ # normal-to-ground plane direction must be zero; effectively that the front
151
+ # and rear wheel contact points are always touching the ground plane. This
152
+ # is actually not part of the dynamic equations, but instead is necessary
153
+ # for the lineraization process.
154
+
155
+ conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z]
156
+
157
+ # The force list; each body has the appropriate gravitational force applied
158
+ # at its mass center.
159
+ FL = [(Frame_mc, -mframe * g * Y.z),
160
+ (Fork_mc, -mfork * g * Y.z),
161
+ (WF_mc, -mwf * g * Y.z),
162
+ (WR_mc, -mwr * g * Y.z)]
163
+ BL = [BodyFrame, BodyFork, BodyWR, BodyWF]
164
+
165
+
166
+ # The N frame is the inertial frame, coordinates are supplied in the order
167
+ # of independent, dependent coordinates, as are the speeds. The kinematic
168
+ # differential equation are also entered here. Here the dependent speeds
169
+ # are specified, in the same order they were provided in earlier, along
170
+ # with the non-holonomic constraints. The dependent coordinate is also
171
+ # provided, with the holonomic constraint. Again, this is only provided
172
+ # for the linearization process.
173
+
174
+ KM = KanesMethod(N, q_ind=[q1, q2, q5],
175
+ q_dependent=[q4], configuration_constraints=conlist_coord,
176
+ u_ind=[u2, u3, u5],
177
+ u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed,
178
+ kd_eqs=kd)
179
+ (fr, frstar) = KM.kanes_equations(BL, FL)
180
+
181
+ # This is the start of entering in the numerical values from the benchmark
182
+ # paper to validate the eigen values of the linearized equations from this
183
+ # model to the reference eigen values. Look at the aforementioned paper for
184
+ # more information. Some of these are intermediate values, used to
185
+ # transform values from the paper into the coordinate systems used in this
186
+ # model.
187
+ PaperRadRear = 0.3
188
+ PaperRadFront = 0.35
189
+ HTA = evalf.N(pi / 2 - pi / 10)
190
+ TrailPaper = 0.08
191
+ rake = evalf.N(-(TrailPaper*sin(HTA)-(PaperRadFront*cos(HTA))))
192
+ PaperWb = 1.02
193
+ PaperFrameCgX = 0.3
194
+ PaperFrameCgZ = 0.9
195
+ PaperForkCgX = 0.9
196
+ PaperForkCgZ = 0.7
197
+ FrameLength = evalf.N(PaperWb*sin(HTA)-(rake-(PaperRadFront-PaperRadRear)*cos(HTA)))
198
+ FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear-(PaperFrameCgX/sin(HTA))*cos(HTA))*sin(HTA))
199
+ FrameCGPar = evalf.N(PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA))
200
+ tempa = evalf.N(PaperForkCgZ - PaperRadFront)
201
+ tempb = evalf.N(PaperWb-PaperForkCgX)
202
+ tempc = evalf.N(sqrt(tempa**2+tempb**2))
203
+ PaperForkL = evalf.N(PaperWb*cos(HTA)-(PaperRadFront-PaperRadRear)*sin(HTA))
204
+ ForkCGNorm = evalf.N(rake+(tempc * sin(pi/2-HTA-acos(tempa/tempc))))
205
+ ForkCGPar = evalf.N(tempc * cos((pi/2-HTA)-acos(tempa/tempc))-PaperForkL)
206
+
207
+ # Here is the final assembly of the numerical values. The symbol 'v' is the
208
+ # forward speed of the bicycle (a concept which only makes sense in the
209
+ # upright, static equilibrium case?). These are in a dictionary which will
210
+ # later be substituted in. Again the sign on the *product* of inertia
211
+ # values is flipped here, due to different orientations of coordinate
212
+ # systems.
213
+ v = symbols('v')
214
+ val_dict = {WFrad: PaperRadFront,
215
+ WRrad: PaperRadRear,
216
+ htangle: HTA,
217
+ forkoffset: rake,
218
+ forklength: PaperForkL,
219
+ framelength: FrameLength,
220
+ forkcg1: ForkCGPar,
221
+ forkcg3: ForkCGNorm,
222
+ framecg1: FrameCGNorm,
223
+ framecg3: FrameCGPar,
224
+ Iwr11: 0.0603,
225
+ Iwr22: 0.12,
226
+ Iwf11: 0.1405,
227
+ Iwf22: 0.28,
228
+ Ifork11: 0.05892,
229
+ Ifork22: 0.06,
230
+ Ifork33: 0.00708,
231
+ Ifork31: 0.00756,
232
+ Iframe11: 9.2,
233
+ Iframe22: 11,
234
+ Iframe33: 2.8,
235
+ Iframe31: -2.4,
236
+ mfork: 4,
237
+ mframe: 85,
238
+ mwf: 3,
239
+ mwr: 2,
240
+ g: 9.81,
241
+ q1: 0,
242
+ q2: 0,
243
+ q4: 0,
244
+ q5: 0,
245
+ u1: 0,
246
+ u2: 0,
247
+ u3: v / PaperRadRear,
248
+ u4: 0,
249
+ u5: 0,
250
+ u6: v / PaperRadFront}
251
+
252
+ # Linearizes the forcing vector; the equations are set up as MM udot =
253
+ # forcing, where MM is the mass matrix, udot is the vector representing the
254
+ # time derivatives of the generalized speeds, and forcing is a vector which
255
+ # contains both external forcing terms and internal forcing terms, such as
256
+ # centripital or coriolis forces. This actually returns a matrix with as
257
+ # many rows as *total* coordinates and speeds, but only as many columns as
258
+ # independent coordinates and speeds.
259
+
260
+ forcing_lin = KM.linearize()[0]
261
+
262
+ # As mentioned above, the size of the linearized forcing terms is expanded
263
+ # to include both q's and u's, so the mass matrix must have this done as
264
+ # well. This will likely be changed to be part of the linearized process,
265
+ # for future reference.
266
+ MM_full = KM.mass_matrix_full
267
+
268
+ MM_full_s = msubs(MM_full, val_dict)
269
+ forcing_lin_s = msubs(forcing_lin, KM.kindiffdict(), val_dict)
270
+
271
+ MM_full_s = MM_full_s.evalf()
272
+ forcing_lin_s = forcing_lin_s.evalf()
273
+
274
+ # Finally, we construct an "A" matrix for the form xdot = A x (x being the
275
+ # state vector, although in this case, the sizes are a little off). The
276
+ # following line extracts only the minimum entries required for eigenvalue
277
+ # analysis, which correspond to rows and columns for lean, steer, lean
278
+ # rate, and steer rate.
279
+ Amat = MM_full_s.inv() * forcing_lin_s
280
+ A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5])
281
+
282
+ # Precomputed for comparison
283
+ Res = Matrix([[ 0, 0, 1.0, 0],
284
+ [ 0, 0, 0, 1.0],
285
+ [9.48977444677355, -0.891197738059089*v**2 - 0.571523173729245, -0.105522449805691*v, -0.330515398992311*v],
286
+ [11.7194768719633, -1.97171508499972*v**2 + 30.9087533932407, 3.67680523332152*v, -3.08486552743311*v]])
287
+
288
+
289
+ # Actual eigenvalue comparison
290
+ eps = 1.e-12
291
+ for i in range(6):
292
+ error = Res.subs(v, i) - A.subs(v, i)
293
+ assert all(abs(x) < eps for x in error)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import (cos, sin, Matrix, symbols)
2
+ from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
3
+ KanesMethod, Particle)
4
+
5
+ def test_replace_qdots_in_force():
6
+ # Test PR 16700 "Replaces qdots with us in force-list in kanes.py"
7
+ # The new functionality allows one to specify forces in qdots which will
8
+ # automatically be replaced with u:s which are defined by the kde supplied
9
+ # to KanesMethod. The test case is the double pendulum with interacting
10
+ # forces in the example of chapter 4.7 "CONTRIBUTING INTERACTION FORCES"
11
+ # in Ref. [1]. Reference list at end test function.
12
+
13
+ q1, q2 = dynamicsymbols('q1, q2')
14
+ qd1, qd2 = dynamicsymbols('q1, q2', level=1)
15
+ u1, u2 = dynamicsymbols('u1, u2')
16
+
17
+ l, m = symbols('l, m')
18
+
19
+ N = ReferenceFrame('N') # Inertial frame
20
+ A = N.orientnew('A', 'Axis', (q1, N.z)) # Rod A frame
21
+ B = A.orientnew('B', 'Axis', (q2, N.z)) # Rod B frame
22
+
23
+ O = Point('O') # Origo
24
+ O.set_vel(N, 0)
25
+
26
+ P = O.locatenew('P', ( l * A.x )) # Point @ end of rod A
27
+ P.v2pt_theory(O, N, A)
28
+
29
+ Q = P.locatenew('Q', ( l * B.x )) # Point @ end of rod B
30
+ Q.v2pt_theory(P, N, B)
31
+
32
+ Ap = Particle('Ap', P, m)
33
+ Bp = Particle('Bp', Q, m)
34
+
35
+ # The forces are specified below. sigma is the torsional spring stiffness
36
+ # and delta is the viscous damping coefficient acting between the two
37
+ # bodies. Here, we specify the viscous damper as function of qdots prior
38
+ # forming the kde. In more complex systems it not might be obvious which
39
+ # kde is most efficient, why it is convenient to specify viscous forces in
40
+ # qdots independently of the kde.
41
+ sig, delta = symbols('sigma, delta')
42
+ Ta = (sig * q2 + delta * qd2) * N.z
43
+ forces = [(A, Ta), (B, -Ta)]
44
+
45
+ # Try different kdes.
46
+ kde1 = [u1 - qd1, u2 - qd2]
47
+ kde2 = [u1 - qd1, u2 - (qd1 + qd2)]
48
+
49
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
50
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
51
+
52
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
53
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
54
+
55
+ # Check EOM for KM2:
56
+ # Mass and force matrix from p.6 in Ref. [2] with added forces from
57
+ # example of chapter 4.7 in [1] and without gravity.
58
+ forcing_matrix_expected = Matrix( [ [ m * l**2 * sin(q2) * u2**2 + sig * q2
59
+ + delta * (u2 - u1)],
60
+ [ m * l**2 * sin(q2) * -u1**2 - sig * q2
61
+ - delta * (u2 - u1)] ] )
62
+ mass_matrix_expected = Matrix( [ [ 2 * m * l**2, m * l**2 * cos(q2) ],
63
+ [ m * l**2 * cos(q2), m * l**2 ] ] )
64
+
65
+ assert (KM2.mass_matrix.expand() == mass_matrix_expected.expand())
66
+ assert (KM2.forcing.expand() == forcing_matrix_expected.expand())
67
+
68
+ # Check fr1 with reference fr_expected from [1] with u:s instead of qdots.
69
+ fr1_expected = Matrix([ 0, -(sig*q2 + delta * u2) ])
70
+ assert fr1.expand() == fr1_expected.expand()
71
+
72
+ # Check fr2
73
+ fr2_expected = Matrix([sig * q2 + delta * (u2 - u1),
74
+ - sig * q2 - delta * (u2 - u1)])
75
+ assert fr2.expand() == fr2_expected.expand()
76
+
77
+ # Specifying forces in u:s should stay the same:
78
+ Ta = (sig * q2 + delta * u2) * N.z
79
+ forces = [(A, Ta), (B, -Ta)]
80
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
81
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
82
+
83
+ assert fr1.expand() == fr1_expected.expand()
84
+
85
+ Ta = (sig * q2 + delta * (u2-u1)) * N.z
86
+ forces = [(A, Ta), (B, -Ta)]
87
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
88
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
89
+
90
+ assert fr2.expand() == fr2_expected.expand()
91
+
92
+ # Test if we have a qubic qdot force:
93
+ Ta = (sig * q2 + delta * qd2**3) * N.z
94
+ forces = [(A, Ta), (B, -Ta)]
95
+
96
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
97
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
98
+
99
+ fr1_cubic_expected = Matrix([ 0, -(sig*q2 + delta * u2**3) ])
100
+
101
+ assert fr1.expand() == fr1_cubic_expected.expand()
102
+
103
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
104
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
105
+
106
+ fr2_cubic_expected = Matrix([sig * q2 + delta * (u2 - u1)**3,
107
+ - sig * q2 - delta * (u2 - u1)**3])
108
+
109
+ assert fr2.expand() == fr2_cubic_expected.expand()
110
+
111
+ # References:
112
+ # [1] T.R. Kane, D. a Levinson, Dynamics Theory and Applications, 2005.
113
+ # [2] Arun K Banerjee, Flexible Multibody Dynamics:Efficient Formulations
114
+ # and Applications, John Wiley and Sons, Ltd, 2016.
115
+ # doi:http://dx.doi.org/10.1002/9781119015635.
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
2
+ RigidBody, LagrangesMethod, Particle,
3
+ inertia, Lagrangian)
4
+ from sympy.core.function import (Derivative, Function)
5
+ from sympy.core.numbers import pi
6
+ from sympy.core.symbol import symbols
7
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
8
+ from sympy.matrices.dense import Matrix
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy.testing.pytest import raises
11
+
12
+
13
+ def test_invalid_coordinates():
14
+ # Simple pendulum, but use symbol instead of dynamicsymbol
15
+ l, m, g = symbols('l m g')
16
+ q = symbols('q') # Generalized coordinate
17
+ N, O = ReferenceFrame('N'), Point('O')
18
+ O.set_vel(N, 0)
19
+ P = Particle('P', Point('P'), m)
20
+ P.point.set_pos(O, l * (sin(q) * N.x - cos(q) * N.y))
21
+ P.potential_energy = m * g * P.point.pos_from(O).dot(N.y)
22
+ L = Lagrangian(N, P)
23
+ raises(ValueError, lambda: LagrangesMethod(L, [q], bodies=P))
24
+
25
+
26
+ def test_disc_on_an_incline_plane():
27
+ # Disc rolling on an inclined plane
28
+ # First the generalized coordinates are created. The mass center of the
29
+ # disc is located from top vertex of the inclined plane by the generalized
30
+ # coordinate 'y'. The orientation of the disc is defined by the angle
31
+ # 'theta'. The mass of the disc is 'm' and its radius is 'R'. The length of
32
+ # the inclined path is 'l', the angle of inclination is 'alpha'. 'g' is the
33
+ # gravitational constant.
34
+ y, theta = dynamicsymbols('y theta')
35
+ yd, thetad = dynamicsymbols('y theta', 1)
36
+ m, g, R, l, alpha = symbols('m g R l alpha')
37
+
38
+ # Next, we create the inertial reference frame 'N'. A reference frame 'A'
39
+ # is attached to the inclined plane. Finally a frame is created which is attached to the disk.
40
+ N = ReferenceFrame('N')
41
+ A = N.orientnew('A', 'Axis', [pi/2 - alpha, N.z])
42
+ B = A.orientnew('B', 'Axis', [-theta, A.z])
43
+
44
+ # Creating the disc 'D'; we create the point that represents the mass
45
+ # center of the disc and set its velocity. The inertia dyadic of the disc
46
+ # is created. Finally, we create the disc.
47
+ Do = Point('Do')
48
+ Do.set_vel(N, yd * A.x)
49
+ I = m * R**2/2 * B.z | B.z
50
+ D = RigidBody('D', Do, B, m, (I, Do))
51
+
52
+ # To construct the Lagrangian, 'L', of the disc, we determine its kinetic
53
+ # and potential energies, T and U, respectively. L is defined as the
54
+ # difference between T and U.
55
+ D.potential_energy = m * g * (l - y) * sin(alpha)
56
+ L = Lagrangian(N, D)
57
+
58
+ # We then create the list of generalized coordinates and constraint
59
+ # equations. The constraint arises due to the disc rolling without slip on
60
+ # on the inclined path. We then invoke the 'LagrangesMethod' class and
61
+ # supply it the necessary arguments and generate the equations of motion.
62
+ # The'rhs' method solves for the q_double_dots (i.e. the second derivative
63
+ # with respect to time of the generalized coordinates and the lagrange
64
+ # multipliers.
65
+ q = [y, theta]
66
+ hol_coneqs = [y - R * theta]
67
+ m = LagrangesMethod(L, q, hol_coneqs=hol_coneqs)
68
+ m.form_lagranges_equations()
69
+ rhs = m.rhs()
70
+ rhs.simplify()
71
+ assert rhs[2] == 2*g*sin(alpha)/3
72
+
73
+
74
+ def test_simp_pen():
75
+ # This tests that the equations generated by LagrangesMethod are identical
76
+ # to those obtained by hand calculations. The system under consideration is
77
+ # the simple pendulum.
78
+ # We begin by creating the generalized coordinates as per the requirements
79
+ # of LagrangesMethod. Also we created the associate symbols
80
+ # that characterize the system: 'm' is the mass of the bob, l is the length
81
+ # of the massless rigid rod connecting the bob to a point O fixed in the
82
+ # inertial frame.
83
+ q, u = dynamicsymbols('q u')
84
+ qd, ud = dynamicsymbols('q u ', 1)
85
+ l, m, g = symbols('l m g')
86
+
87
+ # We then create the inertial frame and a frame attached to the massless
88
+ # string following which we define the inertial angular velocity of the
89
+ # string.
90
+ N = ReferenceFrame('N')
91
+ A = N.orientnew('A', 'Axis', [q, N.z])
92
+ A.set_ang_vel(N, qd * N.z)
93
+
94
+ # Next, we create the point O and fix it in the inertial frame. We then
95
+ # locate the point P to which the bob is attached. Its corresponding
96
+ # velocity is then determined by the 'two point formula'.
97
+ O = Point('O')
98
+ O.set_vel(N, 0)
99
+ P = O.locatenew('P', l * A.x)
100
+ P.v2pt_theory(O, N, A)
101
+
102
+ # The 'Particle' which represents the bob is then created and its
103
+ # Lagrangian generated.
104
+ Pa = Particle('Pa', P, m)
105
+ Pa.potential_energy = - m * g * l * cos(q)
106
+ L = Lagrangian(N, Pa)
107
+
108
+ # The 'LagrangesMethod' class is invoked to obtain equations of motion.
109
+ lm = LagrangesMethod(L, [q])
110
+ lm.form_lagranges_equations()
111
+ RHS = lm.rhs()
112
+ assert RHS[1] == -g*sin(q)/l
113
+
114
+
115
+ def test_nonminimal_pendulum():
116
+ q1, q2 = dynamicsymbols('q1:3')
117
+ q1d, q2d = dynamicsymbols('q1:3', level=1)
118
+ L, m, t = symbols('L, m, t')
119
+ g = 9.8
120
+ # Compose World Frame
121
+ N = ReferenceFrame('N')
122
+ pN = Point('N*')
123
+ pN.set_vel(N, 0)
124
+ # Create point P, the pendulum mass
125
+ P = pN.locatenew('P1', q1*N.x + q2*N.y)
126
+ P.set_vel(N, P.pos_from(pN).dt(N))
127
+ pP = Particle('pP', P, m)
128
+ # Constraint Equations
129
+ f_c = Matrix([q1**2 + q2**2 - L**2])
130
+ # Calculate the lagrangian, and form the equations of motion
131
+ Lag = Lagrangian(N, pP)
132
+ LM = LagrangesMethod(Lag, [q1, q2], hol_coneqs=f_c,
133
+ forcelist=[(P, m*g*N.x)], frame=N)
134
+ LM.form_lagranges_equations()
135
+ # Check solution
136
+ lam1 = LM.lam_vec[0, 0]
137
+ eom_sol = Matrix([[m*Derivative(q1, t, t) - 9.8*m + 2*lam1*q1],
138
+ [m*Derivative(q2, t, t) + 2*lam1*q2]])
139
+ assert LM.eom == eom_sol
140
+ # Check multiplier solution
141
+ lam_sol = Matrix([(19.6*q1 + 2*q1d**2 + 2*q2d**2)/(4*q1**2/m + 4*q2**2/m)])
142
+ assert simplify(LM.solve_multipliers(sol_type='Matrix')) == simplify(lam_sol)
143
+
144
+
145
+ def test_dub_pen():
146
+
147
+ # The system considered is the double pendulum. Like in the
148
+ # test of the simple pendulum above, we begin by creating the generalized
149
+ # coordinates and the simple generalized speeds and accelerations which
150
+ # will be used later. Following this we create frames and points necessary
151
+ # for the kinematics. The procedure isn't explicitly explained as this is
152
+ # similar to the simple pendulum. Also this is documented on the pydy.org
153
+ # website.
154
+ q1, q2 = dynamicsymbols('q1 q2')
155
+ q1d, q2d = dynamicsymbols('q1 q2', 1)
156
+ q1dd, q2dd = dynamicsymbols('q1 q2', 2)
157
+ u1, u2 = dynamicsymbols('u1 u2')
158
+ u1d, u2d = dynamicsymbols('u1 u2', 1)
159
+ l, m, g = symbols('l m g')
160
+
161
+ N = ReferenceFrame('N')
162
+ A = N.orientnew('A', 'Axis', [q1, N.z])
163
+ B = N.orientnew('B', 'Axis', [q2, N.z])
164
+
165
+ A.set_ang_vel(N, q1d * A.z)
166
+ B.set_ang_vel(N, q2d * A.z)
167
+
168
+ O = Point('O')
169
+ P = O.locatenew('P', l * A.x)
170
+ R = P.locatenew('R', l * B.x)
171
+
172
+ O.set_vel(N, 0)
173
+ P.v2pt_theory(O, N, A)
174
+ R.v2pt_theory(P, N, B)
175
+
176
+ ParP = Particle('ParP', P, m)
177
+ ParR = Particle('ParR', R, m)
178
+
179
+ ParP.potential_energy = - m * g * l * cos(q1)
180
+ ParR.potential_energy = - m * g * l * cos(q1) - m * g * l * cos(q2)
181
+ L = Lagrangian(N, ParP, ParR)
182
+ lm = LagrangesMethod(L, [q1, q2], bodies=[ParP, ParR])
183
+ lm.form_lagranges_equations()
184
+
185
+ assert simplify(l*m*(2*g*sin(q1) + l*sin(q1)*sin(q2)*q2dd
186
+ + l*sin(q1)*cos(q2)*q2d**2 - l*sin(q2)*cos(q1)*q2d**2
187
+ + l*cos(q1)*cos(q2)*q2dd + 2*l*q1dd) - lm.eom[0]) == 0
188
+ assert simplify(l*m*(g*sin(q2) + l*sin(q1)*sin(q2)*q1dd
189
+ - l*sin(q1)*cos(q2)*q1d**2 + l*sin(q2)*cos(q1)*q1d**2
190
+ + l*cos(q1)*cos(q2)*q1dd + l*q2dd) - lm.eom[1]) == 0
191
+ assert lm.bodies == [ParP, ParR]
192
+
193
+
194
+ def test_rolling_disc():
195
+ # Rolling Disc Example
196
+ # Here the rolling disc is formed from the contact point up, removing the
197
+ # need to introduce generalized speeds. Only 3 configuration and 3
198
+ # speed variables are need to describe this system, along with the
199
+ # disc's mass and radius, and the local gravity.
200
+ q1, q2, q3 = dynamicsymbols('q1 q2 q3')
201
+ q1d, q2d, q3d = dynamicsymbols('q1 q2 q3', 1)
202
+ r, m, g = symbols('r m g')
203
+
204
+ # The kinematics are formed by a series of simple rotations. Each simple
205
+ # rotation creates a new frame, and the next rotation is defined by the new
206
+ # frame's basis vectors. This example uses a 3-1-2 series of rotations, or
207
+ # Z, X, Y series of rotations. Angular velocity for this is defined using
208
+ # the second frame's basis (the lean frame).
209
+ N = ReferenceFrame('N')
210
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
211
+ L = Y.orientnew('L', 'Axis', [q2, Y.x])
212
+ R = L.orientnew('R', 'Axis', [q3, L.y])
213
+
214
+ # This is the translational kinematics. We create a point with no velocity
215
+ # in N; this is the contact point between the disc and ground. Next we form
216
+ # the position vector from the contact point to the disc's center of mass.
217
+ # Finally we form the velocity and acceleration of the disc.
218
+ C = Point('C')
219
+ C.set_vel(N, 0)
220
+ Dmc = C.locatenew('Dmc', r * L.z)
221
+ Dmc.v2pt_theory(C, N, R)
222
+
223
+ # Forming the inertia dyadic.
224
+ I = inertia(L, m/4 * r**2, m/2 * r**2, m/4 * r**2)
225
+ BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
226
+
227
+ # Finally we form the equations of motion, using the same steps we did
228
+ # before. Supply the Lagrangian, the generalized speeds.
229
+ BodyD.potential_energy = - m * g * r * cos(q2)
230
+ Lag = Lagrangian(N, BodyD)
231
+ q = [q1, q2, q3]
232
+ q1 = Function('q1')
233
+ q2 = Function('q2')
234
+ q3 = Function('q3')
235
+ l = LagrangesMethod(Lag, q)
236
+ l.form_lagranges_equations()
237
+ RHS = l.rhs()
238
+ RHS.simplify()
239
+ t = symbols('t')
240
+
241
+ assert (l.mass_matrix[3:6] == [0, 5*m*r**2/4, 0])
242
+ assert RHS[4].simplify() == (
243
+ (-8*g*sin(q2(t)) + r*(5*sin(2*q2(t))*Derivative(q1(t), t) +
244
+ 12*cos(q2(t))*Derivative(q3(t), t))*Derivative(q1(t), t))/(10*r))
245
+ assert RHS[5] == (-5*cos(q2(t))*Derivative(q1(t), t) + 6*tan(q2(t)
246
+ )*Derivative(q3(t), t) + 4*Derivative(q1(t), t)/cos(q2(t))
247
+ )*Derivative(q2(t), t)
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import symbols
2
+ from sympy.physics.mechanics import dynamicsymbols
3
+ from sympy.physics.mechanics import ReferenceFrame, Point, Particle
4
+ from sympy.physics.mechanics import LagrangesMethod, Lagrangian
5
+
6
+ ### This test asserts that a system with more than one external forces
7
+ ### is acurately formed with Lagrange method (see issue #8626)
8
+
9
+ def test_lagrange_2forces():
10
+ ### Equations for two damped springs in serie with two forces
11
+
12
+ ### generalized coordinates
13
+ q1, q2 = dynamicsymbols('q1, q2')
14
+ ### generalized speeds
15
+ q1d, q2d = dynamicsymbols('q1, q2', 1)
16
+
17
+ ### Mass, spring strength, friction coefficient
18
+ m, k, nu = symbols('m, k, nu')
19
+
20
+ N = ReferenceFrame('N')
21
+ O = Point('O')
22
+
23
+ ### Two points
24
+ P1 = O.locatenew('P1', q1 * N.x)
25
+ P1.set_vel(N, q1d * N.x)
26
+ P2 = O.locatenew('P1', q2 * N.x)
27
+ P2.set_vel(N, q2d * N.x)
28
+
29
+ pP1 = Particle('pP1', P1, m)
30
+ pP1.potential_energy = k * q1**2 / 2
31
+
32
+ pP2 = Particle('pP2', P2, m)
33
+ pP2.potential_energy = k * (q1 - q2)**2 / 2
34
+
35
+ #### Friction forces
36
+ forcelist = [(P1, - nu * q1d * N.x),
37
+ (P2, - nu * q2d * N.x)]
38
+ lag = Lagrangian(N, pP1, pP2)
39
+
40
+ l_method = LagrangesMethod(lag, (q1, q2), forcelist=forcelist, frame=N)
41
+ l_method.form_lagranges_equations()
42
+
43
+ eq1 = l_method.eom[0]
44
+ assert eq1.diff(q1d) == nu
45
+ eq2 = l_method.eom[1]
46
+ assert eq2.diff(q2d) == nu