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

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/sho.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py +5 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py +735 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py +300 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py +1245 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py +66 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc +0 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc +0 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/body.py +611 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py +779 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py +2163 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py +279 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py +741 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py +477 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py +443 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/method.py +39 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/models.py +230 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py +281 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py +366 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/system.py +445 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py +0 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_body.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_functions.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc +0 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/pring.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/__pycache__/sho.cpython-310.pyc ADDED
Binary file (2.81 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __all__ = ['Beam',
2
+ 'Truss']
3
+
4
+ from .beam import Beam
5
+ from .truss import Truss
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module can be used to solve problems related
3
+ to 2D Trusses.
4
+ """
5
+
6
+ from cmath import inf
7
+ from sympy.core.add import Add
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.core.sympify import sympify
11
+ from sympy import Matrix, pi
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.matrices.dense import zeros
14
+ from sympy import sin, cos
15
+
16
+
17
+
18
+ class Truss:
19
+ """
20
+ A Truss is an assembly of members such as beams,
21
+ connected by nodes, that create a rigid structure.
22
+ In engineering, a truss is a structure that
23
+ consists of two-force members only.
24
+
25
+ Trusses are extremely important in engineering applications
26
+ and can be seen in numerous real-world applications like bridges.
27
+
28
+ Examples
29
+ ========
30
+
31
+ There is a Truss consisting of four nodes and five
32
+ members connecting the nodes. A force P acts
33
+ downward on the node D and there also exist pinned
34
+ and roller joints on the nodes A and B respectively.
35
+
36
+ .. image:: truss_example.png
37
+
38
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
39
+ >>> t = Truss()
40
+ >>> t.add_node("node_1", 0, 0)
41
+ >>> t.add_node("node_2", 6, 0)
42
+ >>> t.add_node("node_3", 2, 2)
43
+ >>> t.add_node("node_4", 2, 0)
44
+ >>> t.add_member("member_1", "node_1", "node_4")
45
+ >>> t.add_member("member_2", "node_2", "node_4")
46
+ >>> t.add_member("member_3", "node_1", "node_3")
47
+ >>> t.add_member("member_4", "node_2", "node_3")
48
+ >>> t.add_member("member_5", "node_3", "node_4")
49
+ >>> t.apply_load("node_4", magnitude=10, direction=270)
50
+ >>> t.apply_support("node_1", type="fixed")
51
+ >>> t.apply_support("node_2", type="roller")
52
+ """
53
+
54
+ def __init__(self):
55
+ """
56
+ Initializes the class
57
+ """
58
+ self._nodes = []
59
+ self._members = {}
60
+ self._loads = {}
61
+ self._supports = {}
62
+ self._node_labels = []
63
+ self._node_positions = []
64
+ self._node_position_x = []
65
+ self._node_position_y = []
66
+ self._nodes_occupied = {}
67
+ self._reaction_loads = {}
68
+ self._internal_forces = {}
69
+ self._node_coordinates = {}
70
+
71
+ @property
72
+ def nodes(self):
73
+ """
74
+ Returns the nodes of the truss along with their positions.
75
+ """
76
+ return self._nodes
77
+
78
+ @property
79
+ def node_labels(self):
80
+ """
81
+ Returns the node labels of the truss.
82
+ """
83
+ return self._node_labels
84
+
85
+ @property
86
+ def node_positions(self):
87
+ """
88
+ Returns the positions of the nodes of the truss.
89
+ """
90
+ return self._node_positions
91
+
92
+ @property
93
+ def members(self):
94
+ """
95
+ Returns the members of the truss along with the start and end points.
96
+ """
97
+ return self._members
98
+
99
+ @property
100
+ def member_labels(self):
101
+ """
102
+ Returns the members of the truss along with the start and end points.
103
+ """
104
+ return self._member_labels
105
+
106
+ @property
107
+ def supports(self):
108
+ """
109
+ Returns the nodes with provided supports along with the kind of support provided i.e.
110
+ pinned or roller.
111
+ """
112
+ return self._supports
113
+
114
+ @property
115
+ def loads(self):
116
+ """
117
+ Returns the loads acting on the truss.
118
+ """
119
+ return self._loads
120
+
121
+ @property
122
+ def reaction_loads(self):
123
+ """
124
+ Returns the reaction forces for all supports which are all initialized to 0.
125
+ """
126
+ return self._reaction_loads
127
+
128
+ @property
129
+ def internal_forces(self):
130
+ """
131
+ Returns the internal forces for all members which are all initialized to 0.
132
+ """
133
+ return self._internal_forces
134
+
135
+ def add_node(self, label, x, y):
136
+ """
137
+ This method adds a node to the truss along with its name/label and its location.
138
+
139
+ Parameters
140
+ ==========
141
+ label: String or a Symbol
142
+ The label for a node. It is the only way to identify a particular node.
143
+
144
+ x: Sympifyable
145
+ The x-coordinate of the position of the node.
146
+
147
+ y: Sympifyable
148
+ The y-coordinate of the position of the node.
149
+
150
+ Examples
151
+ ========
152
+
153
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
154
+ >>> t = Truss()
155
+ >>> t.add_node('A', 0, 0)
156
+ >>> t.nodes
157
+ [('A', 0, 0)]
158
+ >>> t.add_node('B', 3, 0)
159
+ >>> t.nodes
160
+ [('A', 0, 0), ('B', 3, 0)]
161
+ """
162
+ x = sympify(x)
163
+ y = sympify(y)
164
+
165
+ if label in self._node_labels:
166
+ raise ValueError("Node needs to have a unique label")
167
+
168
+ elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y):
169
+ raise ValueError("A node already exists at the given position")
170
+
171
+ else :
172
+ self._nodes.append((label, x, y))
173
+ self._node_labels.append(label)
174
+ self._node_positions.append((x, y))
175
+ self._node_position_x.append(x)
176
+ self._node_position_y.append(y)
177
+ self._node_coordinates[label] = [x, y]
178
+
179
+ def remove_node(self, label):
180
+ """
181
+ This method removes a node from the truss.
182
+
183
+ Parameters
184
+ ==========
185
+ label: String or Symbol
186
+ The label of the node to be removed.
187
+
188
+ Examples
189
+ ========
190
+
191
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
192
+ >>> t = Truss()
193
+ >>> t.add_node('A', 0, 0)
194
+ >>> t.nodes
195
+ [('A', 0, 0)]
196
+ >>> t.add_node('B', 3, 0)
197
+ >>> t.nodes
198
+ [('A', 0, 0), ('B', 3, 0)]
199
+ >>> t.remove_node('A')
200
+ >>> t.nodes
201
+ [('B', 3, 0)]
202
+ """
203
+ for i in range(len(self.nodes)):
204
+ if self._node_labels[i] == label:
205
+ x = self._node_position_x[i]
206
+ y = self._node_position_y[i]
207
+
208
+ if label not in self._node_labels:
209
+ raise ValueError("No such node exists in the truss")
210
+
211
+ else:
212
+ members_duplicate = self._members.copy()
213
+ for member in members_duplicate:
214
+ if label == self._members[member][0] or label == self._members[member][1]:
215
+ raise ValueError("The node given has members already attached to it")
216
+ self._nodes.remove((label, x, y))
217
+ self._node_labels.remove(label)
218
+ self._node_positions.remove((x, y))
219
+ self._node_position_x.remove(x)
220
+ self._node_position_y.remove(y)
221
+ if label in list(self._loads):
222
+ self._loads.pop(label)
223
+ if label in list(self._supports):
224
+ self._supports.pop(label)
225
+ self._node_coordinates.pop(label)
226
+
227
+ def add_member(self, label, start, end):
228
+ """
229
+ This method adds a member between any two nodes in the given truss.
230
+
231
+ Parameters
232
+ ==========
233
+ label: String or Symbol
234
+ The label for a member. It is the only way to identify a particular member.
235
+
236
+ start: String or Symbol
237
+ The label of the starting point/node of the member.
238
+
239
+ end: String or Symbol
240
+ The label of the ending point/node of the member.
241
+
242
+ Examples
243
+ ========
244
+
245
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
246
+ >>> t = Truss()
247
+ >>> t.add_node('A', 0, 0)
248
+ >>> t.add_node('B', 3, 0)
249
+ >>> t.add_node('C', 2, 2)
250
+ >>> t.add_member('AB', 'A', 'B')
251
+ >>> t.members
252
+ {'AB': ['A', 'B']}
253
+ """
254
+
255
+ if start not in self._node_labels or end not in self._node_labels or start==end:
256
+ raise ValueError("The start and end points of the member must be unique nodes")
257
+
258
+ elif label in list(self._members):
259
+ raise ValueError("A member with the same label already exists for the truss")
260
+
261
+ elif self._nodes_occupied.get((start, end)):
262
+ raise ValueError("A member already exists between the two nodes")
263
+
264
+ else:
265
+ self._members[label] = [start, end]
266
+ self._nodes_occupied[start, end] = True
267
+ self._nodes_occupied[end, start] = True
268
+ self._internal_forces[label] = 0
269
+
270
+ def remove_member(self, label):
271
+ """
272
+ This method removes a member from the given truss.
273
+
274
+ Parameters
275
+ ==========
276
+ label: String or Symbol
277
+ The label for the member to be removed.
278
+
279
+ Examples
280
+ ========
281
+
282
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
283
+ >>> t = Truss()
284
+ >>> t.add_node('A', 0, 0)
285
+ >>> t.add_node('B', 3, 0)
286
+ >>> t.add_node('C', 2, 2)
287
+ >>> t.add_member('AB', 'A', 'B')
288
+ >>> t.add_member('AC', 'A', 'C')
289
+ >>> t.add_member('BC', 'B', 'C')
290
+ >>> t.members
291
+ {'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']}
292
+ >>> t.remove_member('AC')
293
+ >>> t.members
294
+ {'AB': ['A', 'B'], 'BC': ['B', 'C']}
295
+ """
296
+ if label not in list(self._members):
297
+ raise ValueError("No such member exists in the Truss")
298
+
299
+ else:
300
+ self._nodes_occupied.pop((self._members[label][0], self._members[label][1]))
301
+ self._nodes_occupied.pop((self._members[label][1], self._members[label][0]))
302
+ self._members.pop(label)
303
+ self._internal_forces.pop(label)
304
+
305
+ def change_node_label(self, label, new_label):
306
+ """
307
+ This method changes the label of a node.
308
+
309
+ Parameters
310
+ ==========
311
+ label: String or Symbol
312
+ The label of the node for which the label has
313
+ to be changed.
314
+
315
+ new_label: String or Symbol
316
+ The new label of the node.
317
+
318
+ Examples
319
+ ========
320
+
321
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
322
+ >>> t = Truss()
323
+ >>> t.add_node('A', 0, 0)
324
+ >>> t.add_node('B', 3, 0)
325
+ >>> t.nodes
326
+ [('A', 0, 0), ('B', 3, 0)]
327
+ >>> t.change_node_label('A', 'C')
328
+ >>> t.nodes
329
+ [('C', 0, 0), ('B', 3, 0)]
330
+ """
331
+ if label not in self._node_labels:
332
+ raise ValueError("No such node exists for the Truss")
333
+ elif new_label in self._node_labels:
334
+ raise ValueError("A node with the given label already exists")
335
+ else:
336
+ for node in self._nodes:
337
+ if node[0] == label:
338
+ self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2])
339
+ self._node_labels[self._node_labels.index(node[0])] = new_label
340
+ self._node_coordinates[new_label] = self._node_coordinates[label]
341
+ self._node_coordinates.pop(label)
342
+ if node[0] in list(self._supports):
343
+ self._supports[new_label] = self._supports[node[0]]
344
+ self._supports.pop(node[0])
345
+ if new_label in list(self._supports):
346
+ if self._supports[new_label] == 'pinned':
347
+ if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads):
348
+ self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x']
349
+ self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y']
350
+ self._reaction_loads.pop('R_'+str(label)+'_x')
351
+ self._reaction_loads.pop('R_'+str(label)+'_y')
352
+ self._loads[new_label] = self._loads[label]
353
+ for load in self._loads[new_label]:
354
+ if load[1] == 90:
355
+ load[0] -= Symbol('R_'+str(label)+'_y')
356
+ if load[0] == 0:
357
+ self._loads[label].remove(load)
358
+ break
359
+ for load in self._loads[new_label]:
360
+ if load[1] == 0:
361
+ load[0] -= Symbol('R_'+str(label)+'_x')
362
+ if load[0] == 0:
363
+ self._loads[label].remove(load)
364
+ break
365
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0)
366
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
367
+ self._loads.pop(label)
368
+ elif self._supports[new_label] == 'roller':
369
+ self._loads[new_label] = self._loads[label]
370
+ for load in self._loads[label]:
371
+ if load[1] == 90:
372
+ load[0] -= Symbol('R_'+str(label)+'_y')
373
+ if load[0] == 0:
374
+ self._loads[label].remove(load)
375
+ break
376
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
377
+ self._loads.pop(label)
378
+ else:
379
+ if label in list(self._loads):
380
+ self._loads[new_label] = self._loads[label]
381
+ self._loads.pop(label)
382
+ for member in list(self._members):
383
+ if self._members[member][0] == node[0]:
384
+ self._members[member][0] = new_label
385
+ self._nodes_occupied[(new_label, self._members[member][1])] = True
386
+ self._nodes_occupied[(self._members[member][1], new_label)] = True
387
+ self._nodes_occupied.pop((label, self._members[member][1]))
388
+ self._nodes_occupied.pop((self._members[member][1], label))
389
+ elif self._members[member][1] == node[0]:
390
+ self._members[member][1] = new_label
391
+ self._nodes_occupied[(self._members[member][0], new_label)] = True
392
+ self._nodes_occupied[(new_label, self._members[member][0])] = True
393
+ self._nodes_occupied.pop((self._members[member][0], label))
394
+ self._nodes_occupied.pop((label, self._members[member][0]))
395
+
396
+ def change_member_label(self, label, new_label):
397
+ """
398
+ This method changes the label of a member.
399
+
400
+ Parameters
401
+ ==========
402
+ label: String or Symbol
403
+ The label of the member for which the label has
404
+ to be changed.
405
+
406
+ new_label: String or Symbol
407
+ The new label of the member.
408
+
409
+ Examples
410
+ ========
411
+
412
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
413
+ >>> t = Truss()
414
+ >>> t.add_node('A', 0, 0)
415
+ >>> t.add_node('B', 3, 0)
416
+ >>> t.nodes
417
+ [('A', 0, 0), ('B', 3, 0)]
418
+ >>> t.change_node_label('A', 'C')
419
+ >>> t.nodes
420
+ [('C', 0, 0), ('B', 3, 0)]
421
+ >>> t.add_member('BC', 'B', 'C')
422
+ >>> t.members
423
+ {'BC': ['B', 'C']}
424
+ >>> t.change_member_label('BC', 'BC_new')
425
+ >>> t.members
426
+ {'BC_new': ['B', 'C']}
427
+ """
428
+ if label not in list(self._members):
429
+ raise ValueError("No such member exists for the Truss")
430
+
431
+ else:
432
+ members_duplicate = list(self._members).copy()
433
+ for member in members_duplicate:
434
+ if member == label:
435
+ self._members[new_label] = [self._members[member][0], self._members[member][1]]
436
+ self._members.pop(label)
437
+ self._internal_forces[new_label] = self._internal_forces[label]
438
+ self._internal_forces.pop(label)
439
+
440
+ def apply_load(self, location, magnitude, direction):
441
+ """
442
+ This method applies an external load at a particular node
443
+
444
+ Parameters
445
+ ==========
446
+ location: String or Symbol
447
+ Label of the Node at which load is applied.
448
+
449
+ magnitude: Sympifyable
450
+ Magnitude of the load applied. It must always be positive and any changes in
451
+ the direction of the load are not reflected here.
452
+
453
+ direction: Sympifyable
454
+ The angle, in degrees, that the load vector makes with the horizontal
455
+ in the counter-clockwise direction. It takes the values 0 to 360,
456
+ inclusive.
457
+
458
+ Examples
459
+ ========
460
+
461
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
462
+ >>> from sympy import symbols
463
+ >>> t = Truss()
464
+ >>> t.add_node('A', 0, 0)
465
+ >>> t.add_node('B', 3, 0)
466
+ >>> P = symbols('P')
467
+ >>> t.apply_load('A', P, 90)
468
+ >>> t.apply_load('A', P/2, 45)
469
+ >>> t.apply_load('A', P/4, 90)
470
+ >>> t.loads
471
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
472
+ """
473
+ magnitude = sympify(magnitude)
474
+ direction = sympify(direction)
475
+
476
+ if location not in self.node_labels:
477
+ raise ValueError("Load must be applied at a known node")
478
+
479
+ else:
480
+ if location in list(self._loads):
481
+ self._loads[location].append([magnitude, direction])
482
+ else:
483
+ self._loads[location] = [[magnitude, direction]]
484
+
485
+ def remove_load(self, location, magnitude, direction):
486
+ """
487
+ This method removes an already
488
+ present external load at a particular node
489
+
490
+ Parameters
491
+ ==========
492
+ location: String or Symbol
493
+ Label of the Node at which load is applied and is to be removed.
494
+
495
+ magnitude: Sympifyable
496
+ Magnitude of the load applied.
497
+
498
+ direction: Sympifyable
499
+ The angle, in degrees, that the load vector makes with the horizontal
500
+ in the counter-clockwise direction. It takes the values 0 to 360,
501
+ inclusive.
502
+
503
+ Examples
504
+ ========
505
+
506
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
507
+ >>> from sympy import symbols
508
+ >>> t = Truss()
509
+ >>> t.add_node('A', 0, 0)
510
+ >>> t.add_node('B', 3, 0)
511
+ >>> P = symbols('P')
512
+ >>> t.apply_load('A', P, 90)
513
+ >>> t.apply_load('A', P/2, 45)
514
+ >>> t.apply_load('A', P/4, 90)
515
+ >>> t.loads
516
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
517
+ >>> t.remove_load('A', P/4, 90)
518
+ >>> t.loads
519
+ {'A': [[P, 90], [P/2, 45]]}
520
+ """
521
+ magnitude = sympify(magnitude)
522
+ direction = sympify(direction)
523
+
524
+ if location not in self.node_labels:
525
+ raise ValueError("Load must be removed from a known node")
526
+
527
+ else:
528
+ if [magnitude, direction] not in self._loads[location]:
529
+ raise ValueError("No load of this magnitude and direction has been applied at this node")
530
+ else:
531
+ self._loads[location].remove([magnitude, direction])
532
+ if self._loads[location] == []:
533
+ self._loads.pop(location)
534
+
535
+ def apply_support(self, location, type):
536
+ """
537
+ This method adds a pinned or roller support at a particular node
538
+
539
+ Parameters
540
+ ==========
541
+
542
+ location: String or Symbol
543
+ Label of the Node at which support is added.
544
+
545
+ type: String
546
+ Type of the support being provided at the node.
547
+
548
+ Examples
549
+ ========
550
+
551
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
552
+ >>> t = Truss()
553
+ >>> t.add_node('A', 0, 0)
554
+ >>> t.add_node('B', 3, 0)
555
+ >>> t.apply_support('A', 'pinned')
556
+ >>> t.supports
557
+ {'A': 'pinned'}
558
+ """
559
+ if location not in self._node_labels:
560
+ raise ValueError("Support must be added on a known node")
561
+
562
+ else:
563
+ if location not in list(self._supports):
564
+ if type == 'pinned':
565
+ self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
566
+ self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
567
+ elif type == 'roller':
568
+ self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
569
+ elif self._supports[location] == 'pinned':
570
+ if type == 'roller':
571
+ self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
572
+ elif self._supports[location] == 'roller':
573
+ if type == 'pinned':
574
+ self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
575
+ self._supports[location] = type
576
+
577
+ def remove_support(self, location):
578
+ """
579
+ This method removes support from a particular node
580
+
581
+ Parameters
582
+ ==========
583
+
584
+ location: String or Symbol
585
+ Label of the Node at which support is to be removed.
586
+
587
+ Examples
588
+ ========
589
+
590
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
591
+ >>> t = Truss()
592
+ >>> t.add_node('A', 0, 0)
593
+ >>> t.add_node('B', 3, 0)
594
+ >>> t.apply_support('A', 'pinned')
595
+ >>> t.supports
596
+ {'A': 'pinned'}
597
+ >>> t.remove_support('A')
598
+ >>> t.supports
599
+ {}
600
+ """
601
+ if location not in self._node_labels:
602
+ raise ValueError("No such node exists in the Truss")
603
+
604
+ elif location not in list(self._supports):
605
+ raise ValueError("No support has been added to the given node")
606
+
607
+ else:
608
+ if self._supports[location] == 'pinned':
609
+ self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
610
+ self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
611
+ elif self._supports[location] == 'roller':
612
+ self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
613
+ self._supports.pop(location)
614
+
615
+ def solve(self):
616
+ """
617
+ This method solves for all reaction forces of all supports and all internal forces
618
+ of all the members in the truss, provided the Truss is solvable.
619
+
620
+ A Truss is solvable if the following condition is met,
621
+
622
+ 2n >= r + m
623
+
624
+ Where n is the number of nodes, r is the number of reaction forces, where each pinned
625
+ support has 2 reaction forces and each roller has 1, and m is the number of members.
626
+
627
+ The given condition is derived from the fact that a system of equations is solvable
628
+ only when the number of variables is lesser than or equal to the number of equations.
629
+ Equilibrium Equations in x and y directions give two equations per node giving 2n number
630
+ equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m.
631
+ The number of variables is simply the sum of the number of reaction forces and member
632
+ forces.
633
+
634
+ .. note::
635
+ The sign convention for the internal forces present in a member revolves around whether each
636
+ force is compressive or tensile. While forming equations for each node, internal force due
637
+ to a member on the node is assumed to be away from the node i.e. each force is assumed to
638
+ be compressive by default. Hence, a positive value for an internal force implies the
639
+ presence of compressive force in the member and a negative value implies a tensile force.
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
645
+ >>> t = Truss()
646
+ >>> t.add_node("node_1", 0, 0)
647
+ >>> t.add_node("node_2", 6, 0)
648
+ >>> t.add_node("node_3", 2, 2)
649
+ >>> t.add_node("node_4", 2, 0)
650
+ >>> t.add_member("member_1", "node_1", "node_4")
651
+ >>> t.add_member("member_2", "node_2", "node_4")
652
+ >>> t.add_member("member_3", "node_1", "node_3")
653
+ >>> t.add_member("member_4", "node_2", "node_3")
654
+ >>> t.add_member("member_5", "node_3", "node_4")
655
+ >>> t.apply_load("node_4", magnitude=10, direction=270)
656
+ >>> t.apply_support("node_1", type="pinned")
657
+ >>> t.apply_support("node_2", type="roller")
658
+ >>> t.solve()
659
+ >>> t.reaction_loads
660
+ {'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3}
661
+ >>> t.internal_forces
662
+ {'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10}
663
+ """
664
+ count_reaction_loads = 0
665
+ for node in self._nodes:
666
+ if node[0] in list(self._supports):
667
+ if self._supports[node[0]]=='pinned':
668
+ count_reaction_loads += 2
669
+ elif self._supports[node[0]]=='roller':
670
+ count_reaction_loads += 1
671
+ if 2*len(self._nodes) != len(self._members) + count_reaction_loads:
672
+ raise ValueError("The given truss cannot be solved")
673
+ coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))]
674
+ load_matrix = zeros(2*len(self.nodes), 1)
675
+ load_matrix_row = 0
676
+ for node in self._nodes:
677
+ if node[0] in list(self._loads):
678
+ for load in self._loads[node[0]]:
679
+ if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'):
680
+ load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180)
681
+ load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180)
682
+ load_matrix_row += 2
683
+ cols = 0
684
+ row = 0
685
+ for node in self._nodes:
686
+ if node[0] in list(self._supports):
687
+ if self._supports[node[0]]=='pinned':
688
+ coefficients_matrix[row][cols] += 1
689
+ coefficients_matrix[row+1][cols+1] += 1
690
+ cols += 2
691
+ elif self._supports[node[0]]=='roller':
692
+ coefficients_matrix[row+1][cols] += 1
693
+ cols += 1
694
+ row += 2
695
+ for member in list(self._members):
696
+ start = self._members[member][0]
697
+ end = self._members[member][1]
698
+ length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2)
699
+ start_index = self._node_labels.index(start)
700
+ end_index = self._node_labels.index(end)
701
+ horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length
702
+ vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length
703
+ horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length
704
+ vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length
705
+ coefficients_matrix[start_index*2][cols] += horizontal_component_start
706
+ coefficients_matrix[start_index*2+1][cols] += vertical_component_start
707
+ coefficients_matrix[end_index*2][cols] += horizontal_component_end
708
+ coefficients_matrix[end_index*2+1][cols] += vertical_component_end
709
+ cols += 1
710
+ forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix
711
+ self._reaction_loads = {}
712
+ i = 0
713
+ min_load = inf
714
+ for node in self._nodes:
715
+ if node[0] in list(self._loads):
716
+ for load in self._loads[node[0]]:
717
+ if type(load[0]) not in [Symbol, Mul, Add]:
718
+ min_load = min(min_load, load[0])
719
+ for j in range(len(forces_matrix)):
720
+ if type(forces_matrix[j]) not in [Symbol, Mul, Add]:
721
+ if abs(forces_matrix[j]/min_load) <1E-10:
722
+ forces_matrix[j] = 0
723
+ for node in self._nodes:
724
+ if node[0] in list(self._supports):
725
+ if self._supports[node[0]]=='pinned':
726
+ self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i]
727
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1]
728
+ i += 2
729
+ elif self._supports[node[0]]=='roller':
730
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i]
731
+ i += 1
732
+ for member in list(self._members):
733
+ self._internal_forces[member] = forces_matrix[i]
734
+ i += 1
735
+ return
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc ADDED
Binary file (53.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import isclose
2
+ from sympy.core.numbers import I
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.functions.elementary.complexes import (Abs, arg)
5
+ from sympy.functions.elementary.exponential import log
6
+ from sympy.abc import s, p, a
7
+ from sympy.external import import_module
8
+ from sympy.physics.control.control_plots import \
9
+ (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
10
+ step_response_plot, impulse_response_numerical_data,
11
+ impulse_response_plot, ramp_response_numerical_data,
12
+ ramp_response_plot, bode_magnitude_numerical_data,
13
+ bode_phase_numerical_data, bode_plot)
14
+ from sympy.physics.control.lti import (TransferFunction,
15
+ Series, Parallel, TransferFunctionMatrix)
16
+ from sympy.testing.pytest import raises, skip
17
+
18
+ matplotlib = import_module(
19
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
20
+ catch=(RuntimeError,))
21
+
22
+ numpy = import_module('numpy')
23
+
24
+ tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
25
+ tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
26
+ tf3 = TransferFunction(p, p**3 - 1, p)
27
+ tf4 = TransferFunction(10, p**3, p)
28
+ tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
29
+ tf6 = TransferFunction(1, 1, s)
30
+ tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
31
+ tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
32
+
33
+ ser1 = Series(tf4, TransferFunction(1, p - 5, p))
34
+ ser2 = Series(tf3, TransferFunction(p, p + 2, p))
35
+
36
+ par1 = Parallel(tf1, tf2)
37
+ par2 = Parallel(tf1, tf2, tf3)
38
+
39
+
40
+ def _to_tuple(a, b):
41
+ return tuple(a), tuple(b)
42
+
43
+ def _trim_tuple(a, b):
44
+ a, b = _to_tuple(a, b)
45
+ return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
46
+ tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
47
+
48
+ def y_coordinate_equality(plot_data_func, evalf_func, system):
49
+ """Checks whether the y-coordinate value of the plotted
50
+ data point is equal to the value of the function at a
51
+ particular x."""
52
+ x, y = plot_data_func(system)
53
+ x, y = _trim_tuple(x, y)
54
+ y_exp = tuple(evalf_func(system, x_i) for x_i in x)
55
+ return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
56
+
57
+
58
+ def test_errors():
59
+ if not matplotlib:
60
+ skip("Matplotlib not the default backend")
61
+
62
+ # Invalid `system` check
63
+ tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
64
+ expr = 1/(s**2 - 1)
65
+ raises(NotImplementedError, lambda: pole_zero_plot(tfm))
66
+ raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
67
+ raises(NotImplementedError, lambda: impulse_response_plot(expr))
68
+ raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
69
+ raises(NotImplementedError, lambda: step_response_plot(tfm))
70
+ raises(NotImplementedError, lambda: step_response_numerical_data(expr))
71
+ raises(NotImplementedError, lambda: ramp_response_plot(expr))
72
+ raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
73
+ raises(NotImplementedError, lambda: bode_plot(tfm))
74
+
75
+ # More than 1 variables
76
+ tf_a = TransferFunction(a, s + 1, s)
77
+ raises(ValueError, lambda: pole_zero_plot(tf_a))
78
+ raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
79
+ raises(ValueError, lambda: impulse_response_plot(tf_a))
80
+ raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
81
+ raises(ValueError, lambda: step_response_plot(tf_a))
82
+ raises(ValueError, lambda: step_response_numerical_data(tf_a))
83
+ raises(ValueError, lambda: ramp_response_plot(tf_a))
84
+ raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
85
+ raises(ValueError, lambda: bode_plot(tf_a))
86
+
87
+ # lower_limit > 0 for response plots
88
+ raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
89
+ raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
90
+ raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
91
+
92
+ # slope in ramp_response_plot() is negative
93
+ raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
94
+
95
+ # incorrect frequency or phase unit
96
+ raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
97
+ raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
98
+
99
+
100
+ def test_pole_zero():
101
+ if not numpy:
102
+ skip("NumPy is required for this test")
103
+
104
+ def pz_tester(sys, expected_value):
105
+ z, p = pole_zero_numerical_data(sys)
106
+ z_check = numpy.allclose(z, expected_value[0])
107
+ p_check = numpy.allclose(p, expected_value[1])
108
+ return p_check and z_check
109
+
110
+ exp1 = [[], [-0.24999999999999994+1.3919410907075054j, -0.24999999999999994-1.3919410907075054j]]
111
+ exp2 = [[0.0], [-0.25+0.3227486121839514j, -0.25-0.3227486121839514j]]
112
+ exp3 = [[0.0], [-0.5000000000000004+0.8660254037844395j,
113
+ -0.5000000000000004-0.8660254037844395j, 0.9999999999999998+0j]]
114
+ exp4 = [[], [5.0, 0.0, 0.0, 0.0]]
115
+ exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
116
+ [-0.24999999999999986+1.3919410907075052j,
117
+ -0.24999999999999986-1.3919410907075052j, -0.2499999999999998+0.32274861218395134j,
118
+ -0.2499999999999998-0.32274861218395134j]]
119
+ exp6 = [[], [-1.1641600331447917-3.545808351896439j,
120
+ -0.8358399668552097+2.5458083518964383j]]
121
+
122
+ assert pz_tester(tf1, exp1)
123
+ assert pz_tester(tf2, exp2)
124
+ assert pz_tester(tf3, exp3)
125
+ assert pz_tester(ser1, exp4)
126
+ assert pz_tester(par1, exp5)
127
+ assert pz_tester(tf8, exp6)
128
+
129
+
130
+ def test_bode():
131
+ if not numpy:
132
+ skip("NumPy is required for this test")
133
+
134
+ def bode_phase_evalf(system, point):
135
+ expr = system.to_expr()
136
+ _w = Dummy("w", real=True)
137
+ w_expr = expr.subs({system.var: I*_w})
138
+ return arg(w_expr).subs({_w: point}).evalf()
139
+
140
+ def bode_mag_evalf(system, point):
141
+ expr = system.to_expr()
142
+ _w = Dummy("w", real=True)
143
+ w_expr = expr.subs({system.var: I*_w})
144
+ return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
145
+
146
+ def test_bode_data(sys):
147
+ return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
148
+ and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
149
+
150
+ assert test_bode_data(tf1)
151
+ assert test_bode_data(tf2)
152
+ assert test_bode_data(tf3)
153
+ assert test_bode_data(tf4)
154
+ assert test_bode_data(tf5)
155
+
156
+
157
+ def check_point_accuracy(a, b):
158
+ return all(isclose(a_i, b_i, rel_tol=10e-12) for \
159
+ a_i, b_i in zip(a, b))
160
+
161
+
162
+ def test_impulse_response():
163
+ if not numpy:
164
+ skip("NumPy is required for this test")
165
+
166
+ def impulse_res_tester(sys, expected_value):
167
+ x, y = _to_tuple(*impulse_response_numerical_data(sys,
168
+ adaptive=False, nb_of_points=10))
169
+ x_check = check_point_accuracy(x, expected_value[0])
170
+ y_check = check_point_accuracy(y, expected_value[1])
171
+ return x_check and y_check
172
+
173
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
174
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
175
+ (0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
176
+ 0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
177
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
178
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
179
+ 0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
180
+ -0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
181
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
182
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
183
+ 3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
184
+ 795.6538758627842, 2416.9920942096983, 7342.159505206647))
185
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
186
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
187
+ 55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
188
+ 395.0617283950618, 500.0))
189
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
190
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
191
+ 0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
192
+ 0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
193
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
194
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
195
+ (-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
196
+ 25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
197
+ -1747.0262164682233))
198
+ exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
199
+ 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
200
+ 8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
201
+ 358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
202
+ 4.147764422869658e+20))
203
+
204
+ assert impulse_res_tester(tf1, exp1)
205
+ assert impulse_res_tester(tf2, exp2)
206
+ assert impulse_res_tester(tf3, exp3)
207
+ assert impulse_res_tester(tf4, exp4)
208
+ assert impulse_res_tester(tf5, exp5)
209
+ assert impulse_res_tester(tf7, exp6)
210
+ assert impulse_res_tester(ser1, exp7)
211
+
212
+
213
+ def test_step_response():
214
+ if not numpy:
215
+ skip("NumPy is required for this test")
216
+
217
+ def step_res_tester(sys, expected_value):
218
+ x, y = _to_tuple(*step_response_numerical_data(sys,
219
+ adaptive=False, nb_of_points=10))
220
+ x_check = check_point_accuracy(x, expected_value[0])
221
+ y_check = check_point_accuracy(y, expected_value[1])
222
+ return x_check and y_check
223
+
224
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
225
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
226
+ (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
227
+ 0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
228
+ 0.4486997874319281, 0.4839358435839171))
229
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
230
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
231
+ (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
232
+ 0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
233
+ -0.003636420058445484))
234
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
235
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
236
+ (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
237
+ 86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
238
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
239
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
240
+ (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
241
+ 493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
242
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
243
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
244
+ (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
245
+ 0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
246
+ 0.49997448824584123, 0.5000039745919259))
247
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
248
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
249
+ (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
250
+ 9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
251
+ 2447.387582370878))
252
+
253
+ assert step_res_tester(tf1, exp1)
254
+ assert step_res_tester(tf2, exp2)
255
+ assert step_res_tester(tf3, exp3)
256
+ assert step_res_tester(tf4, exp4)
257
+ assert step_res_tester(tf5, exp5)
258
+ assert step_res_tester(ser2, exp6)
259
+
260
+
261
+ def test_ramp_response():
262
+ if not numpy:
263
+ skip("NumPy is required for this test")
264
+
265
+ def ramp_res_tester(sys, num_points, expected_value, slope=1):
266
+ x, y = _to_tuple(*ramp_response_numerical_data(sys,
267
+ slope=slope, adaptive=False, nb_of_points=num_points))
268
+ x_check = check_point_accuracy(x, expected_value[0])
269
+ y_check = check_point_accuracy(y, expected_value[1])
270
+ return x_check and y_check
271
+
272
+ exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
273
+ 2.7956587704217783, 3.9224897567931514, 4.85022655284895))
274
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
275
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
276
+ (2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
277
+ 0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
278
+ 1.304684417610106))
279
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
280
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
281
+ 0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
282
+ 391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
283
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
284
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
285
+ 154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
286
+ 7803.688462124678, 12500.0))
287
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
288
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
289
+ 14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
290
+ 39.09983919254265, 44.10006013058409))
291
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
292
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
293
+ 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
294
+
295
+ assert ramp_res_tester(tf1, 6, exp1)
296
+ assert ramp_res_tester(tf2, 10, exp2, 1.2)
297
+ assert ramp_res_tester(tf3, 10, exp3, 1.5)
298
+ assert ramp_res_tester(tf4, 10, exp4, 3)
299
+ assert ramp_res_tester(tf5, 10, exp5, 9)
300
+ assert ramp_res_tester(tf6, 10, exp6)
env-llmeval/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py ADDED
@@ -0,0 +1,1245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.function import Function
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.numbers import (I, Rational, oo)
5
+ from sympy.core.power import Pow
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import symbols
8
+ from sympy.functions.elementary.exponential import exp
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.matrices.dense import eye
11
+ from sympy.polys.polytools import factor
12
+ from sympy.polys.rootoftools import CRootOf
13
+ from sympy.simplify.simplify import simplify
14
+ from sympy.core.containers import Tuple
15
+ from sympy.matrices import ImmutableMatrix, Matrix
16
+ from sympy.physics.control import (TransferFunction, Series, Parallel,
17
+ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback,
18
+ bilinear, backward_diff)
19
+ from sympy.testing.pytest import raises
20
+
21
+ a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn, T = symbols('a, x, b, s, g, d, p, k,\
22
+ a0:3, b0:3, tau, zeta, wn, T')
23
+ TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
24
+ TF2 = TransferFunction(k, 1, s)
25
+ TF3 = TransferFunction(a2*p - s, a2*s + p, s)
26
+
27
+
28
+ def test_TransferFunction_construction():
29
+ tf = TransferFunction(s + 1, s**2 + s + 1, s)
30
+ assert tf.num == (s + 1)
31
+ assert tf.den == (s**2 + s + 1)
32
+ assert tf.args == (s + 1, s**2 + s + 1, s)
33
+
34
+ tf1 = TransferFunction(s + 4, s - 5, s)
35
+ assert tf1.num == (s + 4)
36
+ assert tf1.den == (s - 5)
37
+ assert tf1.args == (s + 4, s - 5, s)
38
+
39
+ # using different polynomial variables.
40
+ tf2 = TransferFunction(p + 3, p**2 - 9, p)
41
+ assert tf2.num == (p + 3)
42
+ assert tf2.den == (p**2 - 9)
43
+ assert tf2.args == (p + 3, p**2 - 9, p)
44
+
45
+ tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
46
+ assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
47
+
48
+ # no pole-zero cancellation on its own.
49
+ tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
50
+ assert tf4.den == (s - 1)*(s + 5)
51
+ assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
52
+
53
+ tf4_ = TransferFunction(p + 2, p + 2, p)
54
+ assert tf4_.args == (p + 2, p + 2, p)
55
+
56
+ tf5 = TransferFunction(s - 1, 4 - p, s)
57
+ assert tf5.args == (s - 1, 4 - p, s)
58
+
59
+ tf5_ = TransferFunction(s - 1, s - 1, s)
60
+ assert tf5_.args == (s - 1, s - 1, s)
61
+
62
+ tf6 = TransferFunction(5, 6, s)
63
+ assert tf6.num == 5
64
+ assert tf6.den == 6
65
+ assert tf6.args == (5, 6, s)
66
+
67
+ tf6_ = TransferFunction(1/2, 4, s)
68
+ assert tf6_.num == 0.5
69
+ assert tf6_.den == 4
70
+ assert tf6_.args == (0.500000000000000, 4, s)
71
+
72
+ tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
73
+ tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
74
+ assert not tf7 == tf8
75
+
76
+ tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
77
+ tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
78
+ assert tf7_ == tf8_
79
+ assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
80
+
81
+ tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
82
+ assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
83
+
84
+ tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
85
+ tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
86
+ assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
87
+ assert tf10_ == tf10
88
+
89
+ tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
90
+ assert tf11.num == (a0 + a1*s)
91
+ assert tf11.den == (b0 + b1*s + b2*s**2)
92
+ assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
93
+
94
+ # when just the numerator is 0, leave the denominator alone.
95
+ tf12 = TransferFunction(0, p**2 - p + 1, p)
96
+ assert tf12.args == (0, p**2 - p + 1, p)
97
+
98
+ tf13 = TransferFunction(0, 1, s)
99
+ assert tf13.args == (0, 1, s)
100
+
101
+ # float exponents
102
+ tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
103
+ assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
104
+
105
+ tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
106
+ assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
107
+
108
+ omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
109
+ tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
110
+ assert tf18.num == k_i/s + k_o*s + k_p
111
+ assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
112
+
113
+ # ValueError when denominator is zero.
114
+ raises(ValueError, lambda: TransferFunction(4, 0, s))
115
+ raises(ValueError, lambda: TransferFunction(s, 0, s))
116
+ raises(ValueError, lambda: TransferFunction(0, 0, s))
117
+
118
+ raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
119
+
120
+ raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
121
+ raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
122
+ raises(TypeError, lambda: TransferFunction(3, 4, 8))
123
+
124
+
125
+ def test_TransferFunction_functions():
126
+ # classmethod from_rational_expression
127
+ expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
128
+ expr_2 = s/0
129
+ expr_3 = (p*s**2 + 5*s)/(s + 1)**3
130
+ expr_4 = 6
131
+ expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
132
+ expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
133
+ tf = TransferFunction(s + 1, s**2 + 2, s)
134
+ delay = exp(-s/tau)
135
+ expr_7 = delay*tf.to_expr()
136
+ H1 = TransferFunction.from_rational_expression(expr_7, s)
137
+ H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
138
+ expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
139
+
140
+ assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
141
+ raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
142
+ raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
143
+ assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
144
+ assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
145
+ raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
146
+ assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
147
+ assert TransferFunction.from_rational_expression(expr_5, s) == \
148
+ TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
149
+ assert TransferFunction.from_rational_expression(expr_6, s) == \
150
+ TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
151
+ assert H1 == H2
152
+ assert TransferFunction.from_rational_expression(expr_8, s) == \
153
+ TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
154
+
155
+ # explicitly cancel poles and zeros.
156
+ tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
157
+ a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
158
+ assert tf0.simplify() == simplify(tf0) == a
159
+
160
+ tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
161
+ b = TransferFunction(p + 3, p + 5, p)
162
+ assert tf1.simplify() == simplify(tf1) == b
163
+
164
+ # expand the numerator and the denominator.
165
+ G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
166
+ G2 = TransferFunction(1, -3, p)
167
+ c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
168
+ d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
169
+ e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
170
+ f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
171
+ g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
172
+ G3 = TransferFunction(c, d, s)
173
+ G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
174
+
175
+ assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
176
+ assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
177
+ assert G2.expand() == G2
178
+ assert G3.expand() == TransferFunction(e, f, s)
179
+ assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
180
+
181
+ # purely symbolic polynomials.
182
+ p1 = a1*s + a0
183
+ p2 = b2*s**2 + b1*s + b0
184
+ SP1 = TransferFunction(p1, p2, s)
185
+ expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
186
+ expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
187
+ assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
188
+ assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
189
+ assert expect1_.evalf() == expect1
190
+
191
+ c1, d0, d1, d2 = symbols('c1, d0:3')
192
+ p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
193
+ SP2 = TransferFunction(p3, p4, p)
194
+ expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
195
+ expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
196
+ assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
197
+ assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
198
+ assert expect2_.evalf() == expect2
199
+
200
+ SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
201
+ expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
202
+ expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
203
+ assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
204
+ assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
205
+ assert expect3_.evalf() == expect3
206
+
207
+ SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
208
+ expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
209
+ expect4_ = TransferFunction(7*p**3 + s, p - s, p)
210
+ assert SP4.subs({a0: -1, a1: -7}) == expect4_
211
+ assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
212
+ assert expect4_.evalf() == expect4
213
+
214
+ # Low-frequency (or DC) gain.
215
+ assert tf0.dc_gain() == 1
216
+ assert tf1.dc_gain() == Rational(3, 5)
217
+ assert SP2.dc_gain() == 0
218
+ assert expect4.dc_gain() == -1
219
+ assert expect2_.dc_gain() == 0
220
+ assert TransferFunction(1, s, s).dc_gain() == oo
221
+
222
+ # Poles of a transfer function.
223
+ tf_ = TransferFunction(x**3 - k, k, x)
224
+ _tf = TransferFunction(k, x**4 - k, x)
225
+ TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
226
+ _TF = TransferFunction(x**10 + x + x**2, x**2, x)
227
+ assert G1.poles() == [I, I, -I, -I]
228
+ assert G2.poles() == []
229
+ assert tf1.poles() == [-5, 1]
230
+ assert expect4_.poles() == [s]
231
+ assert SP4.poles() == [-a0*s]
232
+ assert expect3.poles() == [-0.25*p]
233
+ assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
234
+ assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
235
+ assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
236
+ assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
237
+ CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
238
+ CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
239
+ raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
240
+
241
+ # Stability of a transfer function.
242
+ q, r = symbols('q, r', negative=True)
243
+ t = symbols('t', positive=True)
244
+ TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
245
+ stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
246
+ stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
247
+
248
+ assert G1.is_stable() is False
249
+ assert G2.is_stable() is True
250
+ assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
251
+ assert expect2.is_stable() is False
252
+ assert expect1.is_stable() is True
253
+ assert stable_tf.is_stable() is True
254
+ assert stable_tf_.is_stable() is True
255
+ assert TF_.is_stable() is False
256
+ assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
257
+ assert SP4.is_stable() is None
258
+
259
+ # Zeros of a transfer function.
260
+ assert G1.zeros() == [1, 1]
261
+ assert G2.zeros() == []
262
+ assert tf1.zeros() == [-3, 1]
263
+ assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
264
+ sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
265
+ assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
266
+ -(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
267
+ assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
268
+ 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
269
+ assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
270
+ -k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
271
+ assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
272
+ CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
273
+ CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
274
+ raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
275
+
276
+ # negation of TF.
277
+ tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
278
+ tf3 = TransferFunction(-3*p + 3, 1 - p, p)
279
+ assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
280
+ assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
281
+
282
+ # taking power of a TF.
283
+ tf4 = TransferFunction(p + 4, p - 3, p)
284
+ tf5 = TransferFunction(s**2 + 1, 1 - s, s)
285
+ expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
286
+ expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
287
+ assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
288
+ assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
289
+ assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
290
+ assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
291
+ assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
292
+
293
+ raises(ValueError, lambda: tf4**(s**2 + s - 1))
294
+ raises(ValueError, lambda: tf5**s)
295
+ raises(ValueError, lambda: tf4**tf5)
296
+
297
+ # SymPy's own functions.
298
+ tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
299
+ tf6 = TransferFunction(s + p, p**2 - 5, s)
300
+ assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
301
+ assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
302
+ # subs & xreplace
303
+ assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
304
+ assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
305
+ assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
306
+ raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
307
+ assert tf3.subs(p, exp(2)) == tf3
308
+
309
+ tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
310
+ assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
311
+ assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
312
+
313
+ # Conversion to Expr with to_expr()
314
+ tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
315
+ tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
316
+ tf10 = TransferFunction(0, 1, s)
317
+ tf11 = TransferFunction(1, 1, s)
318
+ assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
319
+ assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
320
+ assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
321
+ assert tf11.to_expr() == Pow(1, -1, evaluate=False)
322
+
323
+ def test_TransferFunction_addition_and_subtraction():
324
+ tf1 = TransferFunction(s + 6, s - 5, s)
325
+ tf2 = TransferFunction(s + 3, s + 1, s)
326
+ tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
327
+ tf4 = TransferFunction(p, 2 - p, p)
328
+
329
+ # addition
330
+ assert tf1 + tf2 == Parallel(tf1, tf2)
331
+ assert tf3 + tf1 == Parallel(tf3, tf1)
332
+ assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
333
+ assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
334
+
335
+ c = symbols("c", commutative=False)
336
+ raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
337
+ raises(ValueError, lambda: tf2 + c)
338
+ raises(ValueError, lambda: tf3 + tf4)
339
+ raises(ValueError, lambda: tf1 + (s - 1))
340
+ raises(ValueError, lambda: tf1 + 8)
341
+ raises(ValueError, lambda: (1 - p**3) + tf1)
342
+
343
+ # subtraction
344
+ assert tf1 - tf2 == Parallel(tf1, -tf2)
345
+ assert tf3 - tf2 == Parallel(tf3, -tf2)
346
+ assert -tf1 - tf3 == Parallel(-tf1, -tf3)
347
+ assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
348
+
349
+ raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
350
+ raises(ValueError, lambda: tf3 - tf4)
351
+ raises(ValueError, lambda: tf1 - (s - 1))
352
+ raises(ValueError, lambda: tf1 - 8)
353
+ raises(ValueError, lambda: (s + 5) - tf2)
354
+ raises(ValueError, lambda: (1 + p**4) - tf1)
355
+
356
+
357
+ def test_TransferFunction_multiplication_and_division():
358
+ G1 = TransferFunction(s + 3, -s**3 + 9, s)
359
+ G2 = TransferFunction(s + 1, s - 5, s)
360
+ G3 = TransferFunction(p, p**4 - 6, p)
361
+ G4 = TransferFunction(p + 4, p - 5, p)
362
+ G5 = TransferFunction(s + 6, s - 5, s)
363
+ G6 = TransferFunction(s + 3, s + 1, s)
364
+ G7 = TransferFunction(1, 1, s)
365
+
366
+ # multiplication
367
+ assert G1*G2 == Series(G1, G2)
368
+ assert -G1*G5 == Series(-G1, G5)
369
+ assert -G2*G5*-G6 == Series(-G2, G5, -G6)
370
+ assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
371
+ assert G3*G4 == Series(G3, G4)
372
+ assert (G1*G2)*-(G5*G6) == \
373
+ Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
374
+ assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
375
+
376
+ c = symbols("c", commutative=False)
377
+ raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
378
+ raises(ValueError, lambda: G1 * c)
379
+ raises(ValueError, lambda: G3 * G5)
380
+ raises(ValueError, lambda: G5 * (s - 1))
381
+ raises(ValueError, lambda: 9 * G5)
382
+
383
+ raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
384
+ raises(ValueError, lambda: G6 / 0)
385
+ raises(ValueError, lambda: G3 / G5)
386
+ raises(ValueError, lambda: G5 / 2)
387
+ raises(ValueError, lambda: G5 / s**2)
388
+ raises(ValueError, lambda: (s - 4*s**2) / G2)
389
+ raises(ValueError, lambda: 0 / G4)
390
+ raises(ValueError, lambda: G5 / G6)
391
+ raises(ValueError, lambda: -G3 /G4)
392
+ raises(ValueError, lambda: G7 / (1 + G6))
393
+ raises(ValueError, lambda: G7 / (G5 * G6))
394
+ raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
395
+
396
+
397
+ def test_TransferFunction_is_proper():
398
+ omega_o, zeta, tau = symbols('omega_o, zeta, tau')
399
+ G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
400
+ G2 = TransferFunction(tau - s**3, tau + p**4, tau)
401
+ G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
402
+ G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
403
+ assert G1.is_proper
404
+ assert G2.is_proper
405
+ assert G3.is_proper
406
+ assert not G4.is_proper
407
+
408
+
409
+ def test_TransferFunction_is_strictly_proper():
410
+ omega_o, zeta, tau = symbols('omega_o, zeta, tau')
411
+ tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
412
+ tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
413
+ tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
414
+ tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
415
+ assert not tf1.is_strictly_proper
416
+ assert not tf2.is_strictly_proper
417
+ assert tf3.is_strictly_proper
418
+ assert not tf4.is_strictly_proper
419
+
420
+
421
+ def test_TransferFunction_is_biproper():
422
+ tau, omega_o, zeta = symbols('tau, omega_o, zeta')
423
+ tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
424
+ tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
425
+ tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
426
+ tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
427
+ assert tf1.is_biproper
428
+ assert tf2.is_biproper
429
+ assert not tf3.is_biproper
430
+ assert not tf4.is_biproper
431
+
432
+
433
+ def test_Series_construction():
434
+ tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
435
+ tf2 = TransferFunction(a2*p - s, a2*s + p, s)
436
+ tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
437
+ tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
438
+ inp = Function('X_d')(s)
439
+ out = Function('X')(s)
440
+
441
+ s0 = Series(tf, tf2)
442
+ assert s0.args == (tf, tf2)
443
+ assert s0.var == s
444
+
445
+ s1 = Series(Parallel(tf, -tf2), tf2)
446
+ assert s1.args == (Parallel(tf, -tf2), tf2)
447
+ assert s1.var == s
448
+
449
+ tf3_ = TransferFunction(inp, 1, s)
450
+ tf4_ = TransferFunction(-out, 1, s)
451
+ s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
452
+ assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
453
+
454
+ s3 = Series(tf, tf2, tf4)
455
+ assert s3.args == (tf, tf2, tf4)
456
+
457
+ s4 = Series(tf3_, tf4_)
458
+ assert s4.args == (tf3_, tf4_)
459
+ assert s4.var == s
460
+
461
+ s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
462
+ assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
463
+
464
+ s7 = Series(tf, tf2)
465
+ assert s0 == s7
466
+ assert not s0 == s2
467
+
468
+ raises(ValueError, lambda: Series(tf, tf3))
469
+ raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
470
+ raises(ValueError, lambda: Series(-tf3, tf2))
471
+ raises(TypeError, lambda: Series(2, tf, tf4))
472
+ raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
473
+ raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
474
+
475
+
476
+ def test_MIMOSeries_construction():
477
+ tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
478
+ tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
479
+ tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
480
+
481
+ tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
482
+ tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
483
+ tfm_3 = TransferFunctionMatrix([[-tf_3]])
484
+ tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
485
+ tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
486
+
487
+ s8 = MIMOSeries(tfm_2, tfm_1)
488
+ assert s8.args == (tfm_2, tfm_1)
489
+ assert s8.var == s
490
+ assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
491
+
492
+ s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
493
+ assert s9.args == (tfm_3, tfm_2, tfm_1)
494
+ assert s9.var == s
495
+ assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
496
+
497
+ s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
498
+ assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
499
+ assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
500
+
501
+ # arg cannot be empty tuple.
502
+ raises(ValueError, lambda: MIMOSeries())
503
+
504
+ # arg cannot contain SISO as well as MIMO systems.
505
+ raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
506
+
507
+ # for all the adjacent transfer function matrices:
508
+ # no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
509
+ raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
510
+
511
+ # all the TFMs must use the same complex variable.
512
+ raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
513
+
514
+ # Number or expression not allowed in the arguments.
515
+ raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
516
+ raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
517
+ raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
518
+
519
+
520
+ def test_Series_functions():
521
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
522
+ tf2 = TransferFunction(k, 1, s)
523
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
524
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
525
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
526
+
527
+ assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
528
+ == Series(tf1, Series(tf2, tf3))
529
+ assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
530
+ assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
531
+ assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
532
+ assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
533
+ assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
534
+ assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
535
+ assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
536
+ assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
537
+ assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
538
+ assert -tf1*tf2 == Series(-tf1, tf2)
539
+ assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
540
+ raises(ValueError, lambda: tf1*tf2*tf4)
541
+ raises(ValueError, lambda: tf1*(tf2 - tf4))
542
+ raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
543
+
544
+ # evaluate=True -> doit()
545
+ assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
546
+ TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
547
+ assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
548
+ TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
549
+ assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
550
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
551
+ assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
552
+
553
+ assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
554
+ TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
555
+ assert Series(-tf1, -tf2, -tf3).doit() == \
556
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
557
+ assert -Series(tf1, tf2, tf3).doit() == \
558
+ TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
559
+ assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
560
+ TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
561
+
562
+ assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
563
+ assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
564
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
565
+
566
+ S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
567
+ assert S1.is_proper
568
+ assert not S1.is_strictly_proper
569
+ assert S1.is_biproper
570
+
571
+ S2 = Series(tf1, tf2, tf3)
572
+ assert S2.is_proper
573
+ assert S2.is_strictly_proper
574
+ assert not S2.is_biproper
575
+
576
+ S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
577
+ assert S3.is_proper
578
+ assert S3.is_strictly_proper
579
+ assert not S3.is_biproper
580
+
581
+
582
+ def test_MIMOSeries_functions():
583
+ tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
584
+ tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
585
+ tfm3 = TransferFunctionMatrix([[-TF1]])
586
+ tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
587
+ tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
588
+ tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
589
+ tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
590
+
591
+ assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
592
+ assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
593
+ assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
594
+ assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
595
+ assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
596
+
597
+ raises(ValueError, lambda: tfm1*tfm2 + TF1)
598
+ raises(TypeError, lambda: tfm1*tfm2 + a0)
599
+ raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
600
+ raises(TypeError, lambda: tfm4*-tfm6 - 8)
601
+ raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
602
+
603
+ # Shape criteria.
604
+
605
+ raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
606
+ raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
607
+ raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
608
+
609
+ assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
610
+ assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
611
+
612
+ # Multiplication of a Series object with a SISO TF not allowed.
613
+
614
+ raises(ValueError, lambda: tfm4*tfm5*TF1)
615
+ raises(TypeError, lambda: tfm4*tfm5*a1)
616
+ raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
617
+ raises(TypeError, lambda: tfm5*tfm4*9)
618
+ raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
619
+
620
+ # Transfer function matrix in the arguments.
621
+ assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
622
+ == TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
623
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
624
+ (TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
625
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
626
+
627
+ # doit() should not cancel poles and zeros.
628
+ mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
629
+ mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
630
+ tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
631
+ assert (MIMOSeries(tm_2, tm_1).doit()
632
+ == TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
633
+ assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
634
+
635
+ # calling doit() will expand the internal Series and Parallel objects.
636
+ assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
637
+ == MIMOSeries(-tfm3, -tfm2, tfm1).doit()
638
+ == TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
639
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
640
+ (TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
641
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
642
+ assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
643
+ == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
644
+ == TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
645
+ k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
646
+ TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
647
+
648
+
649
+ def test_Parallel_construction():
650
+ tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
651
+ tf2 = TransferFunction(a2*p - s, a2*s + p, s)
652
+ tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
653
+ tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
654
+ inp = Function('X_d')(s)
655
+ out = Function('X')(s)
656
+
657
+ p0 = Parallel(tf, tf2)
658
+ assert p0.args == (tf, tf2)
659
+ assert p0.var == s
660
+
661
+ p1 = Parallel(Series(tf, -tf2), tf2)
662
+ assert p1.args == (Series(tf, -tf2), tf2)
663
+ assert p1.var == s
664
+
665
+ tf3_ = TransferFunction(inp, 1, s)
666
+ tf4_ = TransferFunction(-out, 1, s)
667
+ p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
668
+ assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
669
+
670
+ p3 = Parallel(tf, tf2, tf4)
671
+ assert p3.args == (tf, tf2, tf4)
672
+
673
+ p4 = Parallel(tf3_, tf4_)
674
+ assert p4.args == (tf3_, tf4_)
675
+ assert p4.var == s
676
+
677
+ p5 = Parallel(tf, tf2)
678
+ assert p0 == p5
679
+ assert not p0 == p1
680
+
681
+ p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
682
+ assert p6.args == (tf2, tf4, Series(tf2, -tf4))
683
+
684
+ p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
685
+ assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
686
+
687
+ raises(ValueError, lambda: Parallel(tf, tf3))
688
+ raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
689
+ raises(ValueError, lambda: Parallel(-tf3, tf4))
690
+ raises(TypeError, lambda: Parallel(2, tf, tf4))
691
+ raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
692
+ raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
693
+
694
+
695
+ def test_MIMOParallel_construction():
696
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
697
+ tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
698
+ tfm3 = TransferFunctionMatrix([[TF1]])
699
+ tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
700
+ tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
701
+ tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
702
+ tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
703
+
704
+ p8 = MIMOParallel(tfm1, tfm2)
705
+ assert p8.args == (tfm1, tfm2)
706
+ assert p8.var == s
707
+ assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
708
+
709
+ p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
710
+ assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
711
+ assert p9.var == s
712
+ assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
713
+
714
+ p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
715
+ assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
716
+ assert p10.var == s
717
+ assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
718
+
719
+ p11 = MIMOParallel(tfm2, tfm1, tfm4)
720
+ assert p11.args == (tfm2, tfm1, tfm4)
721
+ assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
722
+
723
+ p12 = MIMOParallel(tfm6, tfm5)
724
+ assert p12.args == (tfm6, tfm5)
725
+ assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
726
+
727
+ p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
728
+ assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
729
+ assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
730
+
731
+ # arg cannot be empty tuple.
732
+ raises(TypeError, lambda: MIMOParallel(()))
733
+
734
+ # arg cannot contain SISO as well as MIMO systems.
735
+ raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
736
+
737
+ # all TFMs must have same shapes.
738
+ raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
739
+
740
+ # all TFMs must be using the same complex variable.
741
+ raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
742
+
743
+ # Number or expression not allowed in the arguments.
744
+ raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
745
+ raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
746
+
747
+
748
+ def test_Parallel_functions():
749
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
750
+ tf2 = TransferFunction(k, 1, s)
751
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
752
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
753
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
754
+
755
+ assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
756
+ assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
757
+ assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
758
+ assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
759
+ assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
760
+ assert -tf1 - tf2 == Parallel(-tf1, -tf2)
761
+ assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
762
+ assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
763
+ assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
764
+ assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
765
+ assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
766
+ assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
767
+ assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
768
+ raises(ValueError, lambda: tf1 + tf2 + tf4)
769
+ raises(ValueError, lambda: tf1 - tf2*tf4)
770
+ raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
771
+
772
+ # evaluate=True -> doit()
773
+ assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
774
+ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
775
+ assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
776
+ Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
777
+ (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
778
+ 2*s*wn*zeta + wn**2)**2, s)
779
+ assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
780
+ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
781
+ , (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
782
+ assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
783
+
784
+ assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
785
+ TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
786
+ assert Parallel(-tf1, -tf2, -tf3).doit() == \
787
+ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
788
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
789
+ assert -Parallel(tf1, tf2, tf3).doit() == \
790
+ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
791
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
792
+ assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
793
+ TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
794
+ + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
795
+
796
+ assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
797
+ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
798
+ assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
799
+ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
800
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
801
+
802
+ assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
803
+
804
+ P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
805
+ assert P1.is_proper
806
+ assert not P1.is_strictly_proper
807
+ assert P1.is_biproper
808
+
809
+ P2 = Parallel(tf1, -tf2, -tf3)
810
+ assert P2.is_proper
811
+ assert not P2.is_strictly_proper
812
+ assert P2.is_biproper
813
+
814
+ P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
815
+ assert P3.is_proper
816
+ assert not P3.is_strictly_proper
817
+ assert P3.is_biproper
818
+
819
+
820
+ def test_MIMOParallel_functions():
821
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
822
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
823
+
824
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
825
+ tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
826
+ tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
827
+ tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
828
+ tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
829
+ tfm6 = TransferFunctionMatrix([[-TF2]])
830
+ tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
831
+
832
+ assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
833
+ assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
834
+ assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
835
+ assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
836
+ assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
837
+ assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
838
+ raises(ValueError, lambda: tfm1 + tfm2 + TF2)
839
+ raises(TypeError, lambda: tfm1 - tfm2 - a1)
840
+ raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
841
+ raises(TypeError, lambda: -tfm3 - tfm2 - 9)
842
+ raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
843
+ # All TFMs must use the same complex var. tfm7 uses 'p'.
844
+ raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
845
+ raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
846
+ # (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
847
+ raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
848
+ raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
849
+
850
+ assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
851
+ assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
852
+ assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
853
+ raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
854
+ raises(TypeError, lambda: (tfm2 - tfm3)*a2)
855
+ raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
856
+ raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
857
+ raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
858
+
859
+ # (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
860
+ raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
861
+ # (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
862
+ raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
863
+
864
+ # TFM in the arguments.
865
+ assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
866
+ == MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
867
+ == TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
868
+ (TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
869
+ (s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
870
+
871
+
872
+ def test_Feedback_construction():
873
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
874
+ tf2 = TransferFunction(k, 1, s)
875
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
876
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
877
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
878
+ tf6 = TransferFunction(s - p, p + s, p)
879
+
880
+ f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
881
+ assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
882
+ assert f1.sys1 == TransferFunction(1, 1, s)
883
+ assert f1.sys2 == Series(tf1, tf2, tf3)
884
+ assert f1.var == s
885
+
886
+ f2 = Feedback(tf1, tf2*tf3)
887
+ assert f2.args == (tf1, Series(tf2, tf3), -1)
888
+ assert f2.sys1 == tf1
889
+ assert f2.sys2 == Series(tf2, tf3)
890
+ assert f2.var == s
891
+
892
+ f3 = Feedback(tf1*tf2, tf5)
893
+ assert f3.args == (Series(tf1, tf2), tf5, -1)
894
+ assert f3.sys1 == Series(tf1, tf2)
895
+
896
+ f4 = Feedback(tf4, tf6)
897
+ assert f4.args == (tf4, tf6, -1)
898
+ assert f4.sys1 == tf4
899
+ assert f4.var == p
900
+
901
+ f5 = Feedback(tf5, TransferFunction(1, 1, s))
902
+ assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
903
+ assert f5.var == s
904
+ assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
905
+
906
+ f6 = Feedback(TransferFunction(1, 1, p), tf4)
907
+ assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
908
+ assert f6.var == p
909
+
910
+ f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
911
+ assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
912
+ assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
913
+
914
+ # denominator can't be a Parallel instance
915
+ raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
916
+ raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
917
+ raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
918
+ raises(TypeError, lambda: Feedback(1, 1))
919
+ # raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
920
+ raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
921
+ raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
922
+ raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
923
+ raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
924
+
925
+
926
+ def test_Feedback_functions():
927
+ tf = TransferFunction(1, 1, s)
928
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
929
+ tf2 = TransferFunction(k, 1, s)
930
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
931
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
932
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
933
+ tf6 = TransferFunction(s - p, p + s, p)
934
+
935
+ assert tf / (tf + tf1) == Feedback(tf, tf1)
936
+ assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
937
+ assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
938
+ assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
939
+ assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
940
+ assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
941
+ assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
942
+ assert tf5 / (tf + tf5) == Feedback(tf5, tf)
943
+
944
+ raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
945
+ raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5)
946
+ raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
947
+
948
+ assert Feedback(tf, tf1*tf2*tf3).doit() == \
949
+ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
950
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
951
+ assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
952
+ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
953
+ assert Feedback(tf1, tf2*tf3).doit() == \
954
+ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
955
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
956
+ assert Feedback(tf1, tf2*tf3).sensitivity == \
957
+ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
958
+ assert Feedback(tf1*tf2, tf5).doit() == \
959
+ TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
960
+ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
961
+ assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
962
+ 1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
963
+ assert Feedback(tf4, tf6).doit() == \
964
+ TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
965
+ assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
966
+ TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
967
+ assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
968
+
969
+ assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
970
+ TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
971
+ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
972
+ assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
973
+ TransferFunction(p, a0*p + p + p**a1 - s, p)
974
+
975
+
976
+ def test_MIMOFeedback_construction():
977
+ tf1 = TransferFunction(1, s, s)
978
+ tf2 = TransferFunction(s, s**3 - 1, s)
979
+ tf3 = TransferFunction(s, s + 1, s)
980
+ tf4 = TransferFunction(s, s**2 + 1, s)
981
+
982
+ tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
983
+ tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
984
+ tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
985
+
986
+ f1 = MIMOFeedback(tfm_1, tfm_2)
987
+ assert f1.args == (tfm_1, tfm_2, -1)
988
+ assert f1.sys1 == tfm_1
989
+ assert f1.sys2 == tfm_2
990
+ assert f1.var == s
991
+ assert f1.sign == -1
992
+ assert -(-f1) == f1
993
+
994
+ f2 = MIMOFeedback(tfm_2, tfm_1, 1)
995
+ assert f2.args == (tfm_2, tfm_1, 1)
996
+ assert f2.sys1 == tfm_2
997
+ assert f2.sys2 == tfm_1
998
+ assert f2.var == s
999
+ assert f2.sign == 1
1000
+
1001
+ f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
1002
+ assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
1003
+ assert f3.sys1 == tfm_1
1004
+ assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
1005
+ assert f3.var == s
1006
+ assert f3.sign == -1
1007
+
1008
+ mat = Matrix([[1, 1/s], [0, 1]])
1009
+ sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
1010
+ f4 = MIMOFeedback(sys1, controller)
1011
+ assert f4.args == (sys1, controller, -1)
1012
+ assert f4.sys1 == f4.sys2 == sys1
1013
+
1014
+
1015
+ def test_MIMOFeedback_errors():
1016
+ tf1 = TransferFunction(1, s, s)
1017
+ tf2 = TransferFunction(s, s**3 - 1, s)
1018
+ tf3 = TransferFunction(s, s - 1, s)
1019
+ tf4 = TransferFunction(s, s**2 + 1, s)
1020
+ tf5 = TransferFunction(1, 1, s)
1021
+ tf6 = TransferFunction(-1, s - 1, s)
1022
+
1023
+ tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
1024
+ tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
1025
+ tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
1026
+ tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
1027
+ tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
1028
+ # tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
1029
+ tfm_6 = TransferFunctionMatrix([[-tf3]])
1030
+ tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
1031
+
1032
+ # Unsupported Types
1033
+ raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
1034
+ raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
1035
+ # Shape Errors
1036
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
1037
+ raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
1038
+ # sign not 1/-1
1039
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
1040
+ # Non-Invertible Systems
1041
+ raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
1042
+ raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
1043
+ raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
1044
+ # Variable not same in both the systems
1045
+ tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
1046
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
1047
+
1048
+
1049
+ def test_MIMOFeedback_functions():
1050
+ tf1 = TransferFunction(1, s, s)
1051
+ tf2 = TransferFunction(s, s - 1, s)
1052
+ tf3 = TransferFunction(1, 1, s)
1053
+ tf4 = TransferFunction(-1, s - 1, s)
1054
+
1055
+ tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
1056
+ tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
1057
+ tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
1058
+ tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
1059
+
1060
+ # sensitivity, doit(), rewrite()
1061
+ F_1 = MIMOFeedback(tfm_2, tfm_3)
1062
+ F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
1063
+
1064
+ assert F_1.sensitivity == Matrix([[S.Half, 0], [0, S.Half]])
1065
+ assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
1066
+ (2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
1067
+
1068
+ assert F_1.doit() == \
1069
+ TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
1070
+ TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
1071
+ TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
1072
+ assert F_2.doit(cancel=False, expand=True) == \
1073
+ TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
1074
+ TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1075
+ assert F_2.doit(cancel=False) == \
1076
+ TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
1077
+ (-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
1078
+ (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1079
+ assert F_2.doit() == \
1080
+ TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
1081
+ TransferFunction(-2*s**3*(s - 1), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
1082
+ assert F_2.doit(expand=True) == \
1083
+ TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
1084
+ (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1085
+
1086
+ assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
1087
+
1088
+
1089
+ def test_TransferFunctionMatrix_construction():
1090
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
1091
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
1092
+
1093
+ tfm3_ = TransferFunctionMatrix([[-TF3]])
1094
+ assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
1095
+ assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
1096
+ assert tfm3_.var == s
1097
+
1098
+ tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
1099
+ assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
1100
+ assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
1101
+ assert tfm5.var == s
1102
+
1103
+ tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
1104
+ assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
1105
+ assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
1106
+ assert tfm7.var == s
1107
+
1108
+ # all transfer functions will use the same complex variable. tf4 uses 'p'.
1109
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
1110
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
1111
+
1112
+ # length of all the lists in the TFM should be equal.
1113
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
1114
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
1115
+
1116
+ # lists should only support transfer functions in them.
1117
+ raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
1118
+ raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
1119
+
1120
+ # `arg` should strictly be nested list of TransferFunction
1121
+ raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
1122
+ raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
1123
+
1124
+ def test_TransferFunctionMatrix_functions():
1125
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
1126
+
1127
+ # Classmethod (from_matrix)
1128
+
1129
+ mat_1 = ImmutableMatrix([
1130
+ [s*(s + 1)*(s - 3)/(s**4 + 1), 2],
1131
+ [p, p*(s + 1)/(s*(s**1 + 1))]
1132
+ ])
1133
+ mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
1134
+ mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
1135
+ assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
1136
+ TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
1137
+ [TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
1138
+ assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
1139
+ TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
1140
+ assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
1141
+ TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
1142
+ [TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
1143
+
1144
+ # Negating a TFM
1145
+
1146
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
1147
+ assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
1148
+
1149
+ tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
1150
+ assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
1151
+
1152
+ # subs()
1153
+
1154
+ H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
1155
+ H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
1156
+ assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
1157
+ assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
1158
+ assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
1159
+ assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
1160
+ assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
1161
+ assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
1162
+ assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
1163
+
1164
+ # transpose()
1165
+
1166
+ assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
1167
+ assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
1168
+ assert H_1.transpose().transpose() == H_1
1169
+ assert H_2.transpose().transpose() == H_2
1170
+
1171
+ # elem_poles()
1172
+
1173
+ assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
1174
+ [[], [0]]]
1175
+ assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
1176
+ assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
1177
+ [[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
1178
+
1179
+ # elem_zeros()
1180
+
1181
+ assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
1182
+ assert H_2.elem_zeros() == [[[0], [0]]]
1183
+ assert tfm2.elem_zeros() == [[[], [], [a2*p]],
1184
+ [[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
1185
+
1186
+ # doit()
1187
+
1188
+ H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
1189
+ H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
1190
+
1191
+ assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
1192
+ assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
1193
+
1194
+ # _flat()
1195
+
1196
+ assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
1197
+ assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
1198
+ assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
1199
+ assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
1200
+
1201
+ # evalf()
1202
+
1203
+ assert H_1.evalf() == \
1204
+ TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
1205
+ assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
1206
+ TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
1207
+ TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
1208
+
1209
+ # simplify()
1210
+
1211
+ H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
1212
+ TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
1213
+
1214
+ assert H_5.simplify() == simplify(H_5) == \
1215
+ TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
1216
+
1217
+ # expand()
1218
+
1219
+ assert (H_1.expand()
1220
+ == TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
1221
+ (TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
1222
+ assert H_5.expand() == \
1223
+ TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
1224
+
1225
+ def test_TransferFunction_bilinear():
1226
+ # simple transfer function, e.g. ohms law
1227
+ tf = TransferFunction(1, a*s+b, s)
1228
+ numZ, denZ = bilinear(tf, T)
1229
+ # discretized transfer function with coefs from tf.bilinear()
1230
+ tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
1231
+ # corresponding tf with manually calculated coefs
1232
+ tf_test_manual = TransferFunction(s*T+T, s*(T*b+2*a)+T*b-2*a, s)
1233
+
1234
+ assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
1235
+
1236
+ def test_TransferFunction_backward_diff():
1237
+ # simple transfer function, e.g. ohms law
1238
+ tf = TransferFunction(1, a*s+b, s)
1239
+ numZ, denZ = backward_diff(tf, T)
1240
+ # discretized transfer function with coefs from tf.bilinear()
1241
+ tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
1242
+ # corresponding tf with manually calculated coefs
1243
+ tf_test_manual = TransferFunction(s*T, s*(T*b+a)-a, s)
1244
+
1245
+ assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
env-llmeval/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)
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc ADDED
Binary file (23.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc ADDED
Binary file (79.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc ADDED
Binary file (8.77 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc ADDED
Binary file (5.58 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc ADDED
Binary file (8.46 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
env-llmeval/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)
env-llmeval/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.')
env-llmeval/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)
env-llmeval/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)
env-llmeval/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
env-llmeval/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
env-llmeval/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
env-llmeval/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.")
env-llmeval/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
env-llmeval/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)
env-llmeval/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)
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_body.cpython-310.pyc ADDED
Binary file (9.43 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_functions.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc ADDED
Binary file (39.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_jointsmethod.cpython-310.pyc ADDED
Binary file (8.35 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane2.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane3.cpython-310.pyc ADDED
Binary file (5.44 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_kane4.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange.cpython-310.pyc ADDED
Binary file (6.15 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc ADDED
Binary file (1.2 kB). View file