ZTWHHH commited on
Commit
aa889aa
·
verified ·
1 Parent(s): ef76aa4

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. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py +90 -0
  2. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/actuator.py +992 -0
  3. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/inertia.py +197 -0
  4. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py +2188 -0
  5. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py +318 -0
  6. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py +860 -0
  7. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py +474 -0
  8. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/loads.py +177 -0
  9. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/method.py +39 -0
  10. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/models.py +230 -0
  11. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py +209 -0
  12. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/pathway.py +688 -0
  13. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py +314 -0
  14. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_actuator.py +851 -0
  15. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py +262 -0
  16. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py +553 -0
  17. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py +46 -0
  18. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py +5 -0
  19. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py +117 -0
  20. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_particle.py +78 -0
  21. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_rigidbody.py +184 -0
  22. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py +245 -0
  23. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_wrapping_geometry.py +363 -0
  24. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/wrapping_geometry.py +641 -0
  25. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/gaussopt.cpython-310.pyc +0 -0
  26. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/polarization.cpython-310.pyc +0 -0
  27. evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/utils.cpython-310.pyc +0 -0
  28. evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/__init__.cpython-310.pyc +0 -0
  29. evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/configuration_utils.cpython-310.pyc +0 -0
  30. evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/dependency_versions_table.cpython-310.pyc +0 -0
  31. evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/image_processor.cpython-310.pyc +0 -0
  32. evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/__init__.py +27 -0
  33. evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/diffusers_cli.py +43 -0
  34. evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/env.py +84 -0
  35. evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/fp16_safetensors.py +132 -0
  36. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_amused.cpython-310.pyc +0 -0
  37. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_consistency_decoder.cpython-310.pyc +0 -0
  38. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_consistency_models.cpython-310.pyc +0 -0
  39. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddim.cpython-310.pyc +0 -0
  40. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddim_flax.cpython-310.pyc +0 -0
  41. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddpm.cpython-310.pyc +0 -0
  42. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddpm_parallel.cpython-310.pyc +0 -0
  43. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_deis_multistep.cpython-310.pyc +0 -0
  44. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep.cpython-310.pyc +0 -0
  45. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep_flax.cpython-310.pyc +0 -0
  46. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep_inverse.cpython-310.pyc +0 -0
  47. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_sde.cpython-310.pyc +0 -0
  48. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_edm_dpmsolver_multistep.cpython-310.pyc +0 -0
  49. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_euler_discrete_flax.cpython-310.pyc +0 -0
  50. evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_k_dpm_2_discrete.cpython-310.pyc +0 -0
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'vector',
3
+
4
+ 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross',
5
+ 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations',
6
+ 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint',
7
+ 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl',
8
+ 'divergence', 'gradient', 'is_conservative', 'is_solenoidal',
9
+ 'scalar_potential', 'scalar_potential_difference',
10
+
11
+ 'KanesMethod',
12
+
13
+ 'RigidBody',
14
+
15
+ 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy',
16
+ 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint',
17
+ 'mlatex', 'msubs', 'find_dynamicsymbols',
18
+
19
+ 'inertia', 'inertia_of_point_mass', 'Inertia',
20
+
21
+ 'Force', 'Torque',
22
+
23
+ 'Particle',
24
+
25
+ 'LagrangesMethod',
26
+
27
+ 'Linearizer',
28
+
29
+ 'Body',
30
+
31
+ 'SymbolicSystem', 'System',
32
+
33
+ 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint',
34
+ 'SphericalJoint', 'WeldJoint',
35
+
36
+ 'JointsMethod',
37
+
38
+ 'WrappingCylinder', 'WrappingGeometryBase', 'WrappingSphere',
39
+
40
+ 'PathwayBase', 'LinearPathway', 'ObstacleSetPathway', 'WrappingPathway',
41
+
42
+ 'ActuatorBase', 'ForceActuator', 'LinearDamper', 'LinearSpring',
43
+ 'TorqueActuator', 'DuffingSpring'
44
+ ]
45
+
46
+ from sympy.physics import vector
47
+
48
+ from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point,
49
+ cross, dot, express, time_derivative, outer, kinematic_equations,
50
+ get_motion_params, partial_velocity, dynamicsymbols, vprint,
51
+ vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence,
52
+ gradient, is_conservative, is_solenoidal, scalar_potential,
53
+ scalar_potential_difference)
54
+
55
+ from .kane import KanesMethod
56
+
57
+ from .rigidbody import RigidBody
58
+
59
+ from .functions import (linear_momentum, angular_momentum, kinetic_energy,
60
+ potential_energy, Lagrangian, mechanics_printing,
61
+ mprint, msprint, mpprint, mlatex, msubs,
62
+ find_dynamicsymbols)
63
+
64
+ from .inertia import inertia, inertia_of_point_mass, Inertia
65
+
66
+ from .loads import Force, Torque
67
+
68
+ from .particle import Particle
69
+
70
+ from .lagrange import LagrangesMethod
71
+
72
+ from .linearize import Linearizer
73
+
74
+ from .body import Body
75
+
76
+ from .system import SymbolicSystem, System
77
+
78
+ from .jointsmethod import JointsMethod
79
+
80
+ from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint,
81
+ SphericalJoint, WeldJoint)
82
+
83
+ from .wrapping_geometry import (WrappingCylinder, WrappingGeometryBase,
84
+ WrappingSphere)
85
+
86
+ from .pathway import (PathwayBase, LinearPathway, ObstacleSetPathway,
87
+ WrappingPathway)
88
+
89
+ from .actuator import (ActuatorBase, ForceActuator, LinearDamper, LinearSpring,
90
+ TorqueActuator, DuffingSpring)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/actuator.py ADDED
@@ -0,0 +1,992 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of actuators for linked force and torque application."""
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy import S, sympify
6
+ from sympy.physics.mechanics.joint import PinJoint
7
+ from sympy.physics.mechanics.loads import Torque
8
+ from sympy.physics.mechanics.pathway import PathwayBase
9
+ from sympy.physics.mechanics.rigidbody import RigidBody
10
+ from sympy.physics.vector import ReferenceFrame, Vector
11
+
12
+
13
+ __all__ = [
14
+ 'ActuatorBase',
15
+ 'ForceActuator',
16
+ 'LinearDamper',
17
+ 'LinearSpring',
18
+ 'TorqueActuator',
19
+ 'DuffingSpring'
20
+ ]
21
+
22
+
23
+ class ActuatorBase(ABC):
24
+ """Abstract base class for all actuator classes to inherit from.
25
+
26
+ Notes
27
+ =====
28
+
29
+ Instances of this class cannot be directly instantiated by users. However,
30
+ it can be used to created custom actuator types through subclassing.
31
+
32
+ """
33
+
34
+ def __init__(self):
35
+ """Initializer for ``ActuatorBase``."""
36
+ pass
37
+
38
+ @abstractmethod
39
+ def to_loads(self):
40
+ """Loads required by the equations of motion method classes.
41
+
42
+ Explanation
43
+ ===========
44
+
45
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
46
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
47
+ when constructing the equations of motion. This method acts as a
48
+ utility to produce the correctly-structred pairs of points and vectors
49
+ required so that these can be easily concatenated with other items in
50
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
51
+ loads are also in the correct form to also be passed to the other
52
+ equations of motion method classes, e.g. ``LagrangesMethod``.
53
+
54
+ """
55
+ pass
56
+
57
+ def __repr__(self):
58
+ """Default representation of an actuator."""
59
+ return f'{self.__class__.__name__}()'
60
+
61
+
62
+ class ForceActuator(ActuatorBase):
63
+ """Force-producing actuator.
64
+
65
+ Explanation
66
+ ===========
67
+
68
+ A ``ForceActuator`` is an actuator that produces a (expansile) force along
69
+ its length.
70
+
71
+ A force actuator uses a pathway instance to determine the direction and
72
+ number of forces that it applies to a system. Consider the simplest case
73
+ where a ``LinearPathway`` instance is used. This pathway is made up of two
74
+ points that can move relative to each other, and results in a pair of equal
75
+ and opposite forces acting on the endpoints. If the positive time-varying
76
+ Euclidean distance between the two points is defined, then the "extension
77
+ velocity" is the time derivative of this distance. The extension velocity
78
+ is positive when the two points are moving away from each other and
79
+ negative when moving closer to each other. The direction for the force
80
+ acting on either point is determined by constructing a unit vector directed
81
+ from the other point to this point. This establishes a sign convention such
82
+ that a positive force magnitude tends to push the points apart, this is the
83
+ meaning of "expansile" in this context. The following diagram shows the
84
+ positive force sense and the distance between the points::
85
+
86
+ P Q
87
+ o<--- F --->o
88
+ | |
89
+ |<--l(t)--->|
90
+
91
+ Examples
92
+ ========
93
+
94
+ To construct an actuator, an expression (or symbol) must be supplied to
95
+ represent the force it can produce, alongside a pathway specifying its line
96
+ of action. Let's also create a global reference frame and spatially fix one
97
+ of the points in it while setting the other to be positioned such that it
98
+ can freely move in the frame's x direction specified by the coordinate
99
+ ``q``.
100
+
101
+ >>> from sympy import symbols
102
+ >>> from sympy.physics.mechanics import (ForceActuator, LinearPathway,
103
+ ... Point, ReferenceFrame)
104
+ >>> from sympy.physics.vector import dynamicsymbols
105
+ >>> N = ReferenceFrame('N')
106
+ >>> q = dynamicsymbols('q')
107
+ >>> force = symbols('F')
108
+ >>> pA, pB = Point('pA'), Point('pB')
109
+ >>> pA.set_vel(N, 0)
110
+ >>> pB.set_pos(pA, q*N.x)
111
+ >>> pB.pos_from(pA)
112
+ q(t)*N.x
113
+ >>> linear_pathway = LinearPathway(pA, pB)
114
+ >>> actuator = ForceActuator(force, linear_pathway)
115
+ >>> actuator
116
+ ForceActuator(F, LinearPathway(pA, pB))
117
+
118
+ Parameters
119
+ ==========
120
+
121
+ force : Expr
122
+ The scalar expression defining the (expansile) force that the actuator
123
+ produces.
124
+ pathway : PathwayBase
125
+ The pathway that the actuator follows. This must be an instance of a
126
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
127
+
128
+ """
129
+
130
+ def __init__(self, force, pathway):
131
+ """Initializer for ``ForceActuator``.
132
+
133
+ Parameters
134
+ ==========
135
+
136
+ force : Expr
137
+ The scalar expression defining the (expansile) force that the
138
+ actuator produces.
139
+ pathway : PathwayBase
140
+ The pathway that the actuator follows. This must be an instance of
141
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
142
+
143
+ """
144
+ self.force = force
145
+ self.pathway = pathway
146
+
147
+ @property
148
+ def force(self):
149
+ """The magnitude of the force produced by the actuator."""
150
+ return self._force
151
+
152
+ @force.setter
153
+ def force(self, force):
154
+ if hasattr(self, '_force'):
155
+ msg = (
156
+ f'Can\'t set attribute `force` to {repr(force)} as it is '
157
+ f'immutable.'
158
+ )
159
+ raise AttributeError(msg)
160
+ self._force = sympify(force, strict=True)
161
+
162
+ @property
163
+ def pathway(self):
164
+ """The ``Pathway`` defining the actuator's line of action."""
165
+ return self._pathway
166
+
167
+ @pathway.setter
168
+ def pathway(self, pathway):
169
+ if hasattr(self, '_pathway'):
170
+ msg = (
171
+ f'Can\'t set attribute `pathway` to {repr(pathway)} as it is '
172
+ f'immutable.'
173
+ )
174
+ raise AttributeError(msg)
175
+ if not isinstance(pathway, PathwayBase):
176
+ msg = (
177
+ f'Value {repr(pathway)} passed to `pathway` was of type '
178
+ f'{type(pathway)}, must be {PathwayBase}.'
179
+ )
180
+ raise TypeError(msg)
181
+ self._pathway = pathway
182
+
183
+ def to_loads(self):
184
+ """Loads required by the equations of motion method classes.
185
+
186
+ Explanation
187
+ ===========
188
+
189
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
190
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
191
+ when constructing the equations of motion. This method acts as a
192
+ utility to produce the correctly-structred pairs of points and vectors
193
+ required so that these can be easily concatenated with other items in
194
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
195
+ loads are also in the correct form to also be passed to the other
196
+ equations of motion method classes, e.g. ``LagrangesMethod``.
197
+
198
+ Examples
199
+ ========
200
+
201
+ The below example shows how to generate the loads produced by a force
202
+ actuator that follows a linear pathway. In this example we'll assume
203
+ that the force actuator is being used to model a simple linear spring.
204
+ First, create a linear pathway between two points separated by the
205
+ coordinate ``q`` in the ``x`` direction of the global frame ``N``.
206
+
207
+ >>> from sympy.physics.mechanics import (LinearPathway, Point,
208
+ ... ReferenceFrame)
209
+ >>> from sympy.physics.vector import dynamicsymbols
210
+ >>> q = dynamicsymbols('q')
211
+ >>> N = ReferenceFrame('N')
212
+ >>> pA, pB = Point('pA'), Point('pB')
213
+ >>> pB.set_pos(pA, q*N.x)
214
+ >>> pathway = LinearPathway(pA, pB)
215
+
216
+ Now create a symbol ``k`` to describe the spring's stiffness and
217
+ instantiate a force actuator that produces a (contractile) force
218
+ proportional to both the spring's stiffness and the pathway's length.
219
+ Note that actuator classes use the sign convention that expansile
220
+ forces are positive, so for a spring to produce a contractile force the
221
+ spring force needs to be calculated as the negative for the stiffness
222
+ multiplied by the length.
223
+
224
+ >>> from sympy import symbols
225
+ >>> from sympy.physics.mechanics import ForceActuator
226
+ >>> stiffness = symbols('k')
227
+ >>> spring_force = -stiffness*pathway.length
228
+ >>> spring = ForceActuator(spring_force, pathway)
229
+
230
+ The forces produced by the spring can be generated in the list of loads
231
+ form that ``KanesMethod`` (and other equations of motion methods)
232
+ requires by calling the ``to_loads`` method.
233
+
234
+ >>> spring.to_loads()
235
+ [(pA, k*q(t)*N.x), (pB, - k*q(t)*N.x)]
236
+
237
+ A simple linear damper can be modeled in a similar way. Create another
238
+ symbol ``c`` to describe the dampers damping coefficient. This time
239
+ instantiate a force actuator that produces a force proportional to both
240
+ the damper's damping coefficient and the pathway's extension velocity.
241
+ Note that the damping force is negative as it acts in the opposite
242
+ direction to which the damper is changing in length.
243
+
244
+ >>> damping_coefficient = symbols('c')
245
+ >>> damping_force = -damping_coefficient*pathway.extension_velocity
246
+ >>> damper = ForceActuator(damping_force, pathway)
247
+
248
+ Again, the forces produces by the damper can be generated by calling
249
+ the ``to_loads`` method.
250
+
251
+ >>> damper.to_loads()
252
+ [(pA, c*Derivative(q(t), t)*N.x), (pB, - c*Derivative(q(t), t)*N.x)]
253
+
254
+ """
255
+ return self.pathway.to_loads(self.force)
256
+
257
+ def __repr__(self):
258
+ """Representation of a ``ForceActuator``."""
259
+ return f'{self.__class__.__name__}({self.force}, {self.pathway})'
260
+
261
+
262
+ class LinearSpring(ForceActuator):
263
+ """A spring with its spring force as a linear function of its length.
264
+
265
+ Explanation
266
+ ===========
267
+
268
+ Note that the "linear" in the name ``LinearSpring`` refers to the fact that
269
+ the spring force is a linear function of the springs length. I.e. for a
270
+ linear spring with stiffness ``k``, distance between its ends of ``x``, and
271
+ an equilibrium length of ``0``, the spring force will be ``-k*x``, which is
272
+ a linear function in ``x``. To create a spring that follows a linear, or
273
+ straight, pathway between its two ends, a ``LinearPathway`` instance needs
274
+ to be passed to the ``pathway`` parameter.
275
+
276
+ A ``LinearSpring`` is a subclass of ``ForceActuator`` and so follows the
277
+ same sign conventions for length, extension velocity, and the direction of
278
+ the forces it applies to its points of attachment on bodies. The sign
279
+ convention for the direction of forces is such that, for the case where a
280
+ linear spring is instantiated with a ``LinearPathway`` instance as its
281
+ pathway, they act to push the two ends of the spring away from one another.
282
+ Because springs produces a contractile force and acts to pull the two ends
283
+ together towards the equilibrium length when stretched, the scalar portion
284
+ of the forces on the endpoint are negative in order to flip the sign of the
285
+ forces on the endpoints when converted into vector quantities. The
286
+ following diagram shows the positive force sense and the distance between
287
+ the points::
288
+
289
+ P Q
290
+ o<--- F --->o
291
+ | |
292
+ |<--l(t)--->|
293
+
294
+ Examples
295
+ ========
296
+
297
+ To construct a linear spring, an expression (or symbol) must be supplied to
298
+ represent the stiffness (spring constant) of the spring, alongside a
299
+ pathway specifying its line of action. Let's also create a global reference
300
+ frame and spatially fix one of the points in it while setting the other to
301
+ be positioned such that it can freely move in the frame's x direction
302
+ specified by the coordinate ``q``.
303
+
304
+ >>> from sympy import symbols
305
+ >>> from sympy.physics.mechanics import (LinearPathway, LinearSpring,
306
+ ... Point, ReferenceFrame)
307
+ >>> from sympy.physics.vector import dynamicsymbols
308
+ >>> N = ReferenceFrame('N')
309
+ >>> q = dynamicsymbols('q')
310
+ >>> stiffness = symbols('k')
311
+ >>> pA, pB = Point('pA'), Point('pB')
312
+ >>> pA.set_vel(N, 0)
313
+ >>> pB.set_pos(pA, q*N.x)
314
+ >>> pB.pos_from(pA)
315
+ q(t)*N.x
316
+ >>> linear_pathway = LinearPathway(pA, pB)
317
+ >>> spring = LinearSpring(stiffness, linear_pathway)
318
+ >>> spring
319
+ LinearSpring(k, LinearPathway(pA, pB))
320
+
321
+ This spring will produce a force that is proportional to both its stiffness
322
+ and the pathway's length. Note that this force is negative as SymPy's sign
323
+ convention for actuators is that negative forces are contractile.
324
+
325
+ >>> spring.force
326
+ -k*sqrt(q(t)**2)
327
+
328
+ To create a linear spring with a non-zero equilibrium length, an expression
329
+ (or symbol) can be passed to the ``equilibrium_length`` parameter on
330
+ construction on a ``LinearSpring`` instance. Let's create a symbol ``l``
331
+ to denote a non-zero equilibrium length and create another linear spring.
332
+
333
+ >>> l = symbols('l')
334
+ >>> spring = LinearSpring(stiffness, linear_pathway, equilibrium_length=l)
335
+ >>> spring
336
+ LinearSpring(k, LinearPathway(pA, pB), equilibrium_length=l)
337
+
338
+ The spring force of this new spring is again proportional to both its
339
+ stiffness and the pathway's length. However, the spring will not produce
340
+ any force when ``q(t)`` equals ``l``. Note that the force will become
341
+ expansile when ``q(t)`` is less than ``l``, as expected.
342
+
343
+ >>> spring.force
344
+ -k*(-l + sqrt(q(t)**2))
345
+
346
+ Parameters
347
+ ==========
348
+
349
+ stiffness : Expr
350
+ The spring constant.
351
+ pathway : PathwayBase
352
+ The pathway that the actuator follows. This must be an instance of a
353
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
354
+ equilibrium_length : Expr, optional
355
+ The length at which the spring is in equilibrium, i.e. it produces no
356
+ force. The default value is 0, i.e. the spring force is a linear
357
+ function of the pathway's length with no constant offset.
358
+
359
+ See Also
360
+ ========
361
+
362
+ ForceActuator: force-producing actuator (superclass of ``LinearSpring``).
363
+ LinearPathway: straight-line pathway between a pair of points.
364
+
365
+ """
366
+
367
+ def __init__(self, stiffness, pathway, equilibrium_length=S.Zero):
368
+ """Initializer for ``LinearSpring``.
369
+
370
+ Parameters
371
+ ==========
372
+
373
+ stiffness : Expr
374
+ The spring constant.
375
+ pathway : PathwayBase
376
+ The pathway that the actuator follows. This must be an instance of
377
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
378
+ equilibrium_length : Expr, optional
379
+ The length at which the spring is in equilibrium, i.e. it produces
380
+ no force. The default value is 0, i.e. the spring force is a linear
381
+ function of the pathway's length with no constant offset.
382
+
383
+ """
384
+ self.stiffness = stiffness
385
+ self.pathway = pathway
386
+ self.equilibrium_length = equilibrium_length
387
+
388
+ @property
389
+ def force(self):
390
+ """The spring force produced by the linear spring."""
391
+ return -self.stiffness*(self.pathway.length - self.equilibrium_length)
392
+
393
+ @force.setter
394
+ def force(self, force):
395
+ raise AttributeError('Can\'t set computed attribute `force`.')
396
+
397
+ @property
398
+ def stiffness(self):
399
+ """The spring constant for the linear spring."""
400
+ return self._stiffness
401
+
402
+ @stiffness.setter
403
+ def stiffness(self, stiffness):
404
+ if hasattr(self, '_stiffness'):
405
+ msg = (
406
+ f'Can\'t set attribute `stiffness` to {repr(stiffness)} as it '
407
+ f'is immutable.'
408
+ )
409
+ raise AttributeError(msg)
410
+ self._stiffness = sympify(stiffness, strict=True)
411
+
412
+ @property
413
+ def equilibrium_length(self):
414
+ """The length of the spring at which it produces no force."""
415
+ return self._equilibrium_length
416
+
417
+ @equilibrium_length.setter
418
+ def equilibrium_length(self, equilibrium_length):
419
+ if hasattr(self, '_equilibrium_length'):
420
+ msg = (
421
+ f'Can\'t set attribute `equilibrium_length` to '
422
+ f'{repr(equilibrium_length)} as it is immutable.'
423
+ )
424
+ raise AttributeError(msg)
425
+ self._equilibrium_length = sympify(equilibrium_length, strict=True)
426
+
427
+ def __repr__(self):
428
+ """Representation of a ``LinearSpring``."""
429
+ string = f'{self.__class__.__name__}({self.stiffness}, {self.pathway}'
430
+ if self.equilibrium_length == S.Zero:
431
+ string += ')'
432
+ else:
433
+ string += f', equilibrium_length={self.equilibrium_length})'
434
+ return string
435
+
436
+
437
+ class LinearDamper(ForceActuator):
438
+ """A damper whose force is a linear function of its extension velocity.
439
+
440
+ Explanation
441
+ ===========
442
+
443
+ Note that the "linear" in the name ``LinearDamper`` refers to the fact that
444
+ the damping force is a linear function of the damper's rate of change in
445
+ its length. I.e. for a linear damper with damping ``c`` and extension
446
+ velocity ``v``, the damping force will be ``-c*v``, which is a linear
447
+ function in ``v``. To create a damper that follows a linear, or straight,
448
+ pathway between its two ends, a ``LinearPathway`` instance needs to be
449
+ passed to the ``pathway`` parameter.
450
+
451
+ A ``LinearDamper`` is a subclass of ``ForceActuator`` and so follows the
452
+ same sign conventions for length, extension velocity, and the direction of
453
+ the forces it applies to its points of attachment on bodies. The sign
454
+ convention for the direction of forces is such that, for the case where a
455
+ linear damper is instantiated with a ``LinearPathway`` instance as its
456
+ pathway, they act to push the two ends of the damper away from one another.
457
+ Because dampers produce a force that opposes the direction of change in
458
+ length, when extension velocity is positive the scalar portions of the
459
+ forces applied at the two endpoints are negative in order to flip the sign
460
+ of the forces on the endpoints wen converted into vector quantities. When
461
+ extension velocity is negative (i.e. when the damper is shortening), the
462
+ scalar portions of the fofces applied are also negative so that the signs
463
+ cancel producing forces on the endpoints that are in the same direction as
464
+ the positive sign convention for the forces at the endpoints of the pathway
465
+ (i.e. they act to push the endpoints away from one another). The following
466
+ diagram shows the positive force sense and the distance between the
467
+ points::
468
+
469
+ P Q
470
+ o<--- F --->o
471
+ | |
472
+ |<--l(t)--->|
473
+
474
+ Examples
475
+ ========
476
+
477
+ To construct a linear damper, an expression (or symbol) must be supplied to
478
+ represent the damping coefficient of the damper (we'll use the symbol
479
+ ``c``), alongside a pathway specifying its line of action. Let's also
480
+ create a global reference frame and spatially fix one of the points in it
481
+ while setting the other to be positioned such that it can freely move in
482
+ the frame's x direction specified by the coordinate ``q``. The velocity
483
+ that the two points move away from one another can be specified by the
484
+ coordinate ``u`` where ``u`` is the first time derivative of ``q``
485
+ (i.e., ``u = Derivative(q(t), t)``).
486
+
487
+ >>> from sympy import symbols
488
+ >>> from sympy.physics.mechanics import (LinearDamper, LinearPathway,
489
+ ... Point, ReferenceFrame)
490
+ >>> from sympy.physics.vector import dynamicsymbols
491
+ >>> N = ReferenceFrame('N')
492
+ >>> q = dynamicsymbols('q')
493
+ >>> damping = symbols('c')
494
+ >>> pA, pB = Point('pA'), Point('pB')
495
+ >>> pA.set_vel(N, 0)
496
+ >>> pB.set_pos(pA, q*N.x)
497
+ >>> pB.pos_from(pA)
498
+ q(t)*N.x
499
+ >>> pB.vel(N)
500
+ Derivative(q(t), t)*N.x
501
+ >>> linear_pathway = LinearPathway(pA, pB)
502
+ >>> damper = LinearDamper(damping, linear_pathway)
503
+ >>> damper
504
+ LinearDamper(c, LinearPathway(pA, pB))
505
+
506
+ This damper will produce a force that is proportional to both its damping
507
+ coefficient and the pathway's extension length. Note that this force is
508
+ negative as SymPy's sign convention for actuators is that negative forces
509
+ are contractile and the damping force of the damper will oppose the
510
+ direction of length change.
511
+
512
+ >>> damper.force
513
+ -c*sqrt(q(t)**2)*Derivative(q(t), t)/q(t)
514
+
515
+ Parameters
516
+ ==========
517
+
518
+ damping : Expr
519
+ The damping constant.
520
+ pathway : PathwayBase
521
+ The pathway that the actuator follows. This must be an instance of a
522
+ concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
523
+
524
+ See Also
525
+ ========
526
+
527
+ ForceActuator: force-producing actuator (superclass of ``LinearDamper``).
528
+ LinearPathway: straight-line pathway between a pair of points.
529
+
530
+ """
531
+
532
+ def __init__(self, damping, pathway):
533
+ """Initializer for ``LinearDamper``.
534
+
535
+ Parameters
536
+ ==========
537
+
538
+ damping : Expr
539
+ The damping constant.
540
+ pathway : PathwayBase
541
+ The pathway that the actuator follows. This must be an instance of
542
+ a concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
543
+
544
+ """
545
+ self.damping = damping
546
+ self.pathway = pathway
547
+
548
+ @property
549
+ def force(self):
550
+ """The damping force produced by the linear damper."""
551
+ return -self.damping*self.pathway.extension_velocity
552
+
553
+ @force.setter
554
+ def force(self, force):
555
+ raise AttributeError('Can\'t set computed attribute `force`.')
556
+
557
+ @property
558
+ def damping(self):
559
+ """The damping constant for the linear damper."""
560
+ return self._damping
561
+
562
+ @damping.setter
563
+ def damping(self, damping):
564
+ if hasattr(self, '_damping'):
565
+ msg = (
566
+ f'Can\'t set attribute `damping` to {repr(damping)} as it is '
567
+ f'immutable.'
568
+ )
569
+ raise AttributeError(msg)
570
+ self._damping = sympify(damping, strict=True)
571
+
572
+ def __repr__(self):
573
+ """Representation of a ``LinearDamper``."""
574
+ return f'{self.__class__.__name__}({self.damping}, {self.pathway})'
575
+
576
+
577
+ class TorqueActuator(ActuatorBase):
578
+ """Torque-producing actuator.
579
+
580
+ Explanation
581
+ ===========
582
+
583
+ A ``TorqueActuator`` is an actuator that produces a pair of equal and
584
+ opposite torques on a pair of bodies.
585
+
586
+ Examples
587
+ ========
588
+
589
+ To construct a torque actuator, an expression (or symbol) must be supplied
590
+ to represent the torque it can produce, alongside a vector specifying the
591
+ axis about which the torque will act, and a pair of frames on which the
592
+ torque will act.
593
+
594
+ >>> from sympy import symbols
595
+ >>> from sympy.physics.mechanics import (ReferenceFrame, RigidBody,
596
+ ... TorqueActuator)
597
+ >>> N = ReferenceFrame('N')
598
+ >>> A = ReferenceFrame('A')
599
+ >>> torque = symbols('T')
600
+ >>> axis = N.z
601
+ >>> parent = RigidBody('parent', frame=N)
602
+ >>> child = RigidBody('child', frame=A)
603
+ >>> bodies = (child, parent)
604
+ >>> actuator = TorqueActuator(torque, axis, *bodies)
605
+ >>> actuator
606
+ TorqueActuator(T, axis=N.z, target_frame=A, reaction_frame=N)
607
+
608
+ Note that because torques actually act on frames, not bodies,
609
+ ``TorqueActuator`` will extract the frame associated with a ``RigidBody``
610
+ when one is passed instead of a ``ReferenceFrame``.
611
+
612
+ Parameters
613
+ ==========
614
+
615
+ torque : Expr
616
+ The scalar expression defining the torque that the actuator produces.
617
+ axis : Vector
618
+ The axis about which the actuator applies torques.
619
+ target_frame : ReferenceFrame | RigidBody
620
+ The primary frame on which the actuator will apply the torque.
621
+ reaction_frame : ReferenceFrame | RigidBody | None
622
+ The secondary frame on which the actuator will apply the torque. Note
623
+ that the (equal and opposite) reaction torque is applied to this frame.
624
+
625
+ """
626
+
627
+ def __init__(self, torque, axis, target_frame, reaction_frame=None):
628
+ """Initializer for ``TorqueActuator``.
629
+
630
+ Parameters
631
+ ==========
632
+
633
+ torque : Expr
634
+ The scalar expression defining the torque that the actuator
635
+ produces.
636
+ axis : Vector
637
+ The axis about which the actuator applies torques.
638
+ target_frame : ReferenceFrame | RigidBody
639
+ The primary frame on which the actuator will apply the torque.
640
+ reaction_frame : ReferenceFrame | RigidBody | None
641
+ The secondary frame on which the actuator will apply the torque.
642
+ Note that the (equal and opposite) reaction torque is applied to
643
+ this frame.
644
+
645
+ """
646
+ self.torque = torque
647
+ self.axis = axis
648
+ self.target_frame = target_frame
649
+ self.reaction_frame = reaction_frame
650
+
651
+ @classmethod
652
+ def at_pin_joint(cls, torque, pin_joint):
653
+ """Alternate construtor to instantiate from a ``PinJoint`` instance.
654
+
655
+ Examples
656
+ ========
657
+
658
+ To create a pin joint the ``PinJoint`` class requires a name, parent
659
+ body, and child body to be passed to its constructor. It is also
660
+ possible to control the joint axis using the ``joint_axis`` keyword
661
+ argument. In this example let's use the parent body's reference frame's
662
+ z-axis as the joint axis.
663
+
664
+ >>> from sympy.physics.mechanics import (PinJoint, ReferenceFrame,
665
+ ... RigidBody, TorqueActuator)
666
+ >>> N = ReferenceFrame('N')
667
+ >>> A = ReferenceFrame('A')
668
+ >>> parent = RigidBody('parent', frame=N)
669
+ >>> child = RigidBody('child', frame=A)
670
+ >>> pin_joint = PinJoint(
671
+ ... 'pin',
672
+ ... parent,
673
+ ... child,
674
+ ... joint_axis=N.z,
675
+ ... )
676
+
677
+ Let's also create a symbol ``T`` that will represent the torque applied
678
+ by the torque actuator.
679
+
680
+ >>> from sympy import symbols
681
+ >>> torque = symbols('T')
682
+
683
+ To create the torque actuator from the ``torque`` and ``pin_joint``
684
+ variables previously instantiated, these can be passed to the alternate
685
+ constructor class method ``at_pin_joint`` of the ``TorqueActuator``
686
+ class. It should be noted that a positive torque will cause a positive
687
+ displacement of the joint coordinate or that the torque is applied on
688
+ the child body with a reaction torque on the parent.
689
+
690
+ >>> actuator = TorqueActuator.at_pin_joint(torque, pin_joint)
691
+ >>> actuator
692
+ TorqueActuator(T, axis=N.z, target_frame=A, reaction_frame=N)
693
+
694
+ Parameters
695
+ ==========
696
+
697
+ torque : Expr
698
+ The scalar expression defining the torque that the actuator
699
+ produces.
700
+ pin_joint : PinJoint
701
+ The pin joint, and by association the parent and child bodies, on
702
+ which the torque actuator will act. The pair of bodies acted upon
703
+ by the torque actuator are the parent and child bodies of the pin
704
+ joint, with the child acting as the reaction body. The pin joint's
705
+ axis is used as the axis about which the torque actuator will apply
706
+ its torque.
707
+
708
+ """
709
+ if not isinstance(pin_joint, PinJoint):
710
+ msg = (
711
+ f'Value {repr(pin_joint)} passed to `pin_joint` was of type '
712
+ f'{type(pin_joint)}, must be {PinJoint}.'
713
+ )
714
+ raise TypeError(msg)
715
+ return cls(
716
+ torque,
717
+ pin_joint.joint_axis,
718
+ pin_joint.child_interframe,
719
+ pin_joint.parent_interframe,
720
+ )
721
+
722
+ @property
723
+ def torque(self):
724
+ """The magnitude of the torque produced by the actuator."""
725
+ return self._torque
726
+
727
+ @torque.setter
728
+ def torque(self, torque):
729
+ if hasattr(self, '_torque'):
730
+ msg = (
731
+ f'Can\'t set attribute `torque` to {repr(torque)} as it is '
732
+ f'immutable.'
733
+ )
734
+ raise AttributeError(msg)
735
+ self._torque = sympify(torque, strict=True)
736
+
737
+ @property
738
+ def axis(self):
739
+ """The axis about which the torque acts."""
740
+ return self._axis
741
+
742
+ @axis.setter
743
+ def axis(self, axis):
744
+ if hasattr(self, '_axis'):
745
+ msg = (
746
+ f'Can\'t set attribute `axis` to {repr(axis)} as it is '
747
+ f'immutable.'
748
+ )
749
+ raise AttributeError(msg)
750
+ if not isinstance(axis, Vector):
751
+ msg = (
752
+ f'Value {repr(axis)} passed to `axis` was of type '
753
+ f'{type(axis)}, must be {Vector}.'
754
+ )
755
+ raise TypeError(msg)
756
+ self._axis = axis
757
+
758
+ @property
759
+ def target_frame(self):
760
+ """The primary reference frames on which the torque will act."""
761
+ return self._target_frame
762
+
763
+ @target_frame.setter
764
+ def target_frame(self, target_frame):
765
+ if hasattr(self, '_target_frame'):
766
+ msg = (
767
+ f'Can\'t set attribute `target_frame` to {repr(target_frame)} '
768
+ f'as it is immutable.'
769
+ )
770
+ raise AttributeError(msg)
771
+ if isinstance(target_frame, RigidBody):
772
+ target_frame = target_frame.frame
773
+ elif not isinstance(target_frame, ReferenceFrame):
774
+ msg = (
775
+ f'Value {repr(target_frame)} passed to `target_frame` was of '
776
+ f'type {type(target_frame)}, must be {ReferenceFrame}.'
777
+ )
778
+ raise TypeError(msg)
779
+ self._target_frame = target_frame
780
+
781
+ @property
782
+ def reaction_frame(self):
783
+ """The primary reference frames on which the torque will act."""
784
+ return self._reaction_frame
785
+
786
+ @reaction_frame.setter
787
+ def reaction_frame(self, reaction_frame):
788
+ if hasattr(self, '_reaction_frame'):
789
+ msg = (
790
+ f'Can\'t set attribute `reaction_frame` to '
791
+ f'{repr(reaction_frame)} as it is immutable.'
792
+ )
793
+ raise AttributeError(msg)
794
+ if isinstance(reaction_frame, RigidBody):
795
+ reaction_frame = reaction_frame.frame
796
+ elif (
797
+ not isinstance(reaction_frame, ReferenceFrame)
798
+ and reaction_frame is not None
799
+ ):
800
+ msg = (
801
+ f'Value {repr(reaction_frame)} passed to `reaction_frame` was '
802
+ f'of type {type(reaction_frame)}, must be {ReferenceFrame}.'
803
+ )
804
+ raise TypeError(msg)
805
+ self._reaction_frame = reaction_frame
806
+
807
+ def to_loads(self):
808
+ """Loads required by the equations of motion method classes.
809
+
810
+ Explanation
811
+ ===========
812
+
813
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
814
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
815
+ when constructing the equations of motion. This method acts as a
816
+ utility to produce the correctly-structred pairs of points and vectors
817
+ required so that these can be easily concatenated with other items in
818
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
819
+ loads are also in the correct form to also be passed to the other
820
+ equations of motion method classes, e.g. ``LagrangesMethod``.
821
+
822
+ Examples
823
+ ========
824
+
825
+ The below example shows how to generate the loads produced by a torque
826
+ actuator that acts on a pair of bodies attached by a pin joint.
827
+
828
+ >>> from sympy import symbols
829
+ >>> from sympy.physics.mechanics import (PinJoint, ReferenceFrame,
830
+ ... RigidBody, TorqueActuator)
831
+ >>> torque = symbols('T')
832
+ >>> N = ReferenceFrame('N')
833
+ >>> A = ReferenceFrame('A')
834
+ >>> parent = RigidBody('parent', frame=N)
835
+ >>> child = RigidBody('child', frame=A)
836
+ >>> pin_joint = PinJoint(
837
+ ... 'pin',
838
+ ... parent,
839
+ ... child,
840
+ ... joint_axis=N.z,
841
+ ... )
842
+ >>> actuator = TorqueActuator.at_pin_joint(torque, pin_joint)
843
+
844
+ The forces produces by the damper can be generated by calling the
845
+ ``to_loads`` method.
846
+
847
+ >>> actuator.to_loads()
848
+ [(A, T*N.z), (N, - T*N.z)]
849
+
850
+ Alternatively, if a torque actuator is created without a reaction frame
851
+ then the loads returned by the ``to_loads`` method will contain just
852
+ the single load acting on the target frame.
853
+
854
+ >>> actuator = TorqueActuator(torque, N.z, N)
855
+ >>> actuator.to_loads()
856
+ [(N, T*N.z)]
857
+
858
+ """
859
+ loads = [
860
+ Torque(self.target_frame, self.torque*self.axis),
861
+ ]
862
+ if self.reaction_frame is not None:
863
+ loads.append(Torque(self.reaction_frame, -self.torque*self.axis))
864
+ return loads
865
+
866
+ def __repr__(self):
867
+ """Representation of a ``TorqueActuator``."""
868
+ string = (
869
+ f'{self.__class__.__name__}({self.torque}, axis={self.axis}, '
870
+ f'target_frame={self.target_frame}'
871
+ )
872
+ if self.reaction_frame is not None:
873
+ string += f', reaction_frame={self.reaction_frame})'
874
+ else:
875
+ string += ')'
876
+ return string
877
+
878
+
879
+ class DuffingSpring(ForceActuator):
880
+ """A nonlinear spring based on the Duffing equation.
881
+
882
+ Explanation
883
+ ===========
884
+
885
+ Here, ``DuffingSpring`` represents the force exerted by a nonlinear spring based on the Duffing equation:
886
+ F = -beta*x-alpha*x**3, where x is the displacement from the equilibrium position, beta is the linear spring constant,
887
+ and alpha is the coefficient for the nonlinear cubic term.
888
+
889
+ Parameters
890
+ ==========
891
+
892
+ linear_stiffness : Expr
893
+ The linear stiffness coefficient (beta).
894
+ nonlinear_stiffness : Expr
895
+ The nonlinear stiffness coefficient (alpha).
896
+ pathway : PathwayBase
897
+ The pathway that the actuator follows.
898
+ equilibrium_length : Expr, optional
899
+ The length at which the spring is in equilibrium (x).
900
+ """
901
+
902
+ def __init__(self, linear_stiffness, nonlinear_stiffness, pathway, equilibrium_length=S.Zero):
903
+ self.linear_stiffness = sympify(linear_stiffness, strict=True)
904
+ self.nonlinear_stiffness = sympify(nonlinear_stiffness, strict=True)
905
+ self.equilibrium_length = sympify(equilibrium_length, strict=True)
906
+
907
+ if not isinstance(pathway, PathwayBase):
908
+ raise TypeError("pathway must be an instance of PathwayBase.")
909
+ self._pathway = pathway
910
+
911
+ @property
912
+ def linear_stiffness(self):
913
+ return self._linear_stiffness
914
+
915
+ @linear_stiffness.setter
916
+ def linear_stiffness(self, linear_stiffness):
917
+ if hasattr(self, '_linear_stiffness'):
918
+ msg = (
919
+ f'Can\'t set attribute `linear_stiffness` to '
920
+ f'{repr(linear_stiffness)} as it is immutable.'
921
+ )
922
+ raise AttributeError(msg)
923
+ self._linear_stiffness = sympify(linear_stiffness, strict=True)
924
+
925
+ @property
926
+ def nonlinear_stiffness(self):
927
+ return self._nonlinear_stiffness
928
+
929
+ @nonlinear_stiffness.setter
930
+ def nonlinear_stiffness(self, nonlinear_stiffness):
931
+ if hasattr(self, '_nonlinear_stiffness'):
932
+ msg = (
933
+ f'Can\'t set attribute `nonlinear_stiffness` to '
934
+ f'{repr(nonlinear_stiffness)} as it is immutable.'
935
+ )
936
+ raise AttributeError(msg)
937
+ self._nonlinear_stiffness = sympify(nonlinear_stiffness, strict=True)
938
+
939
+ @property
940
+ def pathway(self):
941
+ return self._pathway
942
+
943
+ @pathway.setter
944
+ def pathway(self, pathway):
945
+ if hasattr(self, '_pathway'):
946
+ msg = (
947
+ f'Can\'t set attribute `pathway` to {repr(pathway)} as it is '
948
+ f'immutable.'
949
+ )
950
+ raise AttributeError(msg)
951
+ if not isinstance(pathway, PathwayBase):
952
+ msg = (
953
+ f'Value {repr(pathway)} passed to `pathway` was of type '
954
+ f'{type(pathway)}, must be {PathwayBase}.'
955
+ )
956
+ raise TypeError(msg)
957
+ self._pathway = pathway
958
+
959
+ @property
960
+ def equilibrium_length(self):
961
+ return self._equilibrium_length
962
+
963
+ @equilibrium_length.setter
964
+ def equilibrium_length(self, equilibrium_length):
965
+ if hasattr(self, '_equilibrium_length'):
966
+ msg = (
967
+ f'Can\'t set attribute `equilibrium_length` to '
968
+ f'{repr(equilibrium_length)} as it is immutable.'
969
+ )
970
+ raise AttributeError(msg)
971
+ self._equilibrium_length = sympify(equilibrium_length, strict=True)
972
+
973
+ @property
974
+ def force(self):
975
+ """The force produced by the Duffing spring."""
976
+ displacement = self.pathway.length - self.equilibrium_length
977
+ return -self.linear_stiffness * displacement - self.nonlinear_stiffness * displacement**3
978
+
979
+ @force.setter
980
+ def force(self, force):
981
+ if hasattr(self, '_force'):
982
+ msg = (
983
+ f'Can\'t set attribute `force` to {repr(force)} as it is '
984
+ f'immutable.'
985
+ )
986
+ raise AttributeError(msg)
987
+ self._force = sympify(force, strict=True)
988
+
989
+ def __repr__(self):
990
+ return (f"{self.__class__.__name__}("
991
+ f"{self.linear_stiffness}, {self.nonlinear_stiffness}, {self.pathway}, "
992
+ f"equilibrium_length={self.equilibrium_length})")
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/inertia.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import sympify
2
+ from sympy.physics.vector import Point, Dyadic, ReferenceFrame, outer
3
+ from collections import namedtuple
4
+
5
+ __all__ = ['inertia', 'inertia_of_point_mass', 'Inertia']
6
+
7
+
8
+ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
9
+ """Simple way to create inertia Dyadic object.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ Creates an inertia Dyadic based on the given tensor values and a body-fixed
15
+ reference frame.
16
+
17
+ Parameters
18
+ ==========
19
+
20
+ frame : ReferenceFrame
21
+ The frame the inertia is defined in.
22
+ ixx : Sympifyable
23
+ The xx element in the inertia dyadic.
24
+ iyy : Sympifyable
25
+ The yy element in the inertia dyadic.
26
+ izz : Sympifyable
27
+ The zz element in the inertia dyadic.
28
+ ixy : Sympifyable
29
+ The xy element in the inertia dyadic.
30
+ iyz : Sympifyable
31
+ The yz element in the inertia dyadic.
32
+ izx : Sympifyable
33
+ The zx element in the inertia dyadic.
34
+
35
+ Examples
36
+ ========
37
+
38
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia
39
+ >>> N = ReferenceFrame('N')
40
+ >>> inertia(N, 1, 2, 3)
41
+ (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
42
+
43
+ """
44
+
45
+ if not isinstance(frame, ReferenceFrame):
46
+ raise TypeError('Need to define the inertia in a frame')
47
+ ixx, iyy, izz = sympify(ixx), sympify(iyy), sympify(izz)
48
+ ixy, iyz, izx = sympify(ixy), sympify(iyz), sympify(izx)
49
+ return (ixx*outer(frame.x, frame.x) + ixy*outer(frame.x, frame.y) +
50
+ izx*outer(frame.x, frame.z) + ixy*outer(frame.y, frame.x) +
51
+ iyy*outer(frame.y, frame.y) + iyz*outer(frame.y, frame.z) +
52
+ izx*outer(frame.z, frame.x) + iyz*outer(frame.z, frame.y) +
53
+ izz*outer(frame.z, frame.z))
54
+
55
+
56
+ def inertia_of_point_mass(mass, pos_vec, frame):
57
+ """Inertia dyadic of a point mass relative to point O.
58
+
59
+ Parameters
60
+ ==========
61
+
62
+ mass : Sympifyable
63
+ Mass of the point mass
64
+ pos_vec : Vector
65
+ Position from point O to point mass
66
+ frame : ReferenceFrame
67
+ Reference frame to express the dyadic in
68
+
69
+ Examples
70
+ ========
71
+
72
+ >>> from sympy import symbols
73
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
74
+ >>> N = ReferenceFrame('N')
75
+ >>> r, m = symbols('r m')
76
+ >>> px = r * N.x
77
+ >>> inertia_of_point_mass(m, px, N)
78
+ m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
79
+
80
+ """
81
+
82
+ return mass*(
83
+ (outer(frame.x, frame.x) +
84
+ outer(frame.y, frame.y) +
85
+ outer(frame.z, frame.z)) *
86
+ (pos_vec.dot(pos_vec)) - outer(pos_vec, pos_vec))
87
+
88
+
89
+ class Inertia(namedtuple('Inertia', ['dyadic', 'point'])):
90
+ """Inertia object consisting of a Dyadic and a Point of reference.
91
+
92
+ Explanation
93
+ ===========
94
+
95
+ This is a simple class to store the Point and Dyadic, belonging to an
96
+ inertia.
97
+
98
+ Attributes
99
+ ==========
100
+
101
+ dyadic : Dyadic
102
+ The dyadic of the inertia.
103
+ point : Point
104
+ The reference point of the inertia.
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Inertia
110
+ >>> N = ReferenceFrame('N')
111
+ >>> Po = Point('Po')
112
+ >>> Inertia(N.x.outer(N.x) + N.y.outer(N.y) + N.z.outer(N.z), Po)
113
+ ((N.x|N.x) + (N.y|N.y) + (N.z|N.z), Po)
114
+
115
+ In the example above the Dyadic was created manually, one can however also
116
+ use the ``inertia`` function for this or the class method ``from_tensor`` as
117
+ shown below.
118
+
119
+ >>> Inertia.from_inertia_scalars(Po, N, 1, 1, 1)
120
+ ((N.x|N.x) + (N.y|N.y) + (N.z|N.z), Po)
121
+
122
+ """
123
+ def __new__(cls, dyadic, point):
124
+ # Switch order if given in the wrong order
125
+ if isinstance(dyadic, Point) and isinstance(point, Dyadic):
126
+ point, dyadic = dyadic, point
127
+ if not isinstance(point, Point):
128
+ raise TypeError('Reference point should be of type Point')
129
+ if not isinstance(dyadic, Dyadic):
130
+ raise TypeError('Inertia value should be expressed as a Dyadic')
131
+ return super().__new__(cls, dyadic, point)
132
+
133
+ @classmethod
134
+ def from_inertia_scalars(cls, point, frame, ixx, iyy, izz, ixy=0, iyz=0,
135
+ izx=0):
136
+ """Simple way to create an Inertia object based on the tensor values.
137
+
138
+ Explanation
139
+ ===========
140
+
141
+ This class method uses the :func`~.inertia` to create the Dyadic based
142
+ on the tensor values.
143
+
144
+ Parameters
145
+ ==========
146
+
147
+ point : Point
148
+ The reference point of the inertia.
149
+ frame : ReferenceFrame
150
+ The frame the inertia is defined in.
151
+ ixx : Sympifyable
152
+ The xx element in the inertia dyadic.
153
+ iyy : Sympifyable
154
+ The yy element in the inertia dyadic.
155
+ izz : Sympifyable
156
+ The zz element in the inertia dyadic.
157
+ ixy : Sympifyable
158
+ The xy element in the inertia dyadic.
159
+ iyz : Sympifyable
160
+ The yz element in the inertia dyadic.
161
+ izx : Sympifyable
162
+ The zx element in the inertia dyadic.
163
+
164
+ Examples
165
+ ========
166
+
167
+ >>> from sympy import symbols
168
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Inertia
169
+ >>> ixx, iyy, izz, ixy, iyz, izx = symbols('ixx iyy izz ixy iyz izx')
170
+ >>> N = ReferenceFrame('N')
171
+ >>> P = Point('P')
172
+ >>> I = Inertia.from_inertia_scalars(P, N, ixx, iyy, izz, ixy, iyz, izx)
173
+
174
+ The tensor values can easily be seen when converting the dyadic to a
175
+ matrix.
176
+
177
+ >>> I.dyadic.to_matrix(N)
178
+ Matrix([
179
+ [ixx, ixy, izx],
180
+ [ixy, iyy, iyz],
181
+ [izx, iyz, izz]])
182
+
183
+ """
184
+ return cls(inertia(frame, ixx, iyy, izz, ixy, iyz, izx), point)
185
+
186
+ def __add__(self, other):
187
+ raise TypeError(f"unsupported operand type(s) for +: "
188
+ f"'{self.__class__.__name__}' and "
189
+ f"'{other.__class__.__name__}'")
190
+
191
+ def __mul__(self, other):
192
+ raise TypeError(f"unsupported operand type(s) for *: "
193
+ f"'{self.__class__.__name__}' and "
194
+ f"'{other.__class__.__name__}'")
195
+
196
+ __radd__ = __add__
197
+ __rmul__ = __mul__
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py ADDED
@@ -0,0 +1,2188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy import pi, Derivative, Matrix
6
+ from sympy.core.function import AppliedUndef
7
+ from sympy.physics.mechanics.body_base import BodyBase
8
+ from sympy.physics.mechanics.functions import _validate_coordinates
9
+ from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point,
10
+ ReferenceFrame)
11
+ from sympy.utilities.iterables import iterable
12
+ from sympy.utilities.exceptions import sympy_deprecation_warning
13
+
14
+ __all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint',
15
+ 'PlanarJoint', 'SphericalJoint', 'WeldJoint']
16
+
17
+
18
+ class Joint(ABC):
19
+ """Abstract base class for all specific joints.
20
+
21
+ Explanation
22
+ ===========
23
+
24
+ A joint subtracts degrees of freedom from a body. This is the base class
25
+ for all specific joints and holds all common methods acting as an interface
26
+ for all joints. Custom joint can be created by inheriting Joint class and
27
+ defining all abstract functions.
28
+
29
+ The abstract methods are:
30
+
31
+ - ``_generate_coordinates``
32
+ - ``_generate_speeds``
33
+ - ``_orient_frames``
34
+ - ``_set_angular_velocity``
35
+ - ``_set_linear_velocity``
36
+
37
+ Parameters
38
+ ==========
39
+
40
+ name : string
41
+ A unique name for the joint.
42
+ parent : Particle or RigidBody or Body
43
+ The parent body of joint.
44
+ child : Particle or RigidBody or Body
45
+ The child body of joint.
46
+ coordinates : iterable of dynamicsymbols, optional
47
+ Generalized coordinates of the joint.
48
+ speeds : iterable of dynamicsymbols, optional
49
+ Generalized speeds of joint.
50
+ parent_point : Point or Vector, optional
51
+ Attachment point where the joint is fixed to the parent body. If a
52
+ vector is provided, then the attachment point is computed by adding the
53
+ vector to the body's mass center. The default value is the parent's mass
54
+ center.
55
+ child_point : Point or Vector, optional
56
+ Attachment point where the joint is fixed to the child body. If a
57
+ vector is provided, then the attachment point is computed by adding the
58
+ vector to the body's mass center. The default value is the child's mass
59
+ center.
60
+ parent_axis : Vector, optional
61
+ .. deprecated:: 1.12
62
+ Axis fixed in the parent body which aligns with an axis fixed in the
63
+ child body. The default is the x axis of parent's reference frame.
64
+ For more information on this deprecation, see
65
+ :ref:`deprecated-mechanics-joint-axis`.
66
+ child_axis : Vector, optional
67
+ .. deprecated:: 1.12
68
+ Axis fixed in the child body which aligns with an axis fixed in the
69
+ parent body. The default is the x axis of child's reference frame.
70
+ For more information on this deprecation, see
71
+ :ref:`deprecated-mechanics-joint-axis`.
72
+ parent_interframe : ReferenceFrame, optional
73
+ Intermediate frame of the parent body with respect to which the joint
74
+ transformation is formulated. If a Vector is provided then an interframe
75
+ is created which aligns its X axis with the given vector. The default
76
+ value is the parent's own frame.
77
+ child_interframe : ReferenceFrame, optional
78
+ Intermediate frame of the child body with respect to which the joint
79
+ transformation is formulated. If a Vector is provided then an interframe
80
+ is created which aligns its X axis with the given vector. The default
81
+ value is the child's own frame.
82
+ parent_joint_pos : Point or Vector, optional
83
+ .. deprecated:: 1.12
84
+ This argument is replaced by parent_point and will be removed in a
85
+ future version.
86
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
87
+ child_joint_pos : Point or Vector, optional
88
+ .. deprecated:: 1.12
89
+ This argument is replaced by child_point and will be removed in a
90
+ future version.
91
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
92
+
93
+ Attributes
94
+ ==========
95
+
96
+ name : string
97
+ The joint's name.
98
+ parent : Particle or RigidBody or Body
99
+ The joint's parent body.
100
+ child : Particle or RigidBody or Body
101
+ The joint's child body.
102
+ coordinates : Matrix
103
+ Matrix of the joint's generalized coordinates.
104
+ speeds : Matrix
105
+ Matrix of the joint's generalized speeds.
106
+ parent_point : Point
107
+ Attachment point where the joint is fixed to the parent body.
108
+ child_point : Point
109
+ Attachment point where the joint is fixed to the child body.
110
+ parent_axis : Vector
111
+ The axis fixed in the parent frame that represents the joint.
112
+ child_axis : Vector
113
+ The axis fixed in the child frame that represents the joint.
114
+ parent_interframe : ReferenceFrame
115
+ Intermediate frame of the parent body with respect to which the joint
116
+ transformation is formulated.
117
+ child_interframe : ReferenceFrame
118
+ Intermediate frame of the child body with respect to which the joint
119
+ transformation is formulated.
120
+ kdes : Matrix
121
+ Kinematical differential equations of the joint.
122
+
123
+ Notes
124
+ =====
125
+
126
+ When providing a vector as the intermediate frame, a new intermediate frame
127
+ is created which aligns its X axis with the provided vector. This is done
128
+ with a single fixed rotation about a rotation axis. This rotation axis is
129
+ determined by taking the cross product of the ``body.x`` axis with the
130
+ provided vector. In the case where the provided vector is in the ``-body.x``
131
+ direction, the rotation is done about the ``body.y`` axis.
132
+
133
+ """
134
+
135
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
136
+ parent_point=None, child_point=None, parent_interframe=None,
137
+ child_interframe=None, parent_axis=None, child_axis=None,
138
+ parent_joint_pos=None, child_joint_pos=None):
139
+
140
+ if not isinstance(name, str):
141
+ raise TypeError('Supply a valid name.')
142
+ self._name = name
143
+
144
+ if not isinstance(parent, BodyBase):
145
+ raise TypeError('Parent must be a body.')
146
+ self._parent = parent
147
+
148
+ if not isinstance(child, BodyBase):
149
+ raise TypeError('Child must be a body.')
150
+ self._child = child
151
+
152
+ if parent_axis is not None or child_axis is not None:
153
+ sympy_deprecation_warning(
154
+ """
155
+ The parent_axis and child_axis arguments for the Joint classes
156
+ are deprecated. Instead use parent_interframe, child_interframe.
157
+ """,
158
+ deprecated_since_version="1.12",
159
+ active_deprecations_target="deprecated-mechanics-joint-axis",
160
+ stacklevel=4
161
+ )
162
+ if parent_interframe is None:
163
+ parent_interframe = parent_axis
164
+ if child_interframe is None:
165
+ child_interframe = child_axis
166
+
167
+ # Set parent and child frame attributes
168
+ if hasattr(self._parent, 'frame'):
169
+ self._parent_frame = self._parent.frame
170
+ else:
171
+ if isinstance(parent_interframe, ReferenceFrame):
172
+ self._parent_frame = parent_interframe
173
+ else:
174
+ self._parent_frame = ReferenceFrame(
175
+ f'{self.name}_{self._parent.name}_frame')
176
+ if hasattr(self._child, 'frame'):
177
+ self._child_frame = self._child.frame
178
+ else:
179
+ if isinstance(child_interframe, ReferenceFrame):
180
+ self._child_frame = child_interframe
181
+ else:
182
+ self._child_frame = ReferenceFrame(
183
+ f'{self.name}_{self._child.name}_frame')
184
+
185
+ self._parent_interframe = self._locate_joint_frame(
186
+ self._parent, parent_interframe, self._parent_frame)
187
+ self._child_interframe = self._locate_joint_frame(
188
+ self._child, child_interframe, self._child_frame)
189
+ self._parent_axis = self._axis(parent_axis, self._parent_frame)
190
+ self._child_axis = self._axis(child_axis, self._child_frame)
191
+
192
+ if parent_joint_pos is not None or child_joint_pos is not None:
193
+ sympy_deprecation_warning(
194
+ """
195
+ The parent_joint_pos and child_joint_pos arguments for the Joint
196
+ classes are deprecated. Instead use parent_point and child_point.
197
+ """,
198
+ deprecated_since_version="1.12",
199
+ active_deprecations_target="deprecated-mechanics-joint-pos",
200
+ stacklevel=4
201
+ )
202
+ if parent_point is None:
203
+ parent_point = parent_joint_pos
204
+ if child_point is None:
205
+ child_point = child_joint_pos
206
+ self._parent_point = self._locate_joint_pos(
207
+ self._parent, parent_point, self._parent_frame)
208
+ self._child_point = self._locate_joint_pos(
209
+ self._child, child_point, self._child_frame)
210
+
211
+ self._coordinates = self._generate_coordinates(coordinates)
212
+ self._speeds = self._generate_speeds(speeds)
213
+ _validate_coordinates(self.coordinates, self.speeds)
214
+ self._kdes = self._generate_kdes()
215
+
216
+ self._orient_frames()
217
+ self._set_angular_velocity()
218
+ self._set_linear_velocity()
219
+
220
+ def __str__(self):
221
+ return self.name
222
+
223
+ def __repr__(self):
224
+ return self.__str__()
225
+
226
+ @property
227
+ def name(self):
228
+ """Name of the joint."""
229
+ return self._name
230
+
231
+ @property
232
+ def parent(self):
233
+ """Parent body of Joint."""
234
+ return self._parent
235
+
236
+ @property
237
+ def child(self):
238
+ """Child body of Joint."""
239
+ return self._child
240
+
241
+ @property
242
+ def coordinates(self):
243
+ """Matrix of the joint's generalized coordinates."""
244
+ return self._coordinates
245
+
246
+ @property
247
+ def speeds(self):
248
+ """Matrix of the joint's generalized speeds."""
249
+ return self._speeds
250
+
251
+ @property
252
+ def kdes(self):
253
+ """Kinematical differential equations of the joint."""
254
+ return self._kdes
255
+
256
+ @property
257
+ def parent_axis(self):
258
+ """The axis of parent frame."""
259
+ # Will be removed with `deprecated-mechanics-joint-axis`
260
+ return self._parent_axis
261
+
262
+ @property
263
+ def child_axis(self):
264
+ """The axis of child frame."""
265
+ # Will be removed with `deprecated-mechanics-joint-axis`
266
+ return self._child_axis
267
+
268
+ @property
269
+ def parent_point(self):
270
+ """Attachment point where the joint is fixed to the parent body."""
271
+ return self._parent_point
272
+
273
+ @property
274
+ def child_point(self):
275
+ """Attachment point where the joint is fixed to the child body."""
276
+ return self._child_point
277
+
278
+ @property
279
+ def parent_interframe(self):
280
+ return self._parent_interframe
281
+
282
+ @property
283
+ def child_interframe(self):
284
+ return self._child_interframe
285
+
286
+ @abstractmethod
287
+ def _generate_coordinates(self, coordinates):
288
+ """Generate Matrix of the joint's generalized coordinates."""
289
+ pass
290
+
291
+ @abstractmethod
292
+ def _generate_speeds(self, speeds):
293
+ """Generate Matrix of the joint's generalized speeds."""
294
+ pass
295
+
296
+ @abstractmethod
297
+ def _orient_frames(self):
298
+ """Orient frames as per the joint."""
299
+ pass
300
+
301
+ @abstractmethod
302
+ def _set_angular_velocity(self):
303
+ """Set angular velocity of the joint related frames."""
304
+ pass
305
+
306
+ @abstractmethod
307
+ def _set_linear_velocity(self):
308
+ """Set velocity of related points to the joint."""
309
+ pass
310
+
311
+ @staticmethod
312
+ def _to_vector(matrix, frame):
313
+ """Converts a matrix to a vector in the given frame."""
314
+ return Vector([(matrix, frame)])
315
+
316
+ @staticmethod
317
+ def _axis(ax, *frames):
318
+ """Check whether an axis is fixed in one of the frames."""
319
+ if ax is None:
320
+ ax = frames[0].x
321
+ return ax
322
+ if not isinstance(ax, Vector):
323
+ raise TypeError("Axis must be a Vector.")
324
+ ref_frame = None # Find a body in which the axis can be expressed
325
+ for frame in frames:
326
+ try:
327
+ ax.to_matrix(frame)
328
+ except ValueError:
329
+ pass
330
+ else:
331
+ ref_frame = frame
332
+ break
333
+ if ref_frame is None:
334
+ raise ValueError("Axis cannot be expressed in one of the body's "
335
+ "frames.")
336
+ if not ax.dt(ref_frame) == 0:
337
+ raise ValueError('Axis cannot be time-varying when viewed from the '
338
+ 'associated body.')
339
+ return ax
340
+
341
+ @staticmethod
342
+ def _choose_rotation_axis(frame, axis):
343
+ components = axis.to_matrix(frame)
344
+ x, y, z = components[0], components[1], components[2]
345
+
346
+ if x != 0:
347
+ if y != 0:
348
+ if z != 0:
349
+ return cross(axis, frame.x)
350
+ if z != 0:
351
+ return frame.y
352
+ return frame.z
353
+ else:
354
+ if y != 0:
355
+ return frame.x
356
+ return frame.y
357
+
358
+ @staticmethod
359
+ def _create_aligned_interframe(frame, align_axis, frame_axis=None,
360
+ frame_name=None):
361
+ """
362
+ Returns an intermediate frame, where the ``frame_axis`` defined in
363
+ ``frame`` is aligned with ``axis``. By default this means that the X
364
+ axis will be aligned with ``axis``.
365
+
366
+ Parameters
367
+ ==========
368
+
369
+ frame : BodyBase or ReferenceFrame
370
+ The body or reference frame with respect to which the intermediate
371
+ frame is oriented.
372
+ align_axis : Vector
373
+ The vector with respect to which the intermediate frame will be
374
+ aligned.
375
+ frame_axis : Vector
376
+ The vector of the frame which should get aligned with ``axis``. The
377
+ default is the X axis of the frame.
378
+ frame_name : string
379
+ Name of the to be created intermediate frame. The default adds
380
+ "_int_frame" to the name of ``frame``.
381
+
382
+ Example
383
+ =======
384
+
385
+ An intermediate frame, where the X axis of the parent becomes aligned
386
+ with ``parent.y + parent.z`` can be created as follows:
387
+
388
+ >>> from sympy.physics.mechanics.joint import Joint
389
+ >>> from sympy.physics.mechanics import RigidBody
390
+ >>> parent = RigidBody('parent')
391
+ >>> parent_interframe = Joint._create_aligned_interframe(
392
+ ... parent, parent.y + parent.z)
393
+ >>> parent_interframe
394
+ parent_int_frame
395
+ >>> parent.frame.dcm(parent_interframe)
396
+ Matrix([
397
+ [ 0, -sqrt(2)/2, -sqrt(2)/2],
398
+ [sqrt(2)/2, 1/2, -1/2],
399
+ [sqrt(2)/2, -1/2, 1/2]])
400
+ >>> (parent.y + parent.z).express(parent_interframe)
401
+ sqrt(2)*parent_int_frame.x
402
+
403
+ Notes
404
+ =====
405
+
406
+ The direction cosine matrix between the given frame and intermediate
407
+ frame is formed using a simple rotation about an axis that is normal to
408
+ both ``align_axis`` and ``frame_axis``. In general, the normal axis is
409
+ formed by crossing the ``frame_axis`` with the ``align_axis``. The
410
+ exception is if the axes are parallel with opposite directions, in which
411
+ case the rotation vector is chosen using the rules in the following
412
+ table with the vectors expressed in the given frame:
413
+
414
+ .. list-table::
415
+ :header-rows: 1
416
+
417
+ * - ``align_axis``
418
+ - ``frame_axis``
419
+ - ``rotation_axis``
420
+ * - ``-x``
421
+ - ``x``
422
+ - ``z``
423
+ * - ``-y``
424
+ - ``y``
425
+ - ``x``
426
+ * - ``-z``
427
+ - ``z``
428
+ - ``y``
429
+ * - ``-x-y``
430
+ - ``x+y``
431
+ - ``z``
432
+ * - ``-y-z``
433
+ - ``y+z``
434
+ - ``x``
435
+ * - ``-x-z``
436
+ - ``x+z``
437
+ - ``y``
438
+ * - ``-x-y-z``
439
+ - ``x+y+z``
440
+ - ``(x+y+z) × x``
441
+
442
+ """
443
+ if isinstance(frame, BodyBase):
444
+ frame = frame.frame
445
+ if frame_axis is None:
446
+ frame_axis = frame.x
447
+ if frame_name is None:
448
+ if frame.name[-6:] == '_frame':
449
+ frame_name = f'{frame.name[:-6]}_int_frame'
450
+ else:
451
+ frame_name = f'{frame.name}_int_frame'
452
+ angle = frame_axis.angle_between(align_axis)
453
+ rotation_axis = cross(frame_axis, align_axis)
454
+ if rotation_axis == Vector(0) and angle == 0:
455
+ return frame
456
+ if angle == pi:
457
+ rotation_axis = Joint._choose_rotation_axis(frame, align_axis)
458
+
459
+ int_frame = ReferenceFrame(frame_name)
460
+ int_frame.orient_axis(frame, rotation_axis, angle)
461
+ int_frame.set_ang_vel(frame, 0 * rotation_axis)
462
+ return int_frame
463
+
464
+ def _generate_kdes(self):
465
+ """Generate kinematical differential equations."""
466
+ kdes = []
467
+ t = dynamicsymbols._t
468
+ for i in range(len(self.coordinates)):
469
+ kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
470
+ return Matrix(kdes)
471
+
472
+ def _locate_joint_pos(self, body, joint_pos, body_frame=None):
473
+ """Returns the attachment point of a body."""
474
+ if body_frame is None:
475
+ body_frame = body.frame
476
+ if joint_pos is None:
477
+ return body.masscenter
478
+ if not isinstance(joint_pos, (Point, Vector)):
479
+ raise TypeError('Attachment point must be a Point or Vector.')
480
+ if isinstance(joint_pos, Vector):
481
+ point_name = f'{self.name}_{body.name}_joint'
482
+ joint_pos = body.masscenter.locatenew(point_name, joint_pos)
483
+ if not joint_pos.pos_from(body.masscenter).dt(body_frame) == 0:
484
+ raise ValueError('Attachment point must be fixed to the associated '
485
+ 'body.')
486
+ return joint_pos
487
+
488
+ def _locate_joint_frame(self, body, interframe, body_frame=None):
489
+ """Returns the attachment frame of a body."""
490
+ if body_frame is None:
491
+ body_frame = body.frame
492
+ if interframe is None:
493
+ return body_frame
494
+ if isinstance(interframe, Vector):
495
+ interframe = Joint._create_aligned_interframe(
496
+ body_frame, interframe,
497
+ frame_name=f'{self.name}_{body.name}_int_frame')
498
+ elif not isinstance(interframe, ReferenceFrame):
499
+ raise TypeError('Interframe must be a ReferenceFrame.')
500
+ if not interframe.ang_vel_in(body_frame) == 0:
501
+ raise ValueError(f'Interframe {interframe} is not fixed to body '
502
+ f'{body}.')
503
+ body.masscenter.set_vel(interframe, 0) # Fixate interframe to body
504
+ return interframe
505
+
506
+ def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0,
507
+ number_single=False):
508
+ """Helper method for _generate_coordinates and _generate_speeds.
509
+
510
+ Parameters
511
+ ==========
512
+
513
+ coordinates : iterable
514
+ Iterable of coordinates or speeds that have been provided.
515
+ n_coords : Integer
516
+ Number of coordinates that should be returned.
517
+ label : String, optional
518
+ Coordinate type either 'q' (coordinates) or 'u' (speeds). The
519
+ Default is 'q'.
520
+ offset : Integer
521
+ Count offset when creating new dynamicsymbols. The default is 0.
522
+ number_single : Boolean
523
+ Boolean whether if n_coords == 1, number should still be used. The
524
+ default is False.
525
+
526
+ """
527
+
528
+ def create_symbol(number):
529
+ if n_coords == 1 and not number_single:
530
+ return dynamicsymbols(f'{label}_{self.name}')
531
+ return dynamicsymbols(f'{label}{number}_{self.name}')
532
+
533
+ name = 'generalized coordinate' if label == 'q' else 'generalized speed'
534
+ generated_coordinates = []
535
+ if coordinates is None:
536
+ coordinates = []
537
+ elif not iterable(coordinates):
538
+ coordinates = [coordinates]
539
+ if not (len(coordinates) == 0 or len(coordinates) == n_coords):
540
+ raise ValueError(f'Expected {n_coords} {name}s, instead got '
541
+ f'{len(coordinates)} {name}s.')
542
+ # Supports more iterables, also Matrix
543
+ for i, coord in enumerate(coordinates):
544
+ if coord is None:
545
+ generated_coordinates.append(create_symbol(i + offset))
546
+ elif isinstance(coord, (AppliedUndef, Derivative)):
547
+ generated_coordinates.append(coord)
548
+ else:
549
+ raise TypeError(f'The {name} {coord} should have been a '
550
+ f'dynamicsymbol.')
551
+ for i in range(len(coordinates) + offset, n_coords + offset):
552
+ generated_coordinates.append(create_symbol(i))
553
+ return Matrix(generated_coordinates)
554
+
555
+
556
+ class PinJoint(Joint):
557
+ """Pin (Revolute) Joint.
558
+
559
+ .. raw:: html
560
+ :file: ../../../doc/src/modules/physics/mechanics/api/PinJoint.svg
561
+
562
+ Explanation
563
+ ===========
564
+
565
+ A pin joint is defined such that the joint rotation axis is fixed in both
566
+ the child and parent and the location of the joint is relative to the mass
567
+ center of each body. The child rotates an angle, θ, from the parent about
568
+ the rotation axis and has a simple angular speed, ω, relative to the
569
+ parent. The direction cosine matrix between the child interframe and
570
+ parent interframe is formed using a simple rotation about the joint axis.
571
+ The page on the joints framework gives a more detailed explanation of the
572
+ intermediate frames.
573
+
574
+ Parameters
575
+ ==========
576
+
577
+ name : string
578
+ A unique name for the joint.
579
+ parent : Particle or RigidBody or Body
580
+ The parent body of joint.
581
+ child : Particle or RigidBody or Body
582
+ The child body of joint.
583
+ coordinates : dynamicsymbol, optional
584
+ Generalized coordinates of the joint.
585
+ speeds : dynamicsymbol, optional
586
+ Generalized speeds of joint.
587
+ parent_point : Point or Vector, optional
588
+ Attachment point where the joint is fixed to the parent body. If a
589
+ vector is provided, then the attachment point is computed by adding the
590
+ vector to the body's mass center. The default value is the parent's mass
591
+ center.
592
+ child_point : Point or Vector, optional
593
+ Attachment point where the joint is fixed to the child body. If a
594
+ vector is provided, then the attachment point is computed by adding the
595
+ vector to the body's mass center. The default value is the child's mass
596
+ center.
597
+ parent_axis : Vector, optional
598
+ .. deprecated:: 1.12
599
+ Axis fixed in the parent body which aligns with an axis fixed in the
600
+ child body. The default is the x axis of parent's reference frame.
601
+ For more information on this deprecation, see
602
+ :ref:`deprecated-mechanics-joint-axis`.
603
+ child_axis : Vector, optional
604
+ .. deprecated:: 1.12
605
+ Axis fixed in the child body which aligns with an axis fixed in the
606
+ parent body. The default is the x axis of child's reference frame.
607
+ For more information on this deprecation, see
608
+ :ref:`deprecated-mechanics-joint-axis`.
609
+ parent_interframe : ReferenceFrame, optional
610
+ Intermediate frame of the parent body with respect to which the joint
611
+ transformation is formulated. If a Vector is provided then an interframe
612
+ is created which aligns its X axis with the given vector. The default
613
+ value is the parent's own frame.
614
+ child_interframe : ReferenceFrame, optional
615
+ Intermediate frame of the child body with respect to which the joint
616
+ transformation is formulated. If a Vector is provided then an interframe
617
+ is created which aligns its X axis with the given vector. The default
618
+ value is the child's own frame.
619
+ joint_axis : Vector
620
+ The axis about which the rotation occurs. Note that the components
621
+ of this axis are the same in the parent_interframe and child_interframe.
622
+ parent_joint_pos : Point or Vector, optional
623
+ .. deprecated:: 1.12
624
+ This argument is replaced by parent_point and will be removed in a
625
+ future version.
626
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
627
+ child_joint_pos : Point or Vector, optional
628
+ .. deprecated:: 1.12
629
+ This argument is replaced by child_point and will be removed in a
630
+ future version.
631
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
632
+
633
+ Attributes
634
+ ==========
635
+
636
+ name : string
637
+ The joint's name.
638
+ parent : Particle or RigidBody or Body
639
+ The joint's parent body.
640
+ child : Particle or RigidBody or Body
641
+ The joint's child body.
642
+ coordinates : Matrix
643
+ Matrix of the joint's generalized coordinates. The default value is
644
+ ``dynamicsymbols(f'q_{joint.name}')``.
645
+ speeds : Matrix
646
+ Matrix of the joint's generalized speeds. The default value is
647
+ ``dynamicsymbols(f'u_{joint.name}')``.
648
+ parent_point : Point
649
+ Attachment point where the joint is fixed to the parent body.
650
+ child_point : Point
651
+ Attachment point where the joint is fixed to the child body.
652
+ parent_axis : Vector
653
+ The axis fixed in the parent frame that represents the joint.
654
+ child_axis : Vector
655
+ The axis fixed in the child frame that represents the joint.
656
+ parent_interframe : ReferenceFrame
657
+ Intermediate frame of the parent body with respect to which the joint
658
+ transformation is formulated.
659
+ child_interframe : ReferenceFrame
660
+ Intermediate frame of the child body with respect to which the joint
661
+ transformation is formulated.
662
+ joint_axis : Vector
663
+ The axis about which the rotation occurs. Note that the components of
664
+ this axis are the same in the parent_interframe and child_interframe.
665
+ kdes : Matrix
666
+ Kinematical differential equations of the joint.
667
+
668
+ Examples
669
+ =========
670
+
671
+ A single pin joint is created from two bodies and has the following basic
672
+ attributes:
673
+
674
+ >>> from sympy.physics.mechanics import RigidBody, PinJoint
675
+ >>> parent = RigidBody('P')
676
+ >>> parent
677
+ P
678
+ >>> child = RigidBody('C')
679
+ >>> child
680
+ C
681
+ >>> joint = PinJoint('PC', parent, child)
682
+ >>> joint
683
+ PinJoint: PC parent: P child: C
684
+ >>> joint.name
685
+ 'PC'
686
+ >>> joint.parent
687
+ P
688
+ >>> joint.child
689
+ C
690
+ >>> joint.parent_point
691
+ P_masscenter
692
+ >>> joint.child_point
693
+ C_masscenter
694
+ >>> joint.parent_axis
695
+ P_frame.x
696
+ >>> joint.child_axis
697
+ C_frame.x
698
+ >>> joint.coordinates
699
+ Matrix([[q_PC(t)]])
700
+ >>> joint.speeds
701
+ Matrix([[u_PC(t)]])
702
+ >>> child.frame.ang_vel_in(parent.frame)
703
+ u_PC(t)*P_frame.x
704
+ >>> child.frame.dcm(parent.frame)
705
+ Matrix([
706
+ [1, 0, 0],
707
+ [0, cos(q_PC(t)), sin(q_PC(t))],
708
+ [0, -sin(q_PC(t)), cos(q_PC(t))]])
709
+ >>> joint.child_point.pos_from(joint.parent_point)
710
+ 0
711
+
712
+ To further demonstrate the use of the pin joint, the kinematics of simple
713
+ double pendulum that rotates about the Z axis of each connected body can be
714
+ created as follows.
715
+
716
+ >>> from sympy import symbols, trigsimp
717
+ >>> from sympy.physics.mechanics import RigidBody, PinJoint
718
+ >>> l1, l2 = symbols('l1 l2')
719
+
720
+ First create bodies to represent the fixed ceiling and one to represent
721
+ each pendulum bob.
722
+
723
+ >>> ceiling = RigidBody('C')
724
+ >>> upper_bob = RigidBody('U')
725
+ >>> lower_bob = RigidBody('L')
726
+
727
+ The first joint will connect the upper bob to the ceiling by a distance of
728
+ ``l1`` and the joint axis will be about the Z axis for each body.
729
+
730
+ >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
731
+ ... child_point=-l1*upper_bob.frame.x,
732
+ ... joint_axis=ceiling.frame.z)
733
+
734
+ The second joint will connect the lower bob to the upper bob by a distance
735
+ of ``l2`` and the joint axis will also be about the Z axis for each body.
736
+
737
+ >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
738
+ ... child_point=-l2*lower_bob.frame.x,
739
+ ... joint_axis=upper_bob.frame.z)
740
+
741
+ Once the joints are established the kinematics of the connected bodies can
742
+ be accessed. First the direction cosine matrices of pendulum link relative
743
+ to the ceiling are found:
744
+
745
+ >>> upper_bob.frame.dcm(ceiling.frame)
746
+ Matrix([
747
+ [ cos(q_P1(t)), sin(q_P1(t)), 0],
748
+ [-sin(q_P1(t)), cos(q_P1(t)), 0],
749
+ [ 0, 0, 1]])
750
+ >>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
751
+ Matrix([
752
+ [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0],
753
+ [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0],
754
+ [ 0, 0, 1]])
755
+
756
+ The position of the lower bob's masscenter is found with:
757
+
758
+ >>> lower_bob.masscenter.pos_from(ceiling.masscenter)
759
+ l1*U_frame.x + l2*L_frame.x
760
+
761
+ The angular velocities of the two pendulum links can be computed with
762
+ respect to the ceiling.
763
+
764
+ >>> upper_bob.frame.ang_vel_in(ceiling.frame)
765
+ u_P1(t)*C_frame.z
766
+ >>> lower_bob.frame.ang_vel_in(ceiling.frame)
767
+ u_P1(t)*C_frame.z + u_P2(t)*U_frame.z
768
+
769
+ And finally, the linear velocities of the two pendulum bobs can be computed
770
+ with respect to the ceiling.
771
+
772
+ >>> upper_bob.masscenter.vel(ceiling.frame)
773
+ l1*u_P1(t)*U_frame.y
774
+ >>> lower_bob.masscenter.vel(ceiling.frame)
775
+ l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y
776
+
777
+ """
778
+
779
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
780
+ parent_point=None, child_point=None, parent_interframe=None,
781
+ child_interframe=None, parent_axis=None, child_axis=None,
782
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
783
+
784
+ self._joint_axis = joint_axis
785
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
786
+ child_point, parent_interframe, child_interframe,
787
+ parent_axis, child_axis, parent_joint_pos,
788
+ child_joint_pos)
789
+
790
+ def __str__(self):
791
+ return (f'PinJoint: {self.name} parent: {self.parent} '
792
+ f'child: {self.child}')
793
+
794
+ @property
795
+ def joint_axis(self):
796
+ """Axis about which the child rotates with respect to the parent."""
797
+ return self._joint_axis
798
+
799
+ def _generate_coordinates(self, coordinate):
800
+ return self._fill_coordinate_list(coordinate, 1, 'q')
801
+
802
+ def _generate_speeds(self, speed):
803
+ return self._fill_coordinate_list(speed, 1, 'u')
804
+
805
+ def _orient_frames(self):
806
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
807
+ self.child_interframe.orient_axis(
808
+ self.parent_interframe, self.joint_axis, self.coordinates[0])
809
+
810
+ def _set_angular_velocity(self):
811
+ self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[
812
+ 0] * self.joint_axis.normalize())
813
+
814
+ def _set_linear_velocity(self):
815
+ self.child_point.set_pos(self.parent_point, 0)
816
+ self.parent_point.set_vel(self._parent_frame, 0)
817
+ self.child_point.set_vel(self._child_frame, 0)
818
+ self.child.masscenter.v2pt_theory(self.parent_point,
819
+ self._parent_frame, self._child_frame)
820
+
821
+
822
+ class PrismaticJoint(Joint):
823
+ """Prismatic (Sliding) Joint.
824
+
825
+ .. image:: PrismaticJoint.svg
826
+
827
+ Explanation
828
+ ===========
829
+
830
+ It is defined such that the child body translates with respect to the parent
831
+ body along the body-fixed joint axis. The location of the joint is defined
832
+ by two points, one in each body, which coincide when the generalized
833
+ coordinate is zero. The direction cosine matrix between the
834
+ parent_interframe and child_interframe is the identity matrix. Therefore,
835
+ the direction cosine matrix between the parent and child frames is fully
836
+ defined by the definition of the intermediate frames. The page on the joints
837
+ framework gives a more detailed explanation of the intermediate frames.
838
+
839
+ Parameters
840
+ ==========
841
+
842
+ name : string
843
+ A unique name for the joint.
844
+ parent : Particle or RigidBody or Body
845
+ The parent body of joint.
846
+ child : Particle or RigidBody or Body
847
+ The child body of joint.
848
+ coordinates : dynamicsymbol, optional
849
+ Generalized coordinates of the joint. The default value is
850
+ ``dynamicsymbols(f'q_{joint.name}')``.
851
+ speeds : dynamicsymbol, optional
852
+ Generalized speeds of joint. The default value is
853
+ ``dynamicsymbols(f'u_{joint.name}')``.
854
+ parent_point : Point or Vector, optional
855
+ Attachment point where the joint is fixed to the parent body. If a
856
+ vector is provided, then the attachment point is computed by adding the
857
+ vector to the body's mass center. The default value is the parent's mass
858
+ center.
859
+ child_point : Point or Vector, optional
860
+ Attachment point where the joint is fixed to the child body. If a
861
+ vector is provided, then the attachment point is computed by adding the
862
+ vector to the body's mass center. The default value is the child's mass
863
+ center.
864
+ parent_axis : Vector, optional
865
+ .. deprecated:: 1.12
866
+ Axis fixed in the parent body which aligns with an axis fixed in the
867
+ child body. The default is the x axis of parent's reference frame.
868
+ For more information on this deprecation, see
869
+ :ref:`deprecated-mechanics-joint-axis`.
870
+ child_axis : Vector, optional
871
+ .. deprecated:: 1.12
872
+ Axis fixed in the child body which aligns with an axis fixed in the
873
+ parent body. The default is the x axis of child's reference frame.
874
+ For more information on this deprecation, see
875
+ :ref:`deprecated-mechanics-joint-axis`.
876
+ parent_interframe : ReferenceFrame, optional
877
+ Intermediate frame of the parent body with respect to which the joint
878
+ transformation is formulated. If a Vector is provided then an interframe
879
+ is created which aligns its X axis with the given vector. The default
880
+ value is the parent's own frame.
881
+ child_interframe : ReferenceFrame, optional
882
+ Intermediate frame of the child body with respect to which the joint
883
+ transformation is formulated. If a Vector is provided then an interframe
884
+ is created which aligns its X axis with the given vector. The default
885
+ value is the child's own frame.
886
+ joint_axis : Vector
887
+ The axis along which the translation occurs. Note that the components
888
+ of this axis are the same in the parent_interframe and child_interframe.
889
+ parent_joint_pos : Point or Vector, optional
890
+ .. deprecated:: 1.12
891
+ This argument is replaced by parent_point and will be removed in a
892
+ future version.
893
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
894
+ child_joint_pos : Point or Vector, optional
895
+ .. deprecated:: 1.12
896
+ This argument is replaced by child_point and will be removed in a
897
+ future version.
898
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
899
+
900
+ Attributes
901
+ ==========
902
+
903
+ name : string
904
+ The joint's name.
905
+ parent : Particle or RigidBody or Body
906
+ The joint's parent body.
907
+ child : Particle or RigidBody or Body
908
+ The joint's child body.
909
+ coordinates : Matrix
910
+ Matrix of the joint's generalized coordinates.
911
+ speeds : Matrix
912
+ Matrix of the joint's generalized speeds.
913
+ parent_point : Point
914
+ Attachment point where the joint is fixed to the parent body.
915
+ child_point : Point
916
+ Attachment point where the joint is fixed to the child body.
917
+ parent_axis : Vector
918
+ The axis fixed in the parent frame that represents the joint.
919
+ child_axis : Vector
920
+ The axis fixed in the child frame that represents the joint.
921
+ parent_interframe : ReferenceFrame
922
+ Intermediate frame of the parent body with respect to which the joint
923
+ transformation is formulated.
924
+ child_interframe : ReferenceFrame
925
+ Intermediate frame of the child body with respect to which the joint
926
+ transformation is formulated.
927
+ kdes : Matrix
928
+ Kinematical differential equations of the joint.
929
+
930
+ Examples
931
+ =========
932
+
933
+ A single prismatic joint is created from two bodies and has the following
934
+ basic attributes:
935
+
936
+ >>> from sympy.physics.mechanics import RigidBody, PrismaticJoint
937
+ >>> parent = RigidBody('P')
938
+ >>> parent
939
+ P
940
+ >>> child = RigidBody('C')
941
+ >>> child
942
+ C
943
+ >>> joint = PrismaticJoint('PC', parent, child)
944
+ >>> joint
945
+ PrismaticJoint: PC parent: P child: C
946
+ >>> joint.name
947
+ 'PC'
948
+ >>> joint.parent
949
+ P
950
+ >>> joint.child
951
+ C
952
+ >>> joint.parent_point
953
+ P_masscenter
954
+ >>> joint.child_point
955
+ C_masscenter
956
+ >>> joint.parent_axis
957
+ P_frame.x
958
+ >>> joint.child_axis
959
+ C_frame.x
960
+ >>> joint.coordinates
961
+ Matrix([[q_PC(t)]])
962
+ >>> joint.speeds
963
+ Matrix([[u_PC(t)]])
964
+ >>> child.frame.ang_vel_in(parent.frame)
965
+ 0
966
+ >>> child.frame.dcm(parent.frame)
967
+ Matrix([
968
+ [1, 0, 0],
969
+ [0, 1, 0],
970
+ [0, 0, 1]])
971
+ >>> joint.child_point.pos_from(joint.parent_point)
972
+ q_PC(t)*P_frame.x
973
+
974
+ To further demonstrate the use of the prismatic joint, the kinematics of two
975
+ masses sliding, one moving relative to a fixed body and the other relative
976
+ to the moving body. about the X axis of each connected body can be created
977
+ as follows.
978
+
979
+ >>> from sympy.physics.mechanics import PrismaticJoint, RigidBody
980
+
981
+ First create bodies to represent the fixed ceiling and one to represent
982
+ a particle.
983
+
984
+ >>> wall = RigidBody('W')
985
+ >>> Part1 = RigidBody('P1')
986
+ >>> Part2 = RigidBody('P2')
987
+
988
+ The first joint will connect the particle to the ceiling and the
989
+ joint axis will be about the X axis for each body.
990
+
991
+ >>> J1 = PrismaticJoint('J1', wall, Part1)
992
+
993
+ The second joint will connect the second particle to the first particle
994
+ and the joint axis will also be about the X axis for each body.
995
+
996
+ >>> J2 = PrismaticJoint('J2', Part1, Part2)
997
+
998
+ Once the joint is established the kinematics of the connected bodies can
999
+ be accessed. First the direction cosine matrices of Part relative
1000
+ to the ceiling are found:
1001
+
1002
+ >>> Part1.frame.dcm(wall.frame)
1003
+ Matrix([
1004
+ [1, 0, 0],
1005
+ [0, 1, 0],
1006
+ [0, 0, 1]])
1007
+
1008
+ >>> Part2.frame.dcm(wall.frame)
1009
+ Matrix([
1010
+ [1, 0, 0],
1011
+ [0, 1, 0],
1012
+ [0, 0, 1]])
1013
+
1014
+ The position of the particles' masscenter is found with:
1015
+
1016
+ >>> Part1.masscenter.pos_from(wall.masscenter)
1017
+ q_J1(t)*W_frame.x
1018
+
1019
+ >>> Part2.masscenter.pos_from(wall.masscenter)
1020
+ q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x
1021
+
1022
+ The angular velocities of the two particle links can be computed with
1023
+ respect to the ceiling.
1024
+
1025
+ >>> Part1.frame.ang_vel_in(wall.frame)
1026
+ 0
1027
+
1028
+ >>> Part2.frame.ang_vel_in(wall.frame)
1029
+ 0
1030
+
1031
+ And finally, the linear velocities of the two particles can be computed
1032
+ with respect to the ceiling.
1033
+
1034
+ >>> Part1.masscenter.vel(wall.frame)
1035
+ u_J1(t)*W_frame.x
1036
+
1037
+ >>> Part2.masscenter.vel(wall.frame)
1038
+ u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x
1039
+
1040
+ """
1041
+
1042
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1043
+ parent_point=None, child_point=None, parent_interframe=None,
1044
+ child_interframe=None, parent_axis=None, child_axis=None,
1045
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
1046
+
1047
+ self._joint_axis = joint_axis
1048
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
1049
+ child_point, parent_interframe, child_interframe,
1050
+ parent_axis, child_axis, parent_joint_pos,
1051
+ child_joint_pos)
1052
+
1053
+ def __str__(self):
1054
+ return (f'PrismaticJoint: {self.name} parent: {self.parent} '
1055
+ f'child: {self.child}')
1056
+
1057
+ @property
1058
+ def joint_axis(self):
1059
+ """Axis along which the child translates with respect to the parent."""
1060
+ return self._joint_axis
1061
+
1062
+ def _generate_coordinates(self, coordinate):
1063
+ return self._fill_coordinate_list(coordinate, 1, 'q')
1064
+
1065
+ def _generate_speeds(self, speed):
1066
+ return self._fill_coordinate_list(speed, 1, 'u')
1067
+
1068
+ def _orient_frames(self):
1069
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1070
+ self.child_interframe.orient_axis(
1071
+ self.parent_interframe, self.joint_axis, 0)
1072
+
1073
+ def _set_angular_velocity(self):
1074
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
1075
+
1076
+ def _set_linear_velocity(self):
1077
+ axis = self.joint_axis.normalize()
1078
+ self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis)
1079
+ self.parent_point.set_vel(self._parent_frame, 0)
1080
+ self.child_point.set_vel(self._child_frame, 0)
1081
+ self.child_point.set_vel(self._parent_frame, self.speeds[0] * axis)
1082
+ self.child.masscenter.set_vel(self._parent_frame, self.speeds[0] * axis)
1083
+
1084
+
1085
+ class CylindricalJoint(Joint):
1086
+ """Cylindrical Joint.
1087
+
1088
+ .. image:: CylindricalJoint.svg
1089
+ :align: center
1090
+ :width: 600
1091
+
1092
+ Explanation
1093
+ ===========
1094
+
1095
+ A cylindrical joint is defined such that the child body both rotates about
1096
+ and translates along the body-fixed joint axis with respect to the parent
1097
+ body. The joint axis is both the rotation axis and translation axis. The
1098
+ location of the joint is defined by two points, one in each body, which
1099
+ coincide when the generalized coordinate corresponding to the translation is
1100
+ zero. The direction cosine matrix between the child interframe and parent
1101
+ interframe is formed using a simple rotation about the joint axis. The page
1102
+ on the joints framework gives a more detailed explanation of the
1103
+ intermediate frames.
1104
+
1105
+ Parameters
1106
+ ==========
1107
+
1108
+ name : string
1109
+ A unique name for the joint.
1110
+ parent : Particle or RigidBody or Body
1111
+ The parent body of joint.
1112
+ child : Particle or RigidBody or Body
1113
+ The child body of joint.
1114
+ rotation_coordinate : dynamicsymbol, optional
1115
+ Generalized coordinate corresponding to the rotation angle. The default
1116
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1117
+ translation_coordinate : dynamicsymbol, optional
1118
+ Generalized coordinate corresponding to the translation distance. The
1119
+ default value is ``dynamicsymbols(f'q1_{joint.name}')``.
1120
+ rotation_speed : dynamicsymbol, optional
1121
+ Generalized speed corresponding to the angular velocity. The default
1122
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1123
+ translation_speed : dynamicsymbol, optional
1124
+ Generalized speed corresponding to the translation velocity. The default
1125
+ value is ``dynamicsymbols(f'u1_{joint.name}')``.
1126
+ parent_point : Point or Vector, optional
1127
+ Attachment point where the joint is fixed to the parent body. If a
1128
+ vector is provided, then the attachment point is computed by adding the
1129
+ vector to the body's mass center. The default value is the parent's mass
1130
+ center.
1131
+ child_point : Point or Vector, optional
1132
+ Attachment point where the joint is fixed to the child body. If a
1133
+ vector is provided, then the attachment point is computed by adding the
1134
+ vector to the body's mass center. The default value is the child's mass
1135
+ center.
1136
+ parent_interframe : ReferenceFrame, optional
1137
+ Intermediate frame of the parent body with respect to which the joint
1138
+ transformation is formulated. If a Vector is provided then an interframe
1139
+ is created which aligns its X axis with the given vector. The default
1140
+ value is the parent's own frame.
1141
+ child_interframe : ReferenceFrame, optional
1142
+ Intermediate frame of the child body with respect to which the joint
1143
+ transformation is formulated. If a Vector is provided then an interframe
1144
+ is created which aligns its X axis with the given vector. The default
1145
+ value is the child's own frame.
1146
+ joint_axis : Vector, optional
1147
+ The rotation as well as translation axis. Note that the components of
1148
+ this axis are the same in the parent_interframe and child_interframe.
1149
+
1150
+ Attributes
1151
+ ==========
1152
+
1153
+ name : string
1154
+ The joint's name.
1155
+ parent : Particle or RigidBody or Body
1156
+ The joint's parent body.
1157
+ child : Particle or RigidBody or Body
1158
+ The joint's child body.
1159
+ rotation_coordinate : dynamicsymbol
1160
+ Generalized coordinate corresponding to the rotation angle.
1161
+ translation_coordinate : dynamicsymbol
1162
+ Generalized coordinate corresponding to the translation distance.
1163
+ rotation_speed : dynamicsymbol
1164
+ Generalized speed corresponding to the angular velocity.
1165
+ translation_speed : dynamicsymbol
1166
+ Generalized speed corresponding to the translation velocity.
1167
+ coordinates : Matrix
1168
+ Matrix of the joint's generalized coordinates.
1169
+ speeds : Matrix
1170
+ Matrix of the joint's generalized speeds.
1171
+ parent_point : Point
1172
+ Attachment point where the joint is fixed to the parent body.
1173
+ child_point : Point
1174
+ Attachment point where the joint is fixed to the child body.
1175
+ parent_interframe : ReferenceFrame
1176
+ Intermediate frame of the parent body with respect to which the joint
1177
+ transformation is formulated.
1178
+ child_interframe : ReferenceFrame
1179
+ Intermediate frame of the child body with respect to which the joint
1180
+ transformation is formulated.
1181
+ kdes : Matrix
1182
+ Kinematical differential equations of the joint.
1183
+ joint_axis : Vector
1184
+ The axis of rotation and translation.
1185
+
1186
+ Examples
1187
+ =========
1188
+
1189
+ A single cylindrical joint is created between two bodies and has the
1190
+ following basic attributes:
1191
+
1192
+ >>> from sympy.physics.mechanics import RigidBody, CylindricalJoint
1193
+ >>> parent = RigidBody('P')
1194
+ >>> parent
1195
+ P
1196
+ >>> child = RigidBody('C')
1197
+ >>> child
1198
+ C
1199
+ >>> joint = CylindricalJoint('PC', parent, child)
1200
+ >>> joint
1201
+ CylindricalJoint: PC parent: P child: C
1202
+ >>> joint.name
1203
+ 'PC'
1204
+ >>> joint.parent
1205
+ P
1206
+ >>> joint.child
1207
+ C
1208
+ >>> joint.parent_point
1209
+ P_masscenter
1210
+ >>> joint.child_point
1211
+ C_masscenter
1212
+ >>> joint.parent_axis
1213
+ P_frame.x
1214
+ >>> joint.child_axis
1215
+ C_frame.x
1216
+ >>> joint.coordinates
1217
+ Matrix([
1218
+ [q0_PC(t)],
1219
+ [q1_PC(t)]])
1220
+ >>> joint.speeds
1221
+ Matrix([
1222
+ [u0_PC(t)],
1223
+ [u1_PC(t)]])
1224
+ >>> child.frame.ang_vel_in(parent.frame)
1225
+ u0_PC(t)*P_frame.x
1226
+ >>> child.frame.dcm(parent.frame)
1227
+ Matrix([
1228
+ [1, 0, 0],
1229
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1230
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1231
+ >>> joint.child_point.pos_from(joint.parent_point)
1232
+ q1_PC(t)*P_frame.x
1233
+ >>> child.masscenter.vel(parent.frame)
1234
+ u1_PC(t)*P_frame.x
1235
+
1236
+ To further demonstrate the use of the cylindrical joint, the kinematics of
1237
+ two cylindrical joints perpendicular to each other can be created as follows.
1238
+
1239
+ >>> from sympy import symbols
1240
+ >>> from sympy.physics.mechanics import RigidBody, CylindricalJoint
1241
+ >>> r, l, w = symbols('r l w')
1242
+
1243
+ First create bodies to represent the fixed floor with a fixed pole on it.
1244
+ The second body represents a freely moving tube around that pole. The third
1245
+ body represents a solid flag freely translating along and rotating around
1246
+ the Y axis of the tube.
1247
+
1248
+ >>> floor = RigidBody('floor')
1249
+ >>> tube = RigidBody('tube')
1250
+ >>> flag = RigidBody('flag')
1251
+
1252
+ The first joint will connect the first tube to the floor with it translating
1253
+ along and rotating around the Z axis of both bodies.
1254
+
1255
+ >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z)
1256
+
1257
+ The second joint will connect the tube perpendicular to the flag along the Y
1258
+ axis of both the tube and the flag, with the joint located at a distance
1259
+ ``r`` from the tube's center of mass and a combination of the distances
1260
+ ``l`` and ``w`` from the flag's center of mass.
1261
+
1262
+ >>> flag_joint = CylindricalJoint('C2', tube, flag,
1263
+ ... parent_point=r * tube.y,
1264
+ ... child_point=-w * flag.y + l * flag.z,
1265
+ ... joint_axis=tube.y)
1266
+
1267
+ Once the joints are established the kinematics of the connected bodies can
1268
+ be accessed. First the direction cosine matrices of both the body and the
1269
+ flag relative to the floor are found:
1270
+
1271
+ >>> tube.frame.dcm(floor.frame)
1272
+ Matrix([
1273
+ [ cos(q0_C1(t)), sin(q0_C1(t)), 0],
1274
+ [-sin(q0_C1(t)), cos(q0_C1(t)), 0],
1275
+ [ 0, 0, 1]])
1276
+ >>> flag.frame.dcm(floor.frame)
1277
+ Matrix([
1278
+ [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))],
1279
+ [ -sin(q0_C1(t)), cos(q0_C1(t)), 0],
1280
+ [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]])
1281
+
1282
+ The position of the flag's center of mass is found with:
1283
+
1284
+ >>> flag.masscenter.pos_from(floor.masscenter)
1285
+ q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z
1286
+
1287
+ The angular velocities of the two tubes can be computed with respect to the
1288
+ floor.
1289
+
1290
+ >>> tube.frame.ang_vel_in(floor.frame)
1291
+ u0_C1(t)*floor_frame.z
1292
+ >>> flag.frame.ang_vel_in(floor.frame)
1293
+ u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y
1294
+
1295
+ Finally, the linear velocities of the two tube centers of mass can be
1296
+ computed with respect to the floor, while expressed in the tube's frame.
1297
+
1298
+ >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame)
1299
+ Matrix([
1300
+ [ 0],
1301
+ [ 0],
1302
+ [u1_C1(t)]])
1303
+ >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify()
1304
+ Matrix([
1305
+ [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)],
1306
+ [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)],
1307
+ [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]])
1308
+
1309
+ """
1310
+
1311
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1312
+ translation_coordinate=None, rotation_speed=None,
1313
+ translation_speed=None, parent_point=None, child_point=None,
1314
+ parent_interframe=None, child_interframe=None,
1315
+ joint_axis=None):
1316
+ self._joint_axis = joint_axis
1317
+ coordinates = (rotation_coordinate, translation_coordinate)
1318
+ speeds = (rotation_speed, translation_speed)
1319
+ super().__init__(name, parent, child, coordinates, speeds,
1320
+ parent_point, child_point,
1321
+ parent_interframe=parent_interframe,
1322
+ child_interframe=child_interframe)
1323
+
1324
+ def __str__(self):
1325
+ return (f'CylindricalJoint: {self.name} parent: {self.parent} '
1326
+ f'child: {self.child}')
1327
+
1328
+ @property
1329
+ def joint_axis(self):
1330
+ """Axis about and along which the rotation and translation occurs."""
1331
+ return self._joint_axis
1332
+
1333
+ @property
1334
+ def rotation_coordinate(self):
1335
+ """Generalized coordinate corresponding to the rotation angle."""
1336
+ return self.coordinates[0]
1337
+
1338
+ @property
1339
+ def translation_coordinate(self):
1340
+ """Generalized coordinate corresponding to the translation distance."""
1341
+ return self.coordinates[1]
1342
+
1343
+ @property
1344
+ def rotation_speed(self):
1345
+ """Generalized speed corresponding to the angular velocity."""
1346
+ return self.speeds[0]
1347
+
1348
+ @property
1349
+ def translation_speed(self):
1350
+ """Generalized speed corresponding to the translation velocity."""
1351
+ return self.speeds[1]
1352
+
1353
+ def _generate_coordinates(self, coordinates):
1354
+ return self._fill_coordinate_list(coordinates, 2, 'q')
1355
+
1356
+ def _generate_speeds(self, speeds):
1357
+ return self._fill_coordinate_list(speeds, 2, 'u')
1358
+
1359
+ def _orient_frames(self):
1360
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1361
+ self.child_interframe.orient_axis(
1362
+ self.parent_interframe, self.joint_axis, self.rotation_coordinate)
1363
+
1364
+ def _set_angular_velocity(self):
1365
+ self.child_interframe.set_ang_vel(
1366
+ self.parent_interframe,
1367
+ self.rotation_speed * self.joint_axis.normalize())
1368
+
1369
+ def _set_linear_velocity(self):
1370
+ self.child_point.set_pos(
1371
+ self.parent_point,
1372
+ self.translation_coordinate * self.joint_axis.normalize())
1373
+ self.parent_point.set_vel(self._parent_frame, 0)
1374
+ self.child_point.set_vel(self._child_frame, 0)
1375
+ self.child_point.set_vel(
1376
+ self._parent_frame,
1377
+ self.translation_speed * self.joint_axis.normalize())
1378
+ self.child.masscenter.v2pt_theory(self.child_point, self._parent_frame,
1379
+ self.child_interframe)
1380
+
1381
+
1382
+ class PlanarJoint(Joint):
1383
+ """Planar Joint.
1384
+
1385
+ .. raw:: html
1386
+ :file: ../../../doc/src/modules/physics/mechanics/api/PlanarJoint.svg
1387
+
1388
+ Explanation
1389
+ ===========
1390
+
1391
+ A planar joint is defined such that the child body translates over a fixed
1392
+ plane of the parent body as well as rotate about the rotation axis, which
1393
+ is perpendicular to that plane. The origin of this plane is the
1394
+ ``parent_point`` and the plane is spanned by two nonparallel planar vectors.
1395
+ The location of the ``child_point`` is based on the planar vectors
1396
+ ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$),
1397
+ i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine
1398
+ matrix between the ``child_interframe`` and ``parent_interframe`` is formed
1399
+ using a simple rotation ($q_0$) about the rotation axis.
1400
+
1401
+ In order to simplify the definition of the ``PlanarJoint``, the
1402
+ ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of
1403
+ the ``parent_interframe`` according to the table below. This ensures that
1404
+ you can only define these vectors by creating a separate frame and supplying
1405
+ that as the interframe. If you however would only like to supply the normals
1406
+ of the plane with respect to the parent and child bodies, then you can also
1407
+ supply those to the ``parent_interframe`` and ``child_interframe``
1408
+ arguments. An example of both of these cases is in the examples section
1409
+ below and the page on the joints framework provides a more detailed
1410
+ explanation of the intermediate frames.
1411
+
1412
+ .. list-table::
1413
+
1414
+ * - ``rotation_axis``
1415
+ - ``parent_interframe.x``
1416
+ * - ``planar_vectors[0]``
1417
+ - ``parent_interframe.y``
1418
+ * - ``planar_vectors[1]``
1419
+ - ``parent_interframe.z``
1420
+
1421
+ Parameters
1422
+ ==========
1423
+
1424
+ name : string
1425
+ A unique name for the joint.
1426
+ parent : Particle or RigidBody or Body
1427
+ The parent body of joint.
1428
+ child : Particle or RigidBody or Body
1429
+ The child body of joint.
1430
+ rotation_coordinate : dynamicsymbol, optional
1431
+ Generalized coordinate corresponding to the rotation angle. The default
1432
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1433
+ planar_coordinates : iterable of dynamicsymbols, optional
1434
+ Two generalized coordinates used for the planar translation. The default
1435
+ value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``.
1436
+ rotation_speed : dynamicsymbol, optional
1437
+ Generalized speed corresponding to the angular velocity. The default
1438
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1439
+ planar_speeds : dynamicsymbols, optional
1440
+ Two generalized speeds used for the planar translation velocity. The
1441
+ default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``.
1442
+ parent_point : Point or Vector, optional
1443
+ Attachment point where the joint is fixed to the parent body. If a
1444
+ vector is provided, then the attachment point is computed by adding the
1445
+ vector to the body's mass center. The default value is the parent's mass
1446
+ center.
1447
+ child_point : Point or Vector, optional
1448
+ Attachment point where the joint is fixed to the child body. If a
1449
+ vector is provided, then the attachment point is computed by adding the
1450
+ vector to the body's mass center. The default value is the child's mass
1451
+ center.
1452
+ parent_interframe : ReferenceFrame, optional
1453
+ Intermediate frame of the parent body with respect to which the joint
1454
+ transformation is formulated. If a Vector is provided then an interframe
1455
+ is created which aligns its X axis with the given vector. The default
1456
+ value is the parent's own frame.
1457
+ child_interframe : ReferenceFrame, optional
1458
+ Intermediate frame of the child body with respect to which the joint
1459
+ transformation is formulated. If a Vector is provided then an interframe
1460
+ is created which aligns its X axis with the given vector. The default
1461
+ value is the child's own frame.
1462
+
1463
+ Attributes
1464
+ ==========
1465
+
1466
+ name : string
1467
+ The joint's name.
1468
+ parent : Particle or RigidBody or Body
1469
+ The joint's parent body.
1470
+ child : Particle or RigidBody or Body
1471
+ The joint's child body.
1472
+ rotation_coordinate : dynamicsymbol
1473
+ Generalized coordinate corresponding to the rotation angle.
1474
+ planar_coordinates : Matrix
1475
+ Two generalized coordinates used for the planar translation.
1476
+ rotation_speed : dynamicsymbol
1477
+ Generalized speed corresponding to the angular velocity.
1478
+ planar_speeds : Matrix
1479
+ Two generalized speeds used for the planar translation velocity.
1480
+ coordinates : Matrix
1481
+ Matrix of the joint's generalized coordinates.
1482
+ speeds : Matrix
1483
+ Matrix of the joint's generalized speeds.
1484
+ parent_point : Point
1485
+ Attachment point where the joint is fixed to the parent body.
1486
+ child_point : Point
1487
+ Attachment point where the joint is fixed to the child body.
1488
+ parent_interframe : ReferenceFrame
1489
+ Intermediate frame of the parent body with respect to which the joint
1490
+ transformation is formulated.
1491
+ child_interframe : ReferenceFrame
1492
+ Intermediate frame of the child body with respect to which the joint
1493
+ transformation is formulated.
1494
+ kdes : Matrix
1495
+ Kinematical differential equations of the joint.
1496
+ rotation_axis : Vector
1497
+ The axis about which the rotation occurs.
1498
+ planar_vectors : list
1499
+ The vectors that describe the planar translation directions.
1500
+
1501
+ Examples
1502
+ =========
1503
+
1504
+ A single planar joint is created between two bodies and has the following
1505
+ basic attributes:
1506
+
1507
+ >>> from sympy.physics.mechanics import RigidBody, PlanarJoint
1508
+ >>> parent = RigidBody('P')
1509
+ >>> parent
1510
+ P
1511
+ >>> child = RigidBody('C')
1512
+ >>> child
1513
+ C
1514
+ >>> joint = PlanarJoint('PC', parent, child)
1515
+ >>> joint
1516
+ PlanarJoint: PC parent: P child: C
1517
+ >>> joint.name
1518
+ 'PC'
1519
+ >>> joint.parent
1520
+ P
1521
+ >>> joint.child
1522
+ C
1523
+ >>> joint.parent_point
1524
+ P_masscenter
1525
+ >>> joint.child_point
1526
+ C_masscenter
1527
+ >>> joint.rotation_axis
1528
+ P_frame.x
1529
+ >>> joint.planar_vectors
1530
+ [P_frame.y, P_frame.z]
1531
+ >>> joint.rotation_coordinate
1532
+ q0_PC(t)
1533
+ >>> joint.planar_coordinates
1534
+ Matrix([
1535
+ [q1_PC(t)],
1536
+ [q2_PC(t)]])
1537
+ >>> joint.coordinates
1538
+ Matrix([
1539
+ [q0_PC(t)],
1540
+ [q1_PC(t)],
1541
+ [q2_PC(t)]])
1542
+ >>> joint.rotation_speed
1543
+ u0_PC(t)
1544
+ >>> joint.planar_speeds
1545
+ Matrix([
1546
+ [u1_PC(t)],
1547
+ [u2_PC(t)]])
1548
+ >>> joint.speeds
1549
+ Matrix([
1550
+ [u0_PC(t)],
1551
+ [u1_PC(t)],
1552
+ [u2_PC(t)]])
1553
+ >>> child.frame.ang_vel_in(parent.frame)
1554
+ u0_PC(t)*P_frame.x
1555
+ >>> child.frame.dcm(parent.frame)
1556
+ Matrix([
1557
+ [1, 0, 0],
1558
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1559
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1560
+ >>> joint.child_point.pos_from(joint.parent_point)
1561
+ q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z
1562
+ >>> child.masscenter.vel(parent.frame)
1563
+ u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z
1564
+
1565
+ To further demonstrate the use of the planar joint, the kinematics of a
1566
+ block sliding on a slope, can be created as follows.
1567
+
1568
+ >>> from sympy import symbols
1569
+ >>> from sympy.physics.mechanics import PlanarJoint, RigidBody, ReferenceFrame
1570
+ >>> a, d, h = symbols('a d h')
1571
+
1572
+ First create bodies to represent the slope and the block.
1573
+
1574
+ >>> ground = RigidBody('G')
1575
+ >>> block = RigidBody('B')
1576
+
1577
+ To define the slope you can either define the plane by specifying the
1578
+ ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to
1579
+ create a rotated intermediate frame, so that the ``parent_vectors`` and
1580
+ ``rotation_axis`` will be the unit vectors of this intermediate frame.
1581
+
1582
+ >>> slope = ReferenceFrame('A')
1583
+ >>> slope.orient_axis(ground.frame, ground.y, a)
1584
+
1585
+ The planar joint can be created using these bodies and intermediate frame.
1586
+ We can specify the origin of the slope to be ``d`` above the slope's center
1587
+ of mass and the block's center of mass to be a distance ``h`` above the
1588
+ slope's surface. Note that we can specify the normal of the plane using the
1589
+ rotation axis argument.
1590
+
1591
+ >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x,
1592
+ ... child_point=-h * block.x, parent_interframe=slope)
1593
+
1594
+ Once the joint is established the kinematics of the bodies can be accessed.
1595
+ First the ``rotation_axis``, which is normal to the plane and the
1596
+ ``plane_vectors``, can be found.
1597
+
1598
+ >>> joint.rotation_axis
1599
+ A.x
1600
+ >>> joint.planar_vectors
1601
+ [A.y, A.z]
1602
+
1603
+ The direction cosine matrix of the block with respect to the ground can be
1604
+ found with:
1605
+
1606
+ >>> block.frame.dcm(ground.frame)
1607
+ Matrix([
1608
+ [ cos(a), 0, -sin(a)],
1609
+ [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1610
+ [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1611
+
1612
+ The angular velocity of the block can be computed with respect to the
1613
+ ground.
1614
+
1615
+ >>> block.frame.ang_vel_in(ground.frame)
1616
+ u0_PC(t)*A.x
1617
+
1618
+ The position of the block's center of mass can be found with:
1619
+
1620
+ >>> block.masscenter.pos_from(ground.masscenter)
1621
+ d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z
1622
+
1623
+ Finally, the linear velocity of the block's center of mass can be
1624
+ computed with respect to the ground.
1625
+
1626
+ >>> block.masscenter.vel(ground.frame)
1627
+ u1_PC(t)*A.y + u2_PC(t)*A.z
1628
+
1629
+ In some cases it could be your preference to only define the normals of the
1630
+ plane with respect to both bodies. This can most easily be done by supplying
1631
+ vectors to the ``interframe`` arguments. What will happen in this case is
1632
+ that an interframe will be created with its ``x`` axis aligned with the
1633
+ provided vector. For a further explanation of how this is done see the notes
1634
+ of the ``Joint`` class. In the code below, the above example (with the block
1635
+ on the slope) is recreated by supplying vectors to the interframe arguments.
1636
+ Note that the previously described option is however more computationally
1637
+ efficient, because the algorithm now has to compute the rotation angle
1638
+ between the provided vector and the 'x' axis.
1639
+
1640
+ >>> from sympy import symbols, cos, sin
1641
+ >>> from sympy.physics.mechanics import PlanarJoint, RigidBody
1642
+ >>> a, d, h = symbols('a d h')
1643
+ >>> ground = RigidBody('G')
1644
+ >>> block = RigidBody('B')
1645
+ >>> joint = PlanarJoint(
1646
+ ... 'PC', ground, block, parent_point=d * ground.x,
1647
+ ... child_point=-h * block.x, child_interframe=block.x,
1648
+ ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z)
1649
+ >>> block.frame.dcm(ground.frame).simplify()
1650
+ Matrix([
1651
+ [ cos(a), 0, sin(a)],
1652
+ [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1653
+ [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1654
+
1655
+ """
1656
+
1657
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1658
+ planar_coordinates=None, rotation_speed=None,
1659
+ planar_speeds=None, parent_point=None, child_point=None,
1660
+ parent_interframe=None, child_interframe=None):
1661
+ # A ready to merge implementation of setting the planar_vectors and
1662
+ # rotation_axis was added and removed in PR #24046
1663
+ coordinates = (rotation_coordinate, planar_coordinates)
1664
+ speeds = (rotation_speed, planar_speeds)
1665
+ super().__init__(name, parent, child, coordinates, speeds,
1666
+ parent_point, child_point,
1667
+ parent_interframe=parent_interframe,
1668
+ child_interframe=child_interframe)
1669
+
1670
+ def __str__(self):
1671
+ return (f'PlanarJoint: {self.name} parent: {self.parent} '
1672
+ f'child: {self.child}')
1673
+
1674
+ @property
1675
+ def rotation_coordinate(self):
1676
+ """Generalized coordinate corresponding to the rotation angle."""
1677
+ return self.coordinates[0]
1678
+
1679
+ @property
1680
+ def planar_coordinates(self):
1681
+ """Two generalized coordinates used for the planar translation."""
1682
+ return self.coordinates[1:, 0]
1683
+
1684
+ @property
1685
+ def rotation_speed(self):
1686
+ """Generalized speed corresponding to the angular velocity."""
1687
+ return self.speeds[0]
1688
+
1689
+ @property
1690
+ def planar_speeds(self):
1691
+ """Two generalized speeds used for the planar translation velocity."""
1692
+ return self.speeds[1:, 0]
1693
+
1694
+ @property
1695
+ def rotation_axis(self):
1696
+ """The axis about which the rotation occurs."""
1697
+ return self.parent_interframe.x
1698
+
1699
+ @property
1700
+ def planar_vectors(self):
1701
+ """The vectors that describe the planar translation directions."""
1702
+ return [self.parent_interframe.y, self.parent_interframe.z]
1703
+
1704
+ def _generate_coordinates(self, coordinates):
1705
+ rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q',
1706
+ number_single=True)
1707
+ planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1)
1708
+ return rotation_speed.col_join(planar_speeds)
1709
+
1710
+ def _generate_speeds(self, speeds):
1711
+ rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u',
1712
+ number_single=True)
1713
+ planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1)
1714
+ return rotation_speed.col_join(planar_speeds)
1715
+
1716
+ def _orient_frames(self):
1717
+ self.child_interframe.orient_axis(
1718
+ self.parent_interframe, self.rotation_axis,
1719
+ self.rotation_coordinate)
1720
+
1721
+ def _set_angular_velocity(self):
1722
+ self.child_interframe.set_ang_vel(
1723
+ self.parent_interframe,
1724
+ self.rotation_speed * self.rotation_axis)
1725
+
1726
+ def _set_linear_velocity(self):
1727
+ self.child_point.set_pos(
1728
+ self.parent_point,
1729
+ self.planar_coordinates[0] * self.planar_vectors[0] +
1730
+ self.planar_coordinates[1] * self.planar_vectors[1])
1731
+ self.parent_point.set_vel(self.parent_interframe, 0)
1732
+ self.child_point.set_vel(self.child_interframe, 0)
1733
+ self.child_point.set_vel(
1734
+ self._parent_frame, self.planar_speeds[0] * self.planar_vectors[0] +
1735
+ self.planar_speeds[1] * self.planar_vectors[1])
1736
+ self.child.masscenter.v2pt_theory(self.child_point, self._parent_frame,
1737
+ self._child_frame)
1738
+
1739
+
1740
+ class SphericalJoint(Joint):
1741
+ """Spherical (Ball-and-Socket) Joint.
1742
+
1743
+ .. image:: SphericalJoint.svg
1744
+ :align: center
1745
+ :width: 600
1746
+
1747
+ Explanation
1748
+ ===========
1749
+
1750
+ A spherical joint is defined such that the child body is free to rotate in
1751
+ any direction, without allowing a translation of the ``child_point``. As can
1752
+ also be seen in the image, the ``parent_point`` and ``child_point`` are
1753
+ fixed on top of each other, i.e. the ``joint_point``. This rotation is
1754
+ defined using the :func:`parent_interframe.orient(child_interframe,
1755
+ rot_type, amounts, rot_order)
1756
+ <sympy.physics.vector.frame.ReferenceFrame.orient>` method. The default
1757
+ rotation consists of three relative rotations, i.e. body-fixed rotations.
1758
+ Based on the direction cosine matrix following from these rotations, the
1759
+ angular velocity is computed based on the generalized coordinates and
1760
+ generalized speeds.
1761
+
1762
+ Parameters
1763
+ ==========
1764
+
1765
+ name : string
1766
+ A unique name for the joint.
1767
+ parent : Particle or RigidBody or Body
1768
+ The parent body of joint.
1769
+ child : Particle or RigidBody or Body
1770
+ The child body of joint.
1771
+ coordinates: iterable of dynamicsymbols, optional
1772
+ Generalized coordinates of the joint.
1773
+ speeds : iterable of dynamicsymbols, optional
1774
+ Generalized speeds of joint.
1775
+ parent_point : Point or Vector, optional
1776
+ Attachment point where the joint is fixed to the parent body. If a
1777
+ vector is provided, then the attachment point is computed by adding the
1778
+ vector to the body's mass center. The default value is the parent's mass
1779
+ center.
1780
+ child_point : Point or Vector, optional
1781
+ Attachment point where the joint is fixed to the child body. If a
1782
+ vector is provided, then the attachment point is computed by adding the
1783
+ vector to the body's mass center. The default value is the child's mass
1784
+ center.
1785
+ parent_interframe : ReferenceFrame, optional
1786
+ Intermediate frame of the parent body with respect to which the joint
1787
+ transformation is formulated. If a Vector is provided then an interframe
1788
+ is created which aligns its X axis with the given vector. The default
1789
+ value is the parent's own frame.
1790
+ child_interframe : ReferenceFrame, optional
1791
+ Intermediate frame of the child body with respect to which the joint
1792
+ transformation is formulated. If a Vector is provided then an interframe
1793
+ is created which aligns its X axis with the given vector. The default
1794
+ value is the child's own frame.
1795
+ rot_type : str, optional
1796
+ The method used to generate the direction cosine matrix. Supported
1797
+ methods are:
1798
+
1799
+ - ``'Body'``: three successive rotations about new intermediate axes,
1800
+ also called "Euler and Tait-Bryan angles"
1801
+ - ``'Space'``: three successive rotations about the parent frames' unit
1802
+ vectors
1803
+
1804
+ The default method is ``'Body'``.
1805
+ amounts :
1806
+ Expressions defining the rotation angles or direction cosine matrix.
1807
+ These must match the ``rot_type``. See examples below for details. The
1808
+ input types are:
1809
+
1810
+ - ``'Body'``: 3-tuple of expressions, symbols, or functions
1811
+ - ``'Space'``: 3-tuple of expressions, symbols, or functions
1812
+
1813
+ The default amounts are the given ``coordinates``.
1814
+ rot_order : str or int, optional
1815
+ If applicable, the order of the successive of rotations. The string
1816
+ ``'123'`` and integer ``123`` are equivalent, for example. Required for
1817
+ ``'Body'`` and ``'Space'``. The default value is ``123``.
1818
+
1819
+ Attributes
1820
+ ==========
1821
+
1822
+ name : string
1823
+ The joint's name.
1824
+ parent : Particle or RigidBody or Body
1825
+ The joint's parent body.
1826
+ child : Particle or RigidBody or Body
1827
+ The joint's child body.
1828
+ coordinates : Matrix
1829
+ Matrix of the joint's generalized coordinates.
1830
+ speeds : Matrix
1831
+ Matrix of the joint's generalized speeds.
1832
+ parent_point : Point
1833
+ Attachment point where the joint is fixed to the parent body.
1834
+ child_point : Point
1835
+ Attachment point where the joint is fixed to the child body.
1836
+ parent_interframe : ReferenceFrame
1837
+ Intermediate frame of the parent body with respect to which the joint
1838
+ transformation is formulated.
1839
+ child_interframe : ReferenceFrame
1840
+ Intermediate frame of the child body with respect to which the joint
1841
+ transformation is formulated.
1842
+ kdes : Matrix
1843
+ Kinematical differential equations of the joint.
1844
+
1845
+ Examples
1846
+ =========
1847
+
1848
+ A single spherical joint is created from two bodies and has the following
1849
+ basic attributes:
1850
+
1851
+ >>> from sympy.physics.mechanics import RigidBody, SphericalJoint
1852
+ >>> parent = RigidBody('P')
1853
+ >>> parent
1854
+ P
1855
+ >>> child = RigidBody('C')
1856
+ >>> child
1857
+ C
1858
+ >>> joint = SphericalJoint('PC', parent, child)
1859
+ >>> joint
1860
+ SphericalJoint: PC parent: P child: C
1861
+ >>> joint.name
1862
+ 'PC'
1863
+ >>> joint.parent
1864
+ P
1865
+ >>> joint.child
1866
+ C
1867
+ >>> joint.parent_point
1868
+ P_masscenter
1869
+ >>> joint.child_point
1870
+ C_masscenter
1871
+ >>> joint.parent_interframe
1872
+ P_frame
1873
+ >>> joint.child_interframe
1874
+ C_frame
1875
+ >>> joint.coordinates
1876
+ Matrix([
1877
+ [q0_PC(t)],
1878
+ [q1_PC(t)],
1879
+ [q2_PC(t)]])
1880
+ >>> joint.speeds
1881
+ Matrix([
1882
+ [u0_PC(t)],
1883
+ [u1_PC(t)],
1884
+ [u2_PC(t)]])
1885
+ >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame)
1886
+ Matrix([
1887
+ [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))],
1888
+ [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))],
1889
+ [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]])
1890
+ >>> child.frame.x.to_matrix(parent.frame)
1891
+ Matrix([
1892
+ [ cos(q1_PC(t))*cos(q2_PC(t))],
1893
+ [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))],
1894
+ [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]])
1895
+ >>> joint.child_point.pos_from(joint.parent_point)
1896
+ 0
1897
+
1898
+ To further demonstrate the use of the spherical joint, the kinematics of a
1899
+ spherical joint with a ZXZ rotation can be created as follows.
1900
+
1901
+ >>> from sympy import symbols
1902
+ >>> from sympy.physics.mechanics import RigidBody, SphericalJoint
1903
+ >>> l1 = symbols('l1')
1904
+
1905
+ First create bodies to represent the fixed floor and a pendulum bob.
1906
+
1907
+ >>> floor = RigidBody('F')
1908
+ >>> bob = RigidBody('B')
1909
+
1910
+ The joint will connect the bob to the floor, with the joint located at a
1911
+ distance of ``l1`` from the child's center of mass and the rotation set to a
1912
+ body-fixed ZXZ rotation.
1913
+
1914
+ >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y,
1915
+ ... rot_type='body', rot_order='ZXZ')
1916
+
1917
+ Now that the joint is established, the kinematics of the connected body can
1918
+ be accessed.
1919
+
1920
+ The position of the bob's masscenter is found with:
1921
+
1922
+ >>> bob.masscenter.pos_from(floor.masscenter)
1923
+ - l1*B_frame.y
1924
+
1925
+ The angular velocities of the pendulum link can be computed with respect to
1926
+ the floor.
1927
+
1928
+ >>> bob.frame.ang_vel_in(floor.frame).to_matrix(
1929
+ ... floor.frame).simplify()
1930
+ Matrix([
1931
+ [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))],
1932
+ [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))],
1933
+ [ u0_S(t) + u2_S(t)*cos(q1_S(t))]])
1934
+
1935
+ Finally, the linear velocity of the bob's center of mass can be computed.
1936
+
1937
+ >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame)
1938
+ Matrix([
1939
+ [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))],
1940
+ [ 0],
1941
+ [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]])
1942
+
1943
+ """
1944
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1945
+ parent_point=None, child_point=None, parent_interframe=None,
1946
+ child_interframe=None, rot_type='BODY', amounts=None,
1947
+ rot_order=123):
1948
+ self._rot_type = rot_type
1949
+ self._amounts = amounts
1950
+ self._rot_order = rot_order
1951
+ super().__init__(name, parent, child, coordinates, speeds,
1952
+ parent_point, child_point,
1953
+ parent_interframe=parent_interframe,
1954
+ child_interframe=child_interframe)
1955
+
1956
+ def __str__(self):
1957
+ return (f'SphericalJoint: {self.name} parent: {self.parent} '
1958
+ f'child: {self.child}')
1959
+
1960
+ def _generate_coordinates(self, coordinates):
1961
+ return self._fill_coordinate_list(coordinates, 3, 'q')
1962
+
1963
+ def _generate_speeds(self, speeds):
1964
+ return self._fill_coordinate_list(speeds, len(self.coordinates), 'u')
1965
+
1966
+ def _orient_frames(self):
1967
+ supported_rot_types = ('BODY', 'SPACE')
1968
+ if self._rot_type.upper() not in supported_rot_types:
1969
+ raise NotImplementedError(
1970
+ f'Rotation type "{self._rot_type}" is not implemented. '
1971
+ f'Implemented rotation types are: {supported_rot_types}')
1972
+ amounts = self.coordinates if self._amounts is None else self._amounts
1973
+ self.child_interframe.orient(self.parent_interframe, self._rot_type,
1974
+ amounts, self._rot_order)
1975
+
1976
+ def _set_angular_velocity(self):
1977
+ t = dynamicsymbols._t
1978
+ vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace(
1979
+ {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)}
1980
+ )
1981
+ self.child_interframe.set_ang_vel(self.parent_interframe, vel)
1982
+
1983
+ def _set_linear_velocity(self):
1984
+ self.child_point.set_pos(self.parent_point, 0)
1985
+ self.parent_point.set_vel(self._parent_frame, 0)
1986
+ self.child_point.set_vel(self._child_frame, 0)
1987
+ self.child.masscenter.v2pt_theory(self.parent_point, self._parent_frame,
1988
+ self._child_frame)
1989
+
1990
+
1991
+ class WeldJoint(Joint):
1992
+ """Weld Joint.
1993
+
1994
+ .. raw:: html
1995
+ :file: ../../../doc/src/modules/physics/mechanics/api/WeldJoint.svg
1996
+
1997
+ Explanation
1998
+ ===========
1999
+
2000
+ A weld joint is defined such that there is no relative motion between the
2001
+ child and parent bodies. The direction cosine matrix between the attachment
2002
+ frame (``parent_interframe`` and ``child_interframe``) is the identity
2003
+ matrix and the attachment points (``parent_point`` and ``child_point``) are
2004
+ coincident. The page on the joints framework gives a more detailed
2005
+ explanation of the intermediate frames.
2006
+
2007
+ Parameters
2008
+ ==========
2009
+
2010
+ name : string
2011
+ A unique name for the joint.
2012
+ parent : Particle or RigidBody or Body
2013
+ The parent body of joint.
2014
+ child : Particle or RigidBody or Body
2015
+ The child body of joint.
2016
+ parent_point : Point or Vector, optional
2017
+ Attachment point where the joint is fixed to the parent body. If a
2018
+ vector is provided, then the attachment point is computed by adding the
2019
+ vector to the body's mass center. The default value is the parent's mass
2020
+ center.
2021
+ child_point : Point or Vector, optional
2022
+ Attachment point where the joint is fixed to the child body. If a
2023
+ vector is provided, then the attachment point is computed by adding the
2024
+ vector to the body's mass center. The default value is the child's mass
2025
+ center.
2026
+ parent_interframe : ReferenceFrame, optional
2027
+ Intermediate frame of the parent body with respect to which the joint
2028
+ transformation is formulated. If a Vector is provided then an interframe
2029
+ is created which aligns its X axis with the given vector. The default
2030
+ value is the parent's own frame.
2031
+ child_interframe : ReferenceFrame, optional
2032
+ Intermediate frame of the child body with respect to which the joint
2033
+ transformation is formulated. If a Vector is provided then an interframe
2034
+ is created which aligns its X axis with the given vector. The default
2035
+ value is the child's own frame.
2036
+
2037
+ Attributes
2038
+ ==========
2039
+
2040
+ name : string
2041
+ The joint's name.
2042
+ parent : Particle or RigidBody or Body
2043
+ The joint's parent body.
2044
+ child : Particle or RigidBody or Body
2045
+ The joint's child body.
2046
+ coordinates : Matrix
2047
+ Matrix of the joint's generalized coordinates. The default value is
2048
+ ``dynamicsymbols(f'q_{joint.name}')``.
2049
+ speeds : Matrix
2050
+ Matrix of the joint's generalized speeds. The default value is
2051
+ ``dynamicsymbols(f'u_{joint.name}')``.
2052
+ parent_point : Point
2053
+ Attachment point where the joint is fixed to the parent body.
2054
+ child_point : Point
2055
+ Attachment point where the joint is fixed to the child body.
2056
+ parent_interframe : ReferenceFrame
2057
+ Intermediate frame of the parent body with respect to which the joint
2058
+ transformation is formulated.
2059
+ child_interframe : ReferenceFrame
2060
+ Intermediate frame of the child body with respect to which the joint
2061
+ transformation is formulated.
2062
+ kdes : Matrix
2063
+ Kinematical differential equations of the joint.
2064
+
2065
+ Examples
2066
+ =========
2067
+
2068
+ A single weld joint is created from two bodies and has the following basic
2069
+ attributes:
2070
+
2071
+ >>> from sympy.physics.mechanics import RigidBody, WeldJoint
2072
+ >>> parent = RigidBody('P')
2073
+ >>> parent
2074
+ P
2075
+ >>> child = RigidBody('C')
2076
+ >>> child
2077
+ C
2078
+ >>> joint = WeldJoint('PC', parent, child)
2079
+ >>> joint
2080
+ WeldJoint: PC parent: P child: C
2081
+ >>> joint.name
2082
+ 'PC'
2083
+ >>> joint.parent
2084
+ P
2085
+ >>> joint.child
2086
+ C
2087
+ >>> joint.parent_point
2088
+ P_masscenter
2089
+ >>> joint.child_point
2090
+ C_masscenter
2091
+ >>> joint.coordinates
2092
+ Matrix(0, 0, [])
2093
+ >>> joint.speeds
2094
+ Matrix(0, 0, [])
2095
+ >>> child.frame.ang_vel_in(parent.frame)
2096
+ 0
2097
+ >>> child.frame.dcm(parent.frame)
2098
+ Matrix([
2099
+ [1, 0, 0],
2100
+ [0, 1, 0],
2101
+ [0, 0, 1]])
2102
+ >>> joint.child_point.pos_from(joint.parent_point)
2103
+ 0
2104
+
2105
+ To further demonstrate the use of the weld joint, two relatively-fixed
2106
+ bodies rotated by a quarter turn about the Y axis can be created as follows:
2107
+
2108
+ >>> from sympy import symbols, pi
2109
+ >>> from sympy.physics.mechanics import ReferenceFrame, RigidBody, WeldJoint
2110
+ >>> l1, l2 = symbols('l1 l2')
2111
+
2112
+ First create the bodies to represent the parent and rotated child body.
2113
+
2114
+ >>> parent = RigidBody('P')
2115
+ >>> child = RigidBody('C')
2116
+
2117
+ Next the intermediate frame specifying the fixed rotation with respect to
2118
+ the parent can be created.
2119
+
2120
+ >>> rotated_frame = ReferenceFrame('Pr')
2121
+ >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2)
2122
+
2123
+ The weld between the parent body and child body is located at a distance
2124
+ ``l1`` from the parent's center of mass in the X direction and ``l2`` from
2125
+ the child's center of mass in the child's negative X direction.
2126
+
2127
+ >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x,
2128
+ ... child_point=-l2 * child.x,
2129
+ ... parent_interframe=rotated_frame)
2130
+
2131
+ Now that the joint has been established, the kinematics of the bodies can be
2132
+ accessed. The direction cosine matrix of the child body with respect to the
2133
+ parent can be found:
2134
+
2135
+ >>> child.frame.dcm(parent.frame)
2136
+ Matrix([
2137
+ [0, 0, -1],
2138
+ [0, 1, 0],
2139
+ [1, 0, 0]])
2140
+
2141
+ As can also been seen from the direction cosine matrix, the parent X axis is
2142
+ aligned with the child's Z axis:
2143
+ >>> parent.x == child.z
2144
+ True
2145
+
2146
+ The position of the child's center of mass with respect to the parent's
2147
+ center of mass can be found with:
2148
+
2149
+ >>> child.masscenter.pos_from(parent.masscenter)
2150
+ l1*P_frame.x + l2*C_frame.x
2151
+
2152
+ The angular velocity of the child with respect to the parent is 0 as one
2153
+ would expect.
2154
+
2155
+ >>> child.frame.ang_vel_in(parent.frame)
2156
+ 0
2157
+
2158
+ """
2159
+
2160
+ def __init__(self, name, parent, child, parent_point=None, child_point=None,
2161
+ parent_interframe=None, child_interframe=None):
2162
+ super().__init__(name, parent, child, [], [], parent_point,
2163
+ child_point, parent_interframe=parent_interframe,
2164
+ child_interframe=child_interframe)
2165
+ self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770
2166
+
2167
+ def __str__(self):
2168
+ return (f'WeldJoint: {self.name} parent: {self.parent} '
2169
+ f'child: {self.child}')
2170
+
2171
+ def _generate_coordinates(self, coordinate):
2172
+ return Matrix()
2173
+
2174
+ def _generate_speeds(self, speed):
2175
+ return Matrix()
2176
+
2177
+ def _orient_frames(self):
2178
+ self.child_interframe.orient_axis(self.parent_interframe,
2179
+ self.parent_interframe.x, 0)
2180
+
2181
+ def _set_angular_velocity(self):
2182
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
2183
+
2184
+ def _set_linear_velocity(self):
2185
+ self.child_point.set_pos(self.parent_point, 0)
2186
+ self.parent_point.set_vel(self._parent_frame, 0)
2187
+ self.child_point.set_vel(self._child_frame, 0)
2188
+ self.child.masscenter.set_vel(self._parent_frame, 0)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
2
+ RigidBody, Particle)
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.mechanics.method import _Methods
5
+ from sympy import Matrix
6
+ from sympy.utilities.exceptions import sympy_deprecation_warning
7
+
8
+ __all__ = ['JointsMethod']
9
+
10
+
11
+ class JointsMethod(_Methods):
12
+ """Method for formulating the equations of motion using a set of interconnected bodies with joints.
13
+
14
+ .. deprecated:: 1.13
15
+ The JointsMethod class is deprecated. Its functionality has been
16
+ replaced by the new :class:`~.System` class.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ newtonion : Body or ReferenceFrame
22
+ The newtonion(inertial) frame.
23
+ *joints : Joint
24
+ The joints in the system
25
+
26
+ Attributes
27
+ ==========
28
+
29
+ q, u : iterable
30
+ Iterable of the generalized coordinates and speeds
31
+ bodies : iterable
32
+ Iterable of Body objects in the system.
33
+ loads : iterable
34
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
35
+ describing the forces on the system.
36
+ mass_matrix : Matrix, shape(n, n)
37
+ The system's mass matrix
38
+ forcing : Matrix, shape(n, 1)
39
+ The system's forcing vector
40
+ mass_matrix_full : Matrix, shape(2*n, 2*n)
41
+ The "mass matrix" for the u's and q's
42
+ forcing_full : Matrix, shape(2*n, 1)
43
+ The "forcing vector" for the u's and q's
44
+ method : KanesMethod or Lagrange's method
45
+ Method's object.
46
+ kdes : iterable
47
+ Iterable of kde in they system.
48
+
49
+ Examples
50
+ ========
51
+
52
+ As Body and JointsMethod have been deprecated, the following examples are
53
+ for illustrative purposes only. The functionality of Body is fully captured
54
+ by :class:`~.RigidBody` and :class:`~.Particle` and the functionality of
55
+ JointsMethod is fully captured by :class:`~.System`. To ignore the
56
+ deprecation warning we can use the ignore_warnings context manager.
57
+
58
+ >>> from sympy.utilities.exceptions import ignore_warnings
59
+
60
+ This is a simple example for a one degree of freedom translational
61
+ spring-mass-damper.
62
+
63
+ >>> from sympy import symbols
64
+ >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
65
+ >>> from sympy.physics.vector import dynamicsymbols
66
+ >>> c, k = symbols('c k')
67
+ >>> x, v = dynamicsymbols('x v')
68
+ >>> with ignore_warnings(DeprecationWarning):
69
+ ... wall = Body('W')
70
+ ... body = Body('B')
71
+ >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
72
+ >>> wall.apply_force(c*v*wall.x, reaction_body=body)
73
+ >>> wall.apply_force(k*x*wall.x, reaction_body=body)
74
+ >>> with ignore_warnings(DeprecationWarning):
75
+ ... method = JointsMethod(wall, J)
76
+ >>> method.form_eoms()
77
+ Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
78
+ >>> M = method.mass_matrix_full
79
+ >>> F = method.forcing_full
80
+ >>> rhs = M.LUsolve(F)
81
+ >>> rhs
82
+ Matrix([
83
+ [ v(t)],
84
+ [(-c*v(t) - k*x(t))/B_mass]])
85
+
86
+ Notes
87
+ =====
88
+
89
+ ``JointsMethod`` currently only works with systems that do not have any
90
+ configuration or motion constraints.
91
+
92
+ """
93
+
94
+ def __init__(self, newtonion, *joints):
95
+ sympy_deprecation_warning(
96
+ """
97
+ The JointsMethod class is deprecated.
98
+ Its functionality has been replaced by the new System class.
99
+ """,
100
+ deprecated_since_version="1.13",
101
+ active_deprecations_target="deprecated-mechanics-jointsmethod"
102
+ )
103
+ if isinstance(newtonion, BodyBase):
104
+ self.frame = newtonion.frame
105
+ else:
106
+ self.frame = newtonion
107
+
108
+ self._joints = joints
109
+ self._bodies = self._generate_bodylist()
110
+ self._loads = self._generate_loadlist()
111
+ self._q = self._generate_q()
112
+ self._u = self._generate_u()
113
+ self._kdes = self._generate_kdes()
114
+
115
+ self._method = None
116
+
117
+ @property
118
+ def bodies(self):
119
+ """List of bodies in they system."""
120
+ return self._bodies
121
+
122
+ @property
123
+ def loads(self):
124
+ """List of loads on the system."""
125
+ return self._loads
126
+
127
+ @property
128
+ def q(self):
129
+ """List of the generalized coordinates."""
130
+ return self._q
131
+
132
+ @property
133
+ def u(self):
134
+ """List of the generalized speeds."""
135
+ return self._u
136
+
137
+ @property
138
+ def kdes(self):
139
+ """List of the generalized coordinates."""
140
+ return self._kdes
141
+
142
+ @property
143
+ def forcing_full(self):
144
+ """The "forcing vector" for the u's and q's."""
145
+ return self.method.forcing_full
146
+
147
+ @property
148
+ def mass_matrix_full(self):
149
+ """The "mass matrix" for the u's and q's."""
150
+ return self.method.mass_matrix_full
151
+
152
+ @property
153
+ def mass_matrix(self):
154
+ """The system's mass matrix."""
155
+ return self.method.mass_matrix
156
+
157
+ @property
158
+ def forcing(self):
159
+ """The system's forcing vector."""
160
+ return self.method.forcing
161
+
162
+ @property
163
+ def method(self):
164
+ """Object of method used to form equations of systems."""
165
+ return self._method
166
+
167
+ def _generate_bodylist(self):
168
+ bodies = []
169
+ for joint in self._joints:
170
+ if joint.child not in bodies:
171
+ bodies.append(joint.child)
172
+ if joint.parent not in bodies:
173
+ bodies.append(joint.parent)
174
+ return bodies
175
+
176
+ def _generate_loadlist(self):
177
+ load_list = []
178
+ for body in self.bodies:
179
+ if isinstance(body, Body):
180
+ load_list.extend(body.loads)
181
+ return load_list
182
+
183
+ def _generate_q(self):
184
+ q_ind = []
185
+ for joint in self._joints:
186
+ for coordinate in joint.coordinates:
187
+ if coordinate in q_ind:
188
+ raise ValueError('Coordinates of joints should be unique.')
189
+ q_ind.append(coordinate)
190
+ return Matrix(q_ind)
191
+
192
+ def _generate_u(self):
193
+ u_ind = []
194
+ for joint in self._joints:
195
+ for speed in joint.speeds:
196
+ if speed in u_ind:
197
+ raise ValueError('Speeds of joints should be unique.')
198
+ u_ind.append(speed)
199
+ return Matrix(u_ind)
200
+
201
+ def _generate_kdes(self):
202
+ kd_ind = Matrix(1, 0, []).T
203
+ for joint in self._joints:
204
+ kd_ind = kd_ind.col_join(joint.kdes)
205
+ return kd_ind
206
+
207
+ def _convert_bodies(self):
208
+ # Convert `Body` to `Particle` and `RigidBody`
209
+ bodylist = []
210
+ for body in self.bodies:
211
+ if not isinstance(body, Body):
212
+ bodylist.append(body)
213
+ continue
214
+ if body.is_rigidbody:
215
+ rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
216
+ (body.central_inertia, body.masscenter))
217
+ rb.potential_energy = body.potential_energy
218
+ bodylist.append(rb)
219
+ else:
220
+ part = Particle(body.name, body.masscenter, body.mass)
221
+ part.potential_energy = body.potential_energy
222
+ bodylist.append(part)
223
+ return bodylist
224
+
225
+ def form_eoms(self, method=KanesMethod):
226
+ """Method to form system's equation of motions.
227
+
228
+ Parameters
229
+ ==========
230
+
231
+ method : Class
232
+ Class name of method.
233
+
234
+ Returns
235
+ ========
236
+
237
+ Matrix
238
+ Vector of equations of motions.
239
+
240
+ Examples
241
+ ========
242
+
243
+ As Body and JointsMethod have been deprecated, the following examples
244
+ are for illustrative purposes only. The functionality of Body is fully
245
+ captured by :class:`~.RigidBody` and :class:`~.Particle` and the
246
+ functionality of JointsMethod is fully captured by :class:`~.System`. To
247
+ ignore the deprecation warning we can use the ignore_warnings context
248
+ manager.
249
+
250
+ >>> from sympy.utilities.exceptions import ignore_warnings
251
+
252
+ This is a simple example for a one degree of freedom translational
253
+ spring-mass-damper.
254
+
255
+ >>> from sympy import S, symbols
256
+ >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
257
+ >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
258
+ >>> q = dynamicsymbols('q')
259
+ >>> qd = dynamicsymbols('q', 1)
260
+ >>> m, k, b = symbols('m k b')
261
+ >>> with ignore_warnings(DeprecationWarning):
262
+ ... wall = Body('W')
263
+ ... part = Body('P', mass=m)
264
+ >>> part.potential_energy = k * q**2 / S(2)
265
+ >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
266
+ >>> wall.apply_force(b * qd * wall.x, reaction_body=part)
267
+ >>> with ignore_warnings(DeprecationWarning):
268
+ ... method = JointsMethod(wall, J)
269
+ >>> method.form_eoms(LagrangesMethod)
270
+ Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
271
+
272
+ We can also solve for the states using the 'rhs' method.
273
+
274
+ >>> method.rhs()
275
+ Matrix([
276
+ [ Derivative(q(t), t)],
277
+ [(-b*Derivative(q(t), t) - k*q(t))/m]])
278
+
279
+ """
280
+
281
+ bodylist = self._convert_bodies()
282
+ if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
283
+ L = Lagrangian(self.frame, *bodylist)
284
+ self._method = method(L, self.q, self.loads, bodylist, self.frame)
285
+ else: #KanesMethod or similar
286
+ self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
287
+ forcelist=self.loads, bodies=bodylist)
288
+ soln = self.method._form_eoms()
289
+ return soln
290
+
291
+ def rhs(self, inv_method=None):
292
+ """Returns equations that can be solved numerically.
293
+
294
+ Parameters
295
+ ==========
296
+
297
+ inv_method : str
298
+ The specific sympy inverse matrix calculation method to use. For a
299
+ list of valid methods, see
300
+ :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
301
+
302
+ Returns
303
+ ========
304
+
305
+ Matrix
306
+ Numerically solvable equations.
307
+
308
+ See Also
309
+ ========
310
+
311
+ sympy.physics.mechanics.kane.KanesMethod.rhs:
312
+ KanesMethod's rhs function.
313
+ sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
314
+ LagrangesMethod's rhs function.
315
+
316
+ """
317
+
318
+ return self.method.rhs(inv_method=inv_method)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy 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 (msubs, find_dynamicsymbols,
9
+ _f_list_parser,
10
+ _validate_coordinates,
11
+ _parse_linear_solver)
12
+ from sympy.physics.mechanics.linearize import Linearizer
13
+ from sympy.utilities.iterables import iterable
14
+
15
+ __all__ = ['KanesMethod']
16
+
17
+
18
+ class KanesMethod(_Methods):
19
+ r"""Kane's method object.
20
+
21
+ Explanation
22
+ ===========
23
+
24
+ This object is used to do the "book-keeping" as you go through and form
25
+ equations of motion in the way Kane presents in:
26
+ Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
27
+
28
+ The attributes are for equations in the form [M] udot = forcing.
29
+
30
+ Attributes
31
+ ==========
32
+
33
+ q, u : Matrix
34
+ Matrices of the generalized coordinates and speeds
35
+ bodies : iterable
36
+ Iterable of Particle and RigidBody objects in the system.
37
+ loads : iterable
38
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
39
+ describing the forces on the system.
40
+ auxiliary_eqs : Matrix
41
+ If applicable, the set of auxiliary Kane's
42
+ equations used to solve for non-contributing
43
+ forces.
44
+ mass_matrix : Matrix
45
+ The system's dynamics mass matrix: [k_d; k_dnh]
46
+ forcing : Matrix
47
+ The system's dynamics forcing vector: -[f_d; f_dnh]
48
+ mass_matrix_kin : Matrix
49
+ The "mass matrix" for kinematic differential equations: k_kqdot
50
+ forcing_kin : Matrix
51
+ The forcing vector for kinematic differential equations: -(k_ku*u + f_k)
52
+ mass_matrix_full : Matrix
53
+ The "mass matrix" for the u's and q's with dynamics and kinematics
54
+ forcing_full : Matrix
55
+ The "forcing vector" for the u's and q's with dynamics and kinematics
56
+
57
+ Parameters
58
+ ==========
59
+
60
+ frame : ReferenceFrame
61
+ The inertial reference frame for the system.
62
+ q_ind : iterable of dynamicsymbols
63
+ Independent generalized coordinates.
64
+ u_ind : iterable of dynamicsymbols
65
+ Independent generalized speeds.
66
+ kd_eqs : iterable of Expr, optional
67
+ Kinematic differential equations, which linearly relate the generalized
68
+ speeds to the time-derivatives of the generalized coordinates.
69
+ q_dependent : iterable of dynamicsymbols, optional
70
+ Dependent generalized coordinates.
71
+ configuration_constraints : iterable of Expr, optional
72
+ Constraints on the system's configuration, i.e. holonomic constraints.
73
+ u_dependent : iterable of dynamicsymbols, optional
74
+ Dependent generalized speeds.
75
+ velocity_constraints : iterable of Expr, optional
76
+ Constraints on the system's velocity, i.e. the combination of the
77
+ nonholonomic constraints and the time-derivative of the holonomic
78
+ constraints.
79
+ acceleration_constraints : iterable of Expr, optional
80
+ Constraints on the system's acceleration, by default these are the
81
+ time-derivative of the velocity constraints.
82
+ u_auxiliary : iterable of dynamicsymbols, optional
83
+ Auxiliary generalized speeds.
84
+ bodies : iterable of Particle and/or RigidBody, optional
85
+ The particles and rigid bodies in the system.
86
+ forcelist : iterable of tuple[Point | ReferenceFrame, Vector], optional
87
+ Forces and torques applied on the system.
88
+ explicit_kinematics : bool
89
+ Boolean whether the mass matrices and forcing vectors should use the
90
+ explicit form (default) or implicit form for kinematics.
91
+ See the notes for more details.
92
+ kd_eqs_solver : str, callable
93
+ Method used to solve the kinematic differential equations. If a string
94
+ is supplied, it should be a valid method that can be used with the
95
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
96
+ supplied, it should have the format ``f(A, rhs)``, where it solves the
97
+ equations and returns the solution. The default utilizes LU solve. See
98
+ the notes for more information.
99
+ constraint_solver : str, callable
100
+ Method used to solve the velocity constraints. If a string is
101
+ supplied, it should be a valid method that can be used with the
102
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
103
+ supplied, it should have the format ``f(A, rhs)``, where it solves the
104
+ equations and returns the solution. The default utilizes LU solve. See
105
+ the notes for more information.
106
+
107
+ Notes
108
+ =====
109
+
110
+ The mass matrices and forcing vectors related to kinematic equations
111
+ are given in the explicit form by default. In other words, the kinematic
112
+ mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$.
113
+ In order to get the implicit form of those matrices/vectors, you can set the
114
+ ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$
115
+ is not necessarily an identity matrix. This can provide more compact
116
+ equations for non-simple kinematics.
117
+
118
+ Two linear solvers can be supplied to ``KanesMethod``: one for solving the
119
+ kinematic differential equations and one to solve the velocity constraints.
120
+ Both of these sets of equations can be expressed as a linear system ``Ax = rhs``,
121
+ which have to be solved in order to obtain the equations of motion.
122
+
123
+ The default solver ``'LU'``, which stands for LU solve, results relatively low
124
+ number of operations. The weakness of this method is that it can result in zero
125
+ division errors.
126
+
127
+ If zero divisions are encountered, a possible solver which may solve the problem
128
+ is ``"CRAMER"``. This method uses Cramer's rule to solve the system. This method
129
+ is slower and results in more operations than the default solver. However it only
130
+ uses a single division by default per entry of the solution.
131
+
132
+ While a valid list of solvers can be found at
133
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`, it is also possible to supply a
134
+ `callable`. This way it is possible to use a different solver routine. If the
135
+ kinematic differential equations are not too complex it can be worth it to simplify
136
+ the solution by using ``lambda A, b: simplify(Matrix.LUsolve(A, b))``. Another
137
+ option solver one may use is :func:`sympy.solvers.solveset.linsolve`. This can be
138
+ done using `lambda A, b: tuple(linsolve((A, b)))[0]`, where we select the first
139
+ solution as our system should have only one unique solution.
140
+
141
+ Examples
142
+ ========
143
+
144
+ This is a simple example for a one degree of freedom translational
145
+ spring-mass-damper.
146
+
147
+ In this example, we first need to do the kinematics.
148
+ This involves creating generalized speeds and coordinates and their
149
+ derivatives.
150
+ Then we create a point and set its velocity in a frame.
151
+
152
+ >>> from sympy import symbols
153
+ >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame
154
+ >>> from sympy.physics.mechanics import Point, Particle, KanesMethod
155
+ >>> q, u = dynamicsymbols('q u')
156
+ >>> qd, ud = dynamicsymbols('q u', 1)
157
+ >>> m, c, k = symbols('m c k')
158
+ >>> N = ReferenceFrame('N')
159
+ >>> P = Point('P')
160
+ >>> P.set_vel(N, u * N.x)
161
+
162
+ Next we need to arrange/store information in the way that KanesMethod
163
+ requires. The kinematic differential equations should be an iterable of
164
+ expressions. A list of forces/torques must be constructed, where each entry
165
+ in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where
166
+ the Vectors represent the Force or Torque.
167
+ Next a particle needs to be created, and it needs to have a point and mass
168
+ assigned to it.
169
+ Finally, a list of all bodies and particles needs to be created.
170
+
171
+ >>> kd = [qd - u]
172
+ >>> FL = [(P, (-k * q - c * u) * N.x)]
173
+ >>> pa = Particle('pa', P, m)
174
+ >>> BL = [pa]
175
+
176
+ Finally we can generate the equations of motion.
177
+ First we create the KanesMethod object and supply an inertial frame,
178
+ coordinates, generalized speeds, and the kinematic differential equations.
179
+ Additional quantities such as configuration and motion constraints,
180
+ dependent coordinates and speeds, and auxiliary speeds are also supplied
181
+ here (see the online documentation).
182
+ Next we form FR* and FR to complete: Fr + Fr* = 0.
183
+ We have the equations of motion at this point.
184
+ It makes sense to rearrange them though, so we calculate the mass matrix and
185
+ the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is
186
+ the mass matrix, udot is a vector of the time derivatives of the
187
+ generalized speeds, and forcing is a vector representing "forcing" terms.
188
+
189
+ >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd)
190
+ >>> (fr, frstar) = KM.kanes_equations(BL, FL)
191
+ >>> MM = KM.mass_matrix
192
+ >>> forcing = KM.forcing
193
+ >>> rhs = MM.inv() * forcing
194
+ >>> rhs
195
+ Matrix([[(-c*u(t) - k*q(t))/m]])
196
+ >>> KM.linearize(A_and_B=True)[0]
197
+ Matrix([
198
+ [ 0, 1],
199
+ [-k/m, -c/m]])
200
+
201
+ Please look at the documentation pages for more information on how to
202
+ perform linearization and how to deal with dependent coordinates & speeds,
203
+ and how do deal with bringing non-contributing forces into evidence.
204
+
205
+ """
206
+
207
+ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
208
+ configuration_constraints=None, u_dependent=None,
209
+ velocity_constraints=None, acceleration_constraints=None,
210
+ u_auxiliary=None, bodies=None, forcelist=None,
211
+ explicit_kinematics=True, kd_eqs_solver='LU',
212
+ constraint_solver='LU'):
213
+
214
+ """Please read the online documentation. """
215
+ if not q_ind:
216
+ q_ind = [dynamicsymbols('dummy_q')]
217
+ kd_eqs = [dynamicsymbols('dummy_kd')]
218
+
219
+ if not isinstance(frame, ReferenceFrame):
220
+ raise TypeError('An inertial ReferenceFrame must be supplied')
221
+ self._inertial = frame
222
+
223
+ self._fr = None
224
+ self._frstar = None
225
+
226
+ self._forcelist = forcelist
227
+ self._bodylist = bodies
228
+
229
+ self.explicit_kinematics = explicit_kinematics
230
+ self._constraint_solver = constraint_solver
231
+ self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
232
+ u_auxiliary)
233
+ _validate_coordinates(self.q, self.u)
234
+ self._initialize_kindiffeq_matrices(kd_eqs, kd_eqs_solver)
235
+ self._initialize_constraint_matrices(
236
+ configuration_constraints, velocity_constraints,
237
+ acceleration_constraints, constraint_solver)
238
+
239
+ def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
240
+ """Initialize the coordinate and speed vectors."""
241
+
242
+ none_handler = lambda x: Matrix(x) if x else Matrix()
243
+
244
+ # Initialize generalized coordinates
245
+ q_dep = none_handler(q_dep)
246
+ if not iterable(q_ind):
247
+ raise TypeError('Generalized coordinates must be an iterable.')
248
+ if not iterable(q_dep):
249
+ raise TypeError('Dependent coordinates must be an iterable.')
250
+ q_ind = Matrix(q_ind)
251
+ self._qdep = q_dep
252
+ self._q = Matrix([q_ind, q_dep])
253
+ self._qdot = self.q.diff(dynamicsymbols._t)
254
+
255
+ # Initialize generalized speeds
256
+ u_dep = none_handler(u_dep)
257
+ if not iterable(u_ind):
258
+ raise TypeError('Generalized speeds must be an iterable.')
259
+ if not iterable(u_dep):
260
+ raise TypeError('Dependent speeds must be an iterable.')
261
+ u_ind = Matrix(u_ind)
262
+ self._udep = u_dep
263
+ self._u = Matrix([u_ind, u_dep])
264
+ self._udot = self.u.diff(dynamicsymbols._t)
265
+ self._uaux = none_handler(u_aux)
266
+
267
+ def _initialize_constraint_matrices(self, config, vel, acc, linear_solver='LU'):
268
+ """Initializes constraint matrices."""
269
+ linear_solver = _parse_linear_solver(linear_solver)
270
+ # Define vector dimensions
271
+ o = len(self.u)
272
+ m = len(self._udep)
273
+ p = o - m
274
+ none_handler = lambda x: Matrix(x) if x else Matrix()
275
+
276
+ # Initialize configuration constraints
277
+ config = none_handler(config)
278
+ if len(self._qdep) != len(config):
279
+ raise ValueError('There must be an equal number of dependent '
280
+ 'coordinates and configuration constraints.')
281
+ self._f_h = none_handler(config)
282
+
283
+ # Initialize velocity and acceleration constraints
284
+ vel = none_handler(vel)
285
+ acc = none_handler(acc)
286
+ if len(vel) != m:
287
+ raise ValueError('There must be an equal number of dependent '
288
+ 'speeds and velocity constraints.')
289
+ if acc and (len(acc) != m):
290
+ raise ValueError('There must be an equal number of dependent '
291
+ 'speeds and acceleration constraints.')
292
+ if vel:
293
+ u_zero = dict.fromkeys(self.u, 0)
294
+ udot_zero = dict.fromkeys(self._udot, 0)
295
+
296
+ # When calling kanes_equations, another class instance will be
297
+ # created if auxiliary u's are present. In this case, the
298
+ # computation of kinetic differential equation matrices will be
299
+ # skipped as this was computed during the original KanesMethod
300
+ # object, and the qd_u_map will not be available.
301
+ if self._qdot_u_map is not None:
302
+ vel = msubs(vel, self._qdot_u_map)
303
+
304
+ self._f_nh = msubs(vel, u_zero)
305
+ self._k_nh = (vel - self._f_nh).jacobian(self.u)
306
+ # If no acceleration constraints given, calculate them.
307
+ if not acc:
308
+ _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u +
309
+ self._f_nh.diff(dynamicsymbols._t))
310
+ if self._qdot_u_map is not None:
311
+ _f_dnh = msubs(_f_dnh, self._qdot_u_map)
312
+ self._f_dnh = _f_dnh
313
+ self._k_dnh = self._k_nh
314
+ else:
315
+ if self._qdot_u_map is not None:
316
+ acc = msubs(acc, self._qdot_u_map)
317
+ self._f_dnh = msubs(acc, udot_zero)
318
+ self._k_dnh = (acc - self._f_dnh).jacobian(self._udot)
319
+
320
+ # Form of non-holonomic constraints is B*u + C = 0.
321
+ # We partition B into independent and dependent columns:
322
+ # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds
323
+ # to independent speeds as: udep = Ars*uind, neglecting the C term.
324
+ B_ind = self._k_nh[:, :p]
325
+ B_dep = self._k_nh[:, p:o]
326
+ self._Ars = -linear_solver(B_dep, B_ind)
327
+ else:
328
+ self._f_nh = Matrix()
329
+ self._k_nh = Matrix()
330
+ self._f_dnh = Matrix()
331
+ self._k_dnh = Matrix()
332
+ self._Ars = Matrix()
333
+
334
+ def _initialize_kindiffeq_matrices(self, kdeqs, linear_solver='LU'):
335
+ """Initialize the kinematic differential equation matrices.
336
+
337
+ Parameters
338
+ ==========
339
+ kdeqs : sequence of sympy expressions
340
+ Kinematic differential equations in the form of f(u,q',q,t) where
341
+ f() = 0. The equations have to be linear in the generalized
342
+ coordinates and generalized speeds.
343
+
344
+ """
345
+ linear_solver = _parse_linear_solver(linear_solver)
346
+ if kdeqs:
347
+ if len(self.q) != len(kdeqs):
348
+ raise ValueError('There must be an equal number of kinematic '
349
+ 'differential equations and coordinates.')
350
+
351
+ u = self.u
352
+ qdot = self._qdot
353
+
354
+ kdeqs = Matrix(kdeqs)
355
+
356
+ u_zero = dict.fromkeys(u, 0)
357
+ uaux_zero = dict.fromkeys(self._uaux, 0)
358
+ qdot_zero = dict.fromkeys(qdot, 0)
359
+
360
+ # Extract the linear coefficient matrices as per the following
361
+ # equation:
362
+ #
363
+ # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0
364
+ #
365
+ k_ku = kdeqs.jacobian(u)
366
+ k_kqdot = kdeqs.jacobian(qdot)
367
+ f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero)
368
+
369
+ # The kinematic differential equations should be linear in both q'
370
+ # and u, so check for u and q' in the components.
371
+ dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k))
372
+ nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms]
373
+ if nonlin_vars:
374
+ msg = ('The provided kinematic differential equations are '
375
+ 'nonlinear in {}. They must be linear in the '
376
+ 'generalized speeds and derivatives of the generalized '
377
+ 'coordinates.')
378
+ raise ValueError(msg.format(nonlin_vars))
379
+
380
+ self._f_k_implicit = f_k.xreplace(uaux_zero)
381
+ self._k_ku_implicit = k_ku.xreplace(uaux_zero)
382
+ self._k_kqdot_implicit = k_kqdot
383
+
384
+ # Solve for q'(t) such that the coefficient matrices are now in
385
+ # this form:
386
+ #
387
+ # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0
388
+ #
389
+ # NOTE : Solving the kinematic differential equations here is not
390
+ # necessary and prevents the equations from being provided in fully
391
+ # implicit form.
392
+ f_k_explicit = linear_solver(k_kqdot, f_k)
393
+ k_ku_explicit = linear_solver(k_kqdot, k_ku)
394
+ self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit)))
395
+
396
+ self._f_k = f_k_explicit.xreplace(uaux_zero)
397
+ self._k_ku = k_ku_explicit.xreplace(uaux_zero)
398
+ self._k_kqdot = eye(len(qdot))
399
+
400
+ else:
401
+ self._qdot_u_map = None
402
+ self._f_k_implicit = self._f_k = Matrix()
403
+ self._k_ku_implicit = self._k_ku = Matrix()
404
+ self._k_kqdot_implicit = self._k_kqdot = Matrix()
405
+
406
+ def _form_fr(self, fl):
407
+ """Form the generalized active force."""
408
+ if fl is not None and (len(fl) == 0 or not iterable(fl)):
409
+ raise ValueError('Force pairs must be supplied in an '
410
+ 'non-empty iterable or None.')
411
+
412
+ N = self._inertial
413
+ # pull out relevant velocities for constructing partial velocities
414
+ vel_list, f_list = _f_list_parser(fl, N)
415
+ vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
416
+ f_list = [msubs(i, self._qdot_u_map) for i in f_list]
417
+
418
+ # Fill Fr with dot product of partial velocities and forces
419
+ o = len(self.u)
420
+ b = len(f_list)
421
+ FR = zeros(o, 1)
422
+ partials = partial_velocity(vel_list, self.u, N)
423
+ for i in range(o):
424
+ FR[i] = sum(partials[j][i].dot(f_list[j]) for j in range(b))
425
+
426
+ # In case there are dependent speeds
427
+ if self._udep:
428
+ p = o - len(self._udep)
429
+ FRtilde = FR[:p, 0]
430
+ FRold = FR[p:o, 0]
431
+ FRtilde += self._Ars.T * FRold
432
+ FR = FRtilde
433
+
434
+ self._forcelist = fl
435
+ self._fr = FR
436
+ return FR
437
+
438
+ def _form_frstar(self, bl):
439
+ """Form the generalized inertia force."""
440
+
441
+ if not iterable(bl):
442
+ raise TypeError('Bodies must be supplied in an iterable.')
443
+
444
+ t = dynamicsymbols._t
445
+ N = self._inertial
446
+ # Dicts setting things to zero
447
+ udot_zero = dict.fromkeys(self._udot, 0)
448
+ uaux_zero = dict.fromkeys(self._uaux, 0)
449
+ uauxdot = [diff(i, t) for i in self._uaux]
450
+ uauxdot_zero = dict.fromkeys(uauxdot, 0)
451
+ # Dictionary of q' and q'' to u and u'
452
+ q_ddot_u_map = {k.diff(t): v.diff(t).xreplace(
453
+ self._qdot_u_map) for (k, v) in self._qdot_u_map.items()}
454
+ q_ddot_u_map.update(self._qdot_u_map)
455
+
456
+ # Fill up the list of partials: format is a list with num elements
457
+ # equal to number of entries in body list. Each of these elements is a
458
+ # list - either of length 1 for the translational components of
459
+ # particles or of length 2 for the translational and rotational
460
+ # components of rigid bodies. The inner most list is the list of
461
+ # partial velocities.
462
+ def get_partial_velocity(body):
463
+ if isinstance(body, RigidBody):
464
+ vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)]
465
+ elif isinstance(body, Particle):
466
+ vlist = [body.point.vel(N),]
467
+ else:
468
+ raise TypeError('The body list may only contain either '
469
+ 'RigidBody or Particle as list elements.')
470
+ v = [msubs(vel, self._qdot_u_map) for vel in vlist]
471
+ return partial_velocity(v, self.u, N)
472
+ partials = [get_partial_velocity(body) for body in bl]
473
+
474
+ # Compute fr_star in two components:
475
+ # fr_star = -(MM*u' + nonMM)
476
+ o = len(self.u)
477
+ MM = zeros(o, o)
478
+ nonMM = zeros(o, 1)
479
+ zero_uaux = lambda expr: msubs(expr, uaux_zero)
480
+ zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero)
481
+ for i, body in enumerate(bl):
482
+ if isinstance(body, RigidBody):
483
+ M = zero_uaux(body.mass)
484
+ I = zero_uaux(body.central_inertia)
485
+ vel = zero_uaux(body.masscenter.vel(N))
486
+ omega = zero_uaux(body.frame.ang_vel_in(N))
487
+ acc = zero_udot_uaux(body.masscenter.acc(N))
488
+ inertial_force = (M.diff(t) * vel + M * acc)
489
+ inertial_torque = zero_uaux((I.dt(body.frame).dot(omega)) +
490
+ msubs(I.dot(body.frame.ang_acc_in(N)), udot_zero) +
491
+ (omega.cross(I.dot(omega))))
492
+ for j in range(o):
493
+ tmp_vel = zero_uaux(partials[i][0][j])
494
+ tmp_ang = zero_uaux(I.dot(partials[i][1][j]))
495
+ for k in range(o):
496
+ # translational
497
+ MM[j, k] += M*tmp_vel.dot(partials[i][0][k])
498
+ # rotational
499
+ MM[j, k] += tmp_ang.dot(partials[i][1][k])
500
+ nonMM[j] += inertial_force.dot(partials[i][0][j])
501
+ nonMM[j] += inertial_torque.dot(partials[i][1][j])
502
+ else:
503
+ M = zero_uaux(body.mass)
504
+ vel = zero_uaux(body.point.vel(N))
505
+ acc = zero_udot_uaux(body.point.acc(N))
506
+ inertial_force = (M.diff(t) * vel + M * acc)
507
+ for j in range(o):
508
+ temp = zero_uaux(partials[i][0][j])
509
+ for k in range(o):
510
+ MM[j, k] += M*temp.dot(partials[i][0][k])
511
+ nonMM[j] += inertial_force.dot(partials[i][0][j])
512
+ # Compose fr_star out of MM and nonMM
513
+ MM = zero_uaux(msubs(MM, q_ddot_u_map))
514
+ nonMM = msubs(msubs(nonMM, q_ddot_u_map),
515
+ udot_zero, uauxdot_zero, uaux_zero)
516
+ fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM)
517
+
518
+ # If there are dependent speeds, we need to find fr_star_tilde
519
+ if self._udep:
520
+ p = o - len(self._udep)
521
+ fr_star_ind = fr_star[:p, 0]
522
+ fr_star_dep = fr_star[p:o, 0]
523
+ fr_star = fr_star_ind + (self._Ars.T * fr_star_dep)
524
+ # Apply the same to MM
525
+ MMi = MM[:p, :]
526
+ MMd = MM[p:o, :]
527
+ MM = MMi + (self._Ars.T * MMd)
528
+ # Apply the same to nonMM
529
+ nonMM = nonMM[:p, :] + (self._Ars.T * nonMM[p:o, :])
530
+
531
+ self._bodylist = bl
532
+ self._frstar = fr_star
533
+ self._k_d = MM
534
+ self._f_d = -(self._fr - nonMM)
535
+ return fr_star
536
+
537
+ def to_linearizer(self, linear_solver='LU'):
538
+ """Returns an instance of the Linearizer class, initiated from the
539
+ data in the KanesMethod class. This may be more desirable than using
540
+ the linearize class method, as the Linearizer object will allow more
541
+ efficient recalculation (i.e. about varying operating points).
542
+
543
+ Parameters
544
+ ==========
545
+ linear_solver : str, callable
546
+ Method used to solve the several symbolic linear systems of the
547
+ form ``A*x=b`` in the linearization process. If a string is
548
+ supplied, it should be a valid method that can be used with the
549
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
550
+ supplied, it should have the format ``x = f(A, b)``, where it
551
+ solves the equations and returns the solution. The default is
552
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
553
+ ``LUsolve()`` is fast to compute but will often result in
554
+ divide-by-zero and thus ``nan`` results.
555
+
556
+ Returns
557
+ =======
558
+ Linearizer
559
+ An instantiated
560
+ :class:`sympy.physics.mechanics.linearize.Linearizer`.
561
+
562
+ """
563
+
564
+ if (self._fr is None) or (self._frstar is None):
565
+ raise ValueError('Need to compute Fr, Fr* first.')
566
+
567
+ # Get required equation components. The Kane's method class breaks
568
+ # these into pieces. Need to reassemble
569
+ f_c = self._f_h
570
+ if self._f_nh and self._k_nh:
571
+ f_v = self._f_nh + self._k_nh*Matrix(self.u)
572
+ else:
573
+ f_v = Matrix()
574
+ if self._f_dnh and self._k_dnh:
575
+ f_a = self._f_dnh + self._k_dnh*Matrix(self._udot)
576
+ else:
577
+ f_a = Matrix()
578
+ # Dicts to sub to zero, for splitting up expressions
579
+ u_zero = dict.fromkeys(self.u, 0)
580
+ ud_zero = dict.fromkeys(self._udot, 0)
581
+ qd_zero = dict.fromkeys(self._qdot, 0)
582
+ qd_u_zero = dict.fromkeys(Matrix([self._qdot, self.u]), 0)
583
+ # Break the kinematic differential eqs apart into f_0 and f_1
584
+ f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot)
585
+ f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u)
586
+ # Break the dynamic differential eqs into f_2 and f_3
587
+ f_2 = msubs(self._frstar, qd_u_zero)
588
+ f_3 = msubs(self._frstar, ud_zero) + self._fr
589
+ f_4 = zeros(len(f_2), 1)
590
+
591
+ # Get the required vector components
592
+ q = self.q
593
+ u = self.u
594
+ if self._qdep:
595
+ q_i = q[:-len(self._qdep)]
596
+ else:
597
+ q_i = q
598
+ q_d = self._qdep
599
+ if self._udep:
600
+ u_i = u[:-len(self._udep)]
601
+ else:
602
+ u_i = u
603
+ u_d = self._udep
604
+
605
+ # Form dictionary to set auxiliary speeds & their derivatives to 0.
606
+ uaux = self._uaux
607
+ uauxdot = uaux.diff(dynamicsymbols._t)
608
+ uaux_zero = dict.fromkeys(Matrix([uaux, uauxdot]), 0)
609
+
610
+ # Checking for dynamic symbols outside the dynamic differential
611
+ # equations; throws error if there is.
612
+ sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot]))
613
+ if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot,
614
+ self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]):
615
+ raise ValueError('Cannot have dynamicsymbols outside dynamic \
616
+ forcing vector.')
617
+
618
+ # Find all other dynamic symbols, forming the forcing vector r.
619
+ # Sort r to make it canonical.
620
+ r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list))
621
+ r.sort(key=default_sort_key)
622
+
623
+ # Check for any derivatives of variables in r that are also found in r.
624
+ for i in r:
625
+ if diff(i, dynamicsymbols._t) in r:
626
+ raise ValueError('Cannot have derivatives of specified \
627
+ quantities when linearizing forcing terms.')
628
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
629
+ q_d, u_i, u_d, r, linear_solver=linear_solver)
630
+
631
+ # TODO : Remove `new_method` after 1.1 has been released.
632
+ def linearize(self, *, new_method=None, linear_solver='LU', **kwargs):
633
+ """ Linearize the equations of motion about a symbolic operating point.
634
+
635
+ Parameters
636
+ ==========
637
+ new_method
638
+ Deprecated, does nothing and will be removed.
639
+ linear_solver : str, callable
640
+ Method used to solve the several symbolic linear systems of the
641
+ form ``A*x=b`` in the linearization process. If a string is
642
+ supplied, it should be a valid method that can be used with the
643
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
644
+ supplied, it should have the format ``x = f(A, b)``, where it
645
+ solves the equations and returns the solution. The default is
646
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
647
+ ``LUsolve()`` is fast to compute but will often result in
648
+ divide-by-zero and thus ``nan`` results.
649
+ **kwargs
650
+ Extra keyword arguments are passed to
651
+ :meth:`sympy.physics.mechanics.linearize.Linearizer.linearize`.
652
+
653
+ Explanation
654
+ ===========
655
+
656
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
657
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
658
+
659
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
660
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
661
+ computationally intensive if there are many symbolic parameters. For
662
+ this reason, it may be more desirable to use the default A_and_B=False,
663
+ returning M, A, and B. Values may then be substituted in to these
664
+ matrices, and the state space form found as
665
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
666
+
667
+ In both cases, r is found as all dynamicsymbols in the equations of
668
+ motion that are not part of q, u, q', or u'. They are sorted in
669
+ canonical form.
670
+
671
+ The operating points may be also entered using the ``op_point`` kwarg.
672
+ This takes a dictionary of {symbol: value}, or a an iterable of such
673
+ dictionaries. The values may be numeric or symbolic. The more values
674
+ you can specify beforehand, the faster this computation will run.
675
+
676
+ For more documentation, please see the ``Linearizer`` class.
677
+
678
+ """
679
+
680
+ linearizer = self.to_linearizer(linear_solver=linear_solver)
681
+ result = linearizer.linearize(**kwargs)
682
+ return result + (linearizer.r,)
683
+
684
+ def kanes_equations(self, bodies=None, loads=None):
685
+ """ Method to form Kane's equations, Fr + Fr* = 0.
686
+
687
+ Explanation
688
+ ===========
689
+
690
+ Returns (Fr, Fr*). In the case where auxiliary generalized speeds are
691
+ present (say, s auxiliary speeds, o generalized speeds, and m motion
692
+ constraints) the length of the returned vectors will be o - m + s in
693
+ length. The first o - m equations will be the constrained Kane's
694
+ equations, then the s auxiliary Kane's equations. These auxiliary
695
+ equations can be accessed with the auxiliary_eqs property.
696
+
697
+ Parameters
698
+ ==========
699
+
700
+ bodies : iterable
701
+ An iterable of all RigidBody's and Particle's in the system.
702
+ A system must have at least one body.
703
+ loads : iterable
704
+ Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector)
705
+ tuples which represent the force at a point or torque on a frame.
706
+ Must be either a non-empty iterable of tuples or None which corresponds
707
+ to a system with no constraints.
708
+ """
709
+ if bodies is None:
710
+ bodies = self.bodies
711
+ if loads is None and self._forcelist is not None:
712
+ loads = self._forcelist
713
+ if loads == []:
714
+ loads = None
715
+ if not self._k_kqdot:
716
+ raise AttributeError('Create an instance of KanesMethod with '
717
+ 'kinematic differential equations to use this method.')
718
+ fr = self._form_fr(loads)
719
+ frstar = self._form_frstar(bodies)
720
+ if self._uaux:
721
+ if not self._udep:
722
+ km = KanesMethod(self._inertial, self.q, self._uaux,
723
+ u_auxiliary=self._uaux, constraint_solver=self._constraint_solver)
724
+ else:
725
+ km = KanesMethod(self._inertial, self.q, self._uaux,
726
+ u_auxiliary=self._uaux, u_dependent=self._udep,
727
+ velocity_constraints=(self._k_nh * self.u +
728
+ self._f_nh),
729
+ acceleration_constraints=(self._k_dnh * self._udot +
730
+ self._f_dnh),
731
+ constraint_solver=self._constraint_solver
732
+ )
733
+ km._qdot_u_map = self._qdot_u_map
734
+ self._km = km
735
+ fraux = km._form_fr(loads)
736
+ frstaraux = km._form_frstar(bodies)
737
+ self._aux_eq = fraux + frstaraux
738
+ self._fr = fr.col_join(fraux)
739
+ self._frstar = frstar.col_join(frstaraux)
740
+ return (self._fr, self._frstar)
741
+
742
+ def _form_eoms(self):
743
+ fr, frstar = self.kanes_equations(self.bodylist, self.forcelist)
744
+ return fr + frstar
745
+
746
+ def rhs(self, inv_method=None):
747
+ """Returns the system's equations of motion in first order form. The
748
+ output is the right hand side of::
749
+
750
+ x' = |q'| =: f(q, u, r, p, t)
751
+ |u'|
752
+
753
+ The right hand side is what is needed by most numerical ODE
754
+ integrators.
755
+
756
+ Parameters
757
+ ==========
758
+
759
+ inv_method : str
760
+ The specific sympy inverse matrix calculation method to use. For a
761
+ list of valid methods, see
762
+ :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
763
+
764
+ """
765
+ rhs = zeros(len(self.q) + len(self.u), 1)
766
+ kdes = self.kindiffdict()
767
+ for i, q_i in enumerate(self.q):
768
+ rhs[i] = kdes[q_i.diff()]
769
+
770
+ if inv_method is None:
771
+ rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing)
772
+ else:
773
+ rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method,
774
+ try_block_diag=True) *
775
+ self.forcing)
776
+
777
+ return rhs
778
+
779
+ def kindiffdict(self):
780
+ """Returns a dictionary mapping q' to u."""
781
+ if not self._qdot_u_map:
782
+ raise AttributeError('Create an instance of KanesMethod with '
783
+ 'kinematic differential equations to use this method.')
784
+ return self._qdot_u_map
785
+
786
+ @property
787
+ def auxiliary_eqs(self):
788
+ """A matrix containing the auxiliary equations."""
789
+ if not self._fr or not self._frstar:
790
+ raise ValueError('Need to compute Fr, Fr* first.')
791
+ if not self._uaux:
792
+ raise ValueError('No auxiliary speeds have been declared.')
793
+ return self._aux_eq
794
+
795
+ @property
796
+ def mass_matrix_kin(self):
797
+ r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system."""
798
+ return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit
799
+
800
+ @property
801
+ def forcing_kin(self):
802
+ """The kinematic "forcing vector" of the system."""
803
+ if self.explicit_kinematics:
804
+ return -(self._k_ku * Matrix(self.u) + self._f_k)
805
+ else:
806
+ return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit)
807
+
808
+ @property
809
+ def mass_matrix(self):
810
+ """The mass matrix of the system."""
811
+ if not self._fr or not self._frstar:
812
+ raise ValueError('Need to compute Fr, Fr* first.')
813
+ return Matrix([self._k_d, self._k_dnh])
814
+
815
+ @property
816
+ def forcing(self):
817
+ """The forcing vector of the system."""
818
+ if not self._fr or not self._frstar:
819
+ raise ValueError('Need to compute Fr, Fr* first.')
820
+ return -Matrix([self._f_d, self._f_dnh])
821
+
822
+ @property
823
+ def mass_matrix_full(self):
824
+ """The mass matrix of the system, augmented by the kinematic
825
+ differential equations in explicit or implicit form."""
826
+ if not self._fr or not self._frstar:
827
+ raise ValueError('Need to compute Fr, Fr* first.')
828
+ o, n = len(self.u), len(self.q)
829
+ return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join(
830
+ zeros(o, n).row_join(self.mass_matrix))
831
+
832
+ @property
833
+ def forcing_full(self):
834
+ """The forcing vector of the system, augmented by the kinematic
835
+ differential equations in explicit or implicit form."""
836
+ return Matrix([self.forcing_kin, self.forcing])
837
+
838
+ @property
839
+ def q(self):
840
+ return self._q
841
+
842
+ @property
843
+ def u(self):
844
+ return self._u
845
+
846
+ @property
847
+ def bodylist(self):
848
+ return self._bodylist
849
+
850
+ @property
851
+ def forcelist(self):
852
+ return self._forcelist
853
+
854
+ @property
855
+ def bodies(self):
856
+ return self._bodylist
857
+
858
+ @property
859
+ def loads(self):
860
+ return self._forcelist
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['Linearizer']
2
+
3
+ from sympy import Matrix, eye, zeros
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.utilities.iterables import flatten
6
+ from sympy.physics.vector import dynamicsymbols
7
+ from sympy.physics.mechanics.functions import msubs, _parse_linear_solver
8
+
9
+ from collections import namedtuple
10
+ from collections.abc import Iterable
11
+
12
+
13
+ class Linearizer:
14
+ """This object holds the general model form for a dynamic system. This
15
+ model is used for computing the linearized form of the system, while
16
+ properly dealing with constraints leading to dependent coordinates and
17
+ speeds. The notation and method is described in [1]_.
18
+
19
+ Attributes
20
+ ==========
21
+
22
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
23
+ Matrices holding the general system form.
24
+ q, u, r : Matrix
25
+ Matrices holding the generalized coordinates, speeds, and
26
+ input vectors.
27
+ q_i, u_i : Matrix
28
+ Matrices of the independent generalized coordinates and speeds.
29
+ q_d, u_d : Matrix
30
+ Matrices of the dependent generalized coordinates and speeds.
31
+ perm_mat : Matrix
32
+ Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
33
+
34
+ References
35
+ ==========
36
+
37
+ .. [1] D. L. Peterson, G. Gede, and M. Hubbard, "Symbolic linearization of
38
+ equations of motion of constrained multibody systems," Multibody
39
+ Syst Dyn, vol. 33, no. 2, pp. 143-161, Feb. 2015, doi:
40
+ 10.1007/s11044-014-9436-5.
41
+
42
+ """
43
+
44
+ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None,
45
+ q_d=None, u_i=None, u_d=None, r=None, lams=None,
46
+ linear_solver='LU'):
47
+ """
48
+ Parameters
49
+ ==========
50
+
51
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
52
+ System of equations holding the general system form.
53
+ Supply empty array or Matrix if the parameter
54
+ does not exist.
55
+ q : array_like
56
+ The generalized coordinates.
57
+ u : array_like
58
+ The generalized speeds
59
+ q_i, u_i : array_like, optional
60
+ The independent generalized coordinates and speeds.
61
+ q_d, u_d : array_like, optional
62
+ The dependent generalized coordinates and speeds.
63
+ r : array_like, optional
64
+ The input variables.
65
+ lams : array_like, optional
66
+ The lagrange multipliers
67
+ linear_solver : str, callable
68
+ Method used to solve the several symbolic linear systems of the
69
+ form ``A*x=b`` in the linearization process. If a string is
70
+ supplied, it should be a valid method that can be used with the
71
+ :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
72
+ supplied, it should have the format ``x = f(A, b)``, where it
73
+ solves the equations and returns the solution. The default is
74
+ ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
75
+ ``LUsolve()`` is fast to compute but will often result in
76
+ divide-by-zero and thus ``nan`` results.
77
+
78
+ """
79
+ self.linear_solver = _parse_linear_solver(linear_solver)
80
+
81
+ # Generalized equation form
82
+ self.f_0 = Matrix(f_0)
83
+ self.f_1 = Matrix(f_1)
84
+ self.f_2 = Matrix(f_2)
85
+ self.f_3 = Matrix(f_3)
86
+ self.f_4 = Matrix(f_4)
87
+ self.f_c = Matrix(f_c)
88
+ self.f_v = Matrix(f_v)
89
+ self.f_a = Matrix(f_a)
90
+
91
+ # Generalized equation variables
92
+ self.q = Matrix(q)
93
+ self.u = Matrix(u)
94
+ none_handler = lambda x: Matrix(x) if x else Matrix()
95
+ self.q_i = none_handler(q_i)
96
+ self.q_d = none_handler(q_d)
97
+ self.u_i = none_handler(u_i)
98
+ self.u_d = none_handler(u_d)
99
+ self.r = none_handler(r)
100
+ self.lams = none_handler(lams)
101
+
102
+ # Derivatives of generalized equation variables
103
+ self._qd = self.q.diff(dynamicsymbols._t)
104
+ self._ud = self.u.diff(dynamicsymbols._t)
105
+ # If the user doesn't actually use generalized variables, and the
106
+ # qd and u vectors have any intersecting variables, this can cause
107
+ # problems. We'll fix this with some hackery, and Dummy variables
108
+ dup_vars = set(self._qd).intersection(self.u)
109
+ self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var
110
+ in self._qd])
111
+
112
+ # Derive dimesion terms
113
+ l = len(self.f_c)
114
+ m = len(self.f_v)
115
+ n = len(self.q)
116
+ o = len(self.u)
117
+ s = len(self.r)
118
+ k = len(self.lams)
119
+ dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
120
+ self._dims = dims(l, m, n, o, s, k)
121
+
122
+ self._Pq = None
123
+ self._Pqi = None
124
+ self._Pqd = None
125
+ self._Pu = None
126
+ self._Pui = None
127
+ self._Pud = None
128
+ self._C_0 = None
129
+ self._C_1 = None
130
+ self._C_2 = None
131
+ self.perm_mat = None
132
+
133
+ self._setup_done = False
134
+
135
+ def _setup(self):
136
+ # Calculations here only need to be run once. They are moved out of
137
+ # the __init__ method to increase the speed of Linearizer creation.
138
+ self._form_permutation_matrices()
139
+ self._form_block_matrices()
140
+ self._form_coefficient_matrices()
141
+ self._setup_done = True
142
+
143
+ def _form_permutation_matrices(self):
144
+ """Form the permutation matrices Pq and Pu."""
145
+
146
+ # Extract dimension variables
147
+ l, m, n, o, s, k = self._dims
148
+ # Compute permutation matrices
149
+ if n != 0:
150
+ self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
151
+ if l > 0:
152
+ self._Pqi = self._Pq[:, :-l]
153
+ self._Pqd = self._Pq[:, -l:]
154
+ else:
155
+ self._Pqi = self._Pq
156
+ self._Pqd = Matrix()
157
+ if o != 0:
158
+ self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
159
+ if m > 0:
160
+ self._Pui = self._Pu[:, :-m]
161
+ self._Pud = self._Pu[:, -m:]
162
+ else:
163
+ self._Pui = self._Pu
164
+ self._Pud = Matrix()
165
+ # Compute combination permutation matrix for computing A and B
166
+ P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
167
+ P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
168
+ if P_col1:
169
+ if P_col2:
170
+ self.perm_mat = P_col1.row_join(P_col2)
171
+ else:
172
+ self.perm_mat = P_col1
173
+ else:
174
+ self.perm_mat = P_col2
175
+
176
+ def _form_coefficient_matrices(self):
177
+ """Form the coefficient matrices C_0, C_1, and C_2."""
178
+
179
+ # Extract dimension variables
180
+ l, m, n, o, s, k = self._dims
181
+ # Build up the coefficient matrices C_0, C_1, and C_2
182
+ # If there are configuration constraints (l > 0), form C_0 as normal.
183
+ # If not, C_0 is I_(nxn). Note that this works even if n=0
184
+ if l > 0:
185
+ f_c_jac_q = self.f_c.jacobian(self.q)
186
+ self._C_0 = (eye(n) - self._Pqd *
187
+ self.linear_solver(f_c_jac_q*self._Pqd,
188
+ f_c_jac_q))*self._Pqi
189
+ else:
190
+ self._C_0 = eye(n)
191
+ # If there are motion constraints (m > 0), form C_1 and C_2 as normal.
192
+ # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
193
+ # o = 0.
194
+ if m > 0:
195
+ f_v_jac_u = self.f_v.jacobian(self.u)
196
+ temp = f_v_jac_u * self._Pud
197
+ if n != 0:
198
+ f_v_jac_q = self.f_v.jacobian(self.q)
199
+ self._C_1 = -self._Pud * self.linear_solver(temp, f_v_jac_q)
200
+ else:
201
+ self._C_1 = zeros(o, n)
202
+ self._C_2 = (eye(o) - self._Pud *
203
+ self.linear_solver(temp, f_v_jac_u))*self._Pui
204
+ else:
205
+ self._C_1 = zeros(o, n)
206
+ self._C_2 = eye(o)
207
+
208
+ def _form_block_matrices(self):
209
+ """Form the block matrices for composing M, A, and B."""
210
+
211
+ # Extract dimension variables
212
+ l, m, n, o, s, k = self._dims
213
+ # Block Matrix Definitions. These are only defined if under certain
214
+ # conditions. If undefined, an empty matrix is used instead
215
+ if n != 0:
216
+ self._M_qq = self.f_0.jacobian(self._qd)
217
+ self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
218
+ else:
219
+ self._M_qq = Matrix()
220
+ self._A_qq = Matrix()
221
+ if n != 0 and m != 0:
222
+ self._M_uqc = self.f_a.jacobian(self._qd_dup)
223
+ self._A_uqc = -self.f_a.jacobian(self.q)
224
+ else:
225
+ self._M_uqc = Matrix()
226
+ self._A_uqc = Matrix()
227
+ if n != 0 and o - m + k != 0:
228
+ self._M_uqd = self.f_3.jacobian(self._qd_dup)
229
+ self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
230
+ else:
231
+ self._M_uqd = Matrix()
232
+ self._A_uqd = Matrix()
233
+ if o != 0 and m != 0:
234
+ self._M_uuc = self.f_a.jacobian(self._ud)
235
+ self._A_uuc = -self.f_a.jacobian(self.u)
236
+ else:
237
+ self._M_uuc = Matrix()
238
+ self._A_uuc = Matrix()
239
+ if o != 0 and o - m + k != 0:
240
+ self._M_uud = self.f_2.jacobian(self._ud)
241
+ self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
242
+ else:
243
+ self._M_uud = Matrix()
244
+ self._A_uud = Matrix()
245
+ if o != 0 and n != 0:
246
+ self._A_qu = -self.f_1.jacobian(self.u)
247
+ else:
248
+ self._A_qu = Matrix()
249
+ if k != 0 and o - m + k != 0:
250
+ self._M_uld = self.f_4.jacobian(self.lams)
251
+ else:
252
+ self._M_uld = Matrix()
253
+ if s != 0 and o - m + k != 0:
254
+ self._B_u = -self.f_3.jacobian(self.r)
255
+ else:
256
+ self._B_u = Matrix()
257
+
258
+ def linearize(self, op_point=None, A_and_B=False, simplify=False):
259
+ """Linearize the system about the operating point. Note that
260
+ q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
261
+ These may be either symbolic or numeric.
262
+
263
+ Parameters
264
+ ==========
265
+ op_point : dict or iterable of dicts, optional
266
+ Dictionary or iterable of dictionaries containing the operating
267
+ point conditions for all or a subset of the generalized
268
+ coordinates, generalized speeds, and time derivatives of the
269
+ generalized speeds. These will be substituted into the linearized
270
+ system before the linearization is complete. Leave set to ``None``
271
+ if you want the operating point to be an arbitrary set of symbols.
272
+ Note that any reduction in symbols (whether substituted for numbers
273
+ or expressions with a common parameter) will result in faster
274
+ runtime.
275
+ A_and_B : bool, optional
276
+ If A_and_B=False (default), (M, A, B) is returned and of
277
+ A_and_B=True, (A, B) is returned. See below.
278
+ simplify : bool, optional
279
+ Determines if returned values are simplified before return.
280
+ For large expressions this may be time consuming. Default is False.
281
+
282
+ Returns
283
+ =======
284
+ M, A, B : Matrices, ``A_and_B=False``
285
+ Matrices from the implicit form:
286
+ ``[M]*[q', u']^T = [A]*[q_ind, u_ind]^T + [B]*r``
287
+ A, B : Matrices, ``A_and_B=True``
288
+ Matrices from the explicit form:
289
+ ``[q_ind', u_ind']^T = [A]*[q_ind, u_ind]^T + [B]*r``
290
+
291
+ Notes
292
+ =====
293
+
294
+ Note that the process of solving with A_and_B=True is computationally
295
+ intensive if there are many symbolic parameters. For this reason, it
296
+ may be more desirable to use the default A_and_B=False, returning M, A,
297
+ and B. More values may then be substituted in to these matrices later
298
+ on. The state space form can then be found as A = P.T*M.LUsolve(A), B =
299
+ P.T*M.LUsolve(B), where P = Linearizer.perm_mat.
300
+
301
+ """
302
+
303
+ # Run the setup if needed:
304
+ if not self._setup_done:
305
+ self._setup()
306
+
307
+ # Compose dict of operating conditions
308
+ if isinstance(op_point, dict):
309
+ op_point_dict = op_point
310
+ elif isinstance(op_point, Iterable):
311
+ op_point_dict = {}
312
+ for op in op_point:
313
+ op_point_dict.update(op)
314
+ else:
315
+ op_point_dict = {}
316
+
317
+ # Extract dimension variables
318
+ l, m, n, o, s, k = self._dims
319
+
320
+ # Rename terms to shorten expressions
321
+ M_qq = self._M_qq
322
+ M_uqc = self._M_uqc
323
+ M_uqd = self._M_uqd
324
+ M_uuc = self._M_uuc
325
+ M_uud = self._M_uud
326
+ M_uld = self._M_uld
327
+ A_qq = self._A_qq
328
+ A_uqc = self._A_uqc
329
+ A_uqd = self._A_uqd
330
+ A_qu = self._A_qu
331
+ A_uuc = self._A_uuc
332
+ A_uud = self._A_uud
333
+ B_u = self._B_u
334
+ C_0 = self._C_0
335
+ C_1 = self._C_1
336
+ C_2 = self._C_2
337
+
338
+ # Build up Mass Matrix
339
+ # |M_qq 0_nxo 0_nxk|
340
+ # M = |M_uqc M_uuc 0_mxk|
341
+ # |M_uqd M_uud M_uld|
342
+ if o != 0:
343
+ col2 = Matrix([zeros(n, o), M_uuc, M_uud])
344
+ if k != 0:
345
+ col3 = Matrix([zeros(n + m, k), M_uld])
346
+ if n != 0:
347
+ col1 = Matrix([M_qq, M_uqc, M_uqd])
348
+ if o != 0 and k != 0:
349
+ M = col1.row_join(col2).row_join(col3)
350
+ elif o != 0:
351
+ M = col1.row_join(col2)
352
+ else:
353
+ M = col1
354
+ elif k != 0:
355
+ M = col2.row_join(col3)
356
+ else:
357
+ M = col2
358
+ M_eq = msubs(M, op_point_dict)
359
+
360
+ # Build up state coefficient matrix A
361
+ # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
362
+ # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
363
+ # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
364
+ # Col 1 is only defined if n != 0
365
+ if n != 0:
366
+ r1c1 = A_qq
367
+ if o != 0:
368
+ r1c1 += (A_qu * C_1)
369
+ r1c1 = r1c1 * C_0
370
+ if m != 0:
371
+ r2c1 = A_uqc
372
+ if o != 0:
373
+ r2c1 += (A_uuc * C_1)
374
+ r2c1 = r2c1 * C_0
375
+ else:
376
+ r2c1 = Matrix()
377
+ if o - m + k != 0:
378
+ r3c1 = A_uqd
379
+ if o != 0:
380
+ r3c1 += (A_uud * C_1)
381
+ r3c1 = r3c1 * C_0
382
+ else:
383
+ r3c1 = Matrix()
384
+ col1 = Matrix([r1c1, r2c1, r3c1])
385
+ else:
386
+ col1 = Matrix()
387
+ # Col 2 is only defined if o != 0
388
+ if o != 0:
389
+ if n != 0:
390
+ r1c2 = A_qu * C_2
391
+ else:
392
+ r1c2 = Matrix()
393
+ if m != 0:
394
+ r2c2 = A_uuc * C_2
395
+ else:
396
+ r2c2 = Matrix()
397
+ if o - m + k != 0:
398
+ r3c2 = A_uud * C_2
399
+ else:
400
+ r3c2 = Matrix()
401
+ col2 = Matrix([r1c2, r2c2, r3c2])
402
+ else:
403
+ col2 = Matrix()
404
+ if col1:
405
+ if col2:
406
+ Amat = col1.row_join(col2)
407
+ else:
408
+ Amat = col1
409
+ else:
410
+ Amat = col2
411
+ Amat_eq = msubs(Amat, op_point_dict)
412
+
413
+ # Build up the B matrix if there are forcing variables
414
+ # |0_(n + m)xs|
415
+ # B = |B_u |
416
+ if s != 0 and o - m + k != 0:
417
+ Bmat = zeros(n + m, s).col_join(B_u)
418
+ Bmat_eq = msubs(Bmat, op_point_dict)
419
+ else:
420
+ Bmat_eq = Matrix()
421
+
422
+ # kwarg A_and_B indicates to return A, B for forming the equation
423
+ # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
424
+ if A_and_B:
425
+ A_cont = self.perm_mat.T * self.linear_solver(M_eq, Amat_eq)
426
+ if Bmat_eq:
427
+ B_cont = self.perm_mat.T * self.linear_solver(M_eq, Bmat_eq)
428
+ else:
429
+ # Bmat = Matrix([]), so no need to sub
430
+ B_cont = Bmat_eq
431
+ if simplify:
432
+ A_cont.simplify()
433
+ B_cont.simplify()
434
+ return A_cont, B_cont
435
+ # Otherwise return M, A, B for forming the equation
436
+ # [M]dx = [A]x + [B]r, where x = [q, u]^T
437
+ else:
438
+ if simplify:
439
+ M_eq.simplify()
440
+ Amat_eq.simplify()
441
+ Bmat_eq.simplify()
442
+ return M_eq, Amat_eq, Bmat_eq
443
+
444
+
445
+ def permutation_matrix(orig_vec, per_vec):
446
+ """Compute the permutation matrix to change order of
447
+ orig_vec into order of per_vec.
448
+
449
+ Parameters
450
+ ==========
451
+
452
+ orig_vec : array_like
453
+ Symbols in original ordering.
454
+ per_vec : array_like
455
+ Symbols in new ordering.
456
+
457
+ Returns
458
+ =======
459
+
460
+ p_matrix : Matrix
461
+ Permutation matrix such that orig_vec == (p_matrix * per_vec).
462
+ """
463
+ if not isinstance(orig_vec, (list, tuple)):
464
+ orig_vec = flatten(orig_vec)
465
+ if not isinstance(per_vec, (list, tuple)):
466
+ per_vec = flatten(per_vec)
467
+ if set(orig_vec) != set(per_vec):
468
+ raise ValueError("orig_vec and per_vec must be the same length, "
469
+ "and contain the same symbols.")
470
+ ind_list = [orig_vec.index(i) for i in per_vec]
471
+ p_matrix = zeros(len(orig_vec))
472
+ for i, j in enumerate(ind_list):
473
+ p_matrix[i, j] = 1
474
+ return p_matrix
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/loads.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+ from collections import namedtuple
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.vector import Vector, ReferenceFrame, Point
5
+
6
+ __all__ = ['LoadBase', 'Force', 'Torque']
7
+
8
+
9
+ class LoadBase(ABC, namedtuple('LoadBase', ['location', 'vector'])):
10
+ """Abstract base class for the various loading types."""
11
+
12
+ def __add__(self, other):
13
+ raise TypeError(f"unsupported operand type(s) for +: "
14
+ f"'{self.__class__.__name__}' and "
15
+ f"'{other.__class__.__name__}'")
16
+
17
+ def __mul__(self, other):
18
+ raise TypeError(f"unsupported operand type(s) for *: "
19
+ f"'{self.__class__.__name__}' and "
20
+ f"'{other.__class__.__name__}'")
21
+
22
+ __radd__ = __add__
23
+ __rmul__ = __mul__
24
+
25
+
26
+ class Force(LoadBase):
27
+ """Force acting upon a point.
28
+
29
+ Explanation
30
+ ===========
31
+
32
+ A force is a vector that is bound to a line of action. This class stores
33
+ both a point, which lies on the line of action, and the vector. A tuple can
34
+ also be used, with the location as the first entry and the vector as second
35
+ entry.
36
+
37
+ Examples
38
+ ========
39
+
40
+ A force of magnitude 2 along N.x acting on a point Po can be created as
41
+ follows:
42
+
43
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, Force
44
+ >>> N = ReferenceFrame('N')
45
+ >>> Po = Point('Po')
46
+ >>> Force(Po, 2 * N.x)
47
+ (Po, 2*N.x)
48
+
49
+ If a body is supplied, then the center of mass of that body is used.
50
+
51
+ >>> from sympy.physics.mechanics import Particle
52
+ >>> P = Particle('P', point=Po)
53
+ >>> Force(P, 2 * N.x)
54
+ (Po, 2*N.x)
55
+
56
+ """
57
+
58
+ def __new__(cls, point, force):
59
+ if isinstance(point, BodyBase):
60
+ point = point.masscenter
61
+ if not isinstance(point, Point):
62
+ raise TypeError('Force location should be a Point.')
63
+ if not isinstance(force, Vector):
64
+ raise TypeError('Force vector should be a Vector.')
65
+ return super().__new__(cls, point, force)
66
+
67
+ def __repr__(self):
68
+ return (f'{self.__class__.__name__}(point={self.point}, '
69
+ f'force={self.force})')
70
+
71
+ @property
72
+ def point(self):
73
+ return self.location
74
+
75
+ @property
76
+ def force(self):
77
+ return self.vector
78
+
79
+
80
+ class Torque(LoadBase):
81
+ """Torque acting upon a frame.
82
+
83
+ Explanation
84
+ ===========
85
+
86
+ A torque is a free vector that is acting on a reference frame, which is
87
+ associated with a rigid body. This class stores both the frame and the
88
+ vector. A tuple can also be used, with the location as the first item and
89
+ the vector as second item.
90
+
91
+ Examples
92
+ ========
93
+
94
+ A torque of magnitude 2 about N.x acting on a frame N can be created as
95
+ follows:
96
+
97
+ >>> from sympy.physics.mechanics import ReferenceFrame, Torque
98
+ >>> N = ReferenceFrame('N')
99
+ >>> Torque(N, 2 * N.x)
100
+ (N, 2*N.x)
101
+
102
+ If a body is supplied, then the frame fixed to that body is used.
103
+
104
+ >>> from sympy.physics.mechanics import RigidBody
105
+ >>> rb = RigidBody('rb', frame=N)
106
+ >>> Torque(rb, 2 * N.x)
107
+ (N, 2*N.x)
108
+
109
+ """
110
+
111
+ def __new__(cls, frame, torque):
112
+ if isinstance(frame, BodyBase):
113
+ frame = frame.frame
114
+ if not isinstance(frame, ReferenceFrame):
115
+ raise TypeError('Torque location should be a ReferenceFrame.')
116
+ if not isinstance(torque, Vector):
117
+ raise TypeError('Torque vector should be a Vector.')
118
+ return super().__new__(cls, frame, torque)
119
+
120
+ def __repr__(self):
121
+ return (f'{self.__class__.__name__}(frame={self.frame}, '
122
+ f'torque={self.torque})')
123
+
124
+ @property
125
+ def frame(self):
126
+ return self.location
127
+
128
+ @property
129
+ def torque(self):
130
+ return self.vector
131
+
132
+
133
+ def gravity(acceleration, *bodies):
134
+ """
135
+ Returns a list of gravity forces given the acceleration
136
+ due to gravity and any number of particles or rigidbodies.
137
+
138
+ Example
139
+ =======
140
+
141
+ >>> from sympy.physics.mechanics import ReferenceFrame, Particle, RigidBody
142
+ >>> from sympy.physics.mechanics.loads import gravity
143
+ >>> from sympy import symbols
144
+ >>> N = ReferenceFrame('N')
145
+ >>> g = symbols('g')
146
+ >>> P = Particle('P')
147
+ >>> B = RigidBody('B')
148
+ >>> gravity(g*N.y, P, B)
149
+ [(P_masscenter, P_mass*g*N.y),
150
+ (B_masscenter, B_mass*g*N.y)]
151
+
152
+ """
153
+
154
+ gravity_force = []
155
+ for body in bodies:
156
+ if not isinstance(body, BodyBase):
157
+ raise TypeError(f'{type(body)} is not a body type')
158
+ gravity_force.append(Force(body.masscenter, body.mass * acceleration))
159
+ return gravity_force
160
+
161
+
162
+ def _parse_load(load):
163
+ """Helper function to parse loads and convert tuples to load objects."""
164
+ if isinstance(load, LoadBase):
165
+ return load
166
+ elif isinstance(load, tuple):
167
+ if len(load) != 2:
168
+ raise ValueError(f'Load {load} should have a length of 2.')
169
+ if isinstance(load[0], Point):
170
+ return Force(load[0], load[1])
171
+ elif isinstance(load[0], ReferenceFrame):
172
+ return Torque(load[0], load[1])
173
+ else:
174
+ raise ValueError(f'Load not recognized. The load location {load[0]}'
175
+ f' should either be a Point or a ReferenceFrame.')
176
+ raise TypeError(f'Load type {type(load)} not recognized as a load. It '
177
+ f'should be a Force, Torque or tuple.')
evalkit_internvl/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.")
evalkit_internvl/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
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import S
2
+ from sympy.physics.vector import cross, dot
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.mechanics.inertia import inertia_of_point_mass
5
+ from sympy.utilities.exceptions import sympy_deprecation_warning
6
+
7
+ __all__ = ['Particle']
8
+
9
+
10
+ class Particle(BodyBase):
11
+ """A particle.
12
+
13
+ Explanation
14
+ ===========
15
+
16
+ Particles have a non-zero mass and lack spatial extension; they take up no
17
+ space.
18
+
19
+ Values need to be supplied on initialization, but can be changed later.
20
+
21
+ Parameters
22
+ ==========
23
+
24
+ name : str
25
+ Name of particle
26
+ point : Point
27
+ A physics/mechanics Point which represents the position, velocity, and
28
+ acceleration of this Particle
29
+ mass : Sympifyable
30
+ A SymPy expression representing the Particle's mass
31
+ potential_energy : Sympifyable
32
+ The potential energy of the Particle.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy.physics.mechanics import Particle, Point
38
+ >>> from sympy import Symbol
39
+ >>> po = Point('po')
40
+ >>> m = Symbol('m')
41
+ >>> pa = Particle('pa', po, m)
42
+ >>> # Or you could change these later
43
+ >>> pa.mass = m
44
+ >>> pa.point = po
45
+
46
+ """
47
+ point = BodyBase.masscenter
48
+
49
+ def __init__(self, name, point=None, mass=None):
50
+ super().__init__(name, point, mass)
51
+
52
+ def linear_momentum(self, frame):
53
+ """Linear momentum of the particle.
54
+
55
+ Explanation
56
+ ===========
57
+
58
+ The linear momentum L, of a particle P, with respect to frame N is
59
+ given by:
60
+
61
+ L = m * v
62
+
63
+ where m is the mass of the particle, and v is the velocity of the
64
+ particle in the frame N.
65
+
66
+ Parameters
67
+ ==========
68
+
69
+ frame : ReferenceFrame
70
+ The frame in which linear momentum is desired.
71
+
72
+ Examples
73
+ ========
74
+
75
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
76
+ >>> from sympy.physics.mechanics import dynamicsymbols
77
+ >>> from sympy.physics.vector import init_vprinting
78
+ >>> init_vprinting(pretty_print=False)
79
+ >>> m, v = dynamicsymbols('m v')
80
+ >>> N = ReferenceFrame('N')
81
+ >>> P = Point('P')
82
+ >>> A = Particle('A', P, m)
83
+ >>> P.set_vel(N, v * N.x)
84
+ >>> A.linear_momentum(N)
85
+ m*v*N.x
86
+
87
+ """
88
+
89
+ return self.mass * self.point.vel(frame)
90
+
91
+ def angular_momentum(self, point, frame):
92
+ """Angular momentum of the particle about the point.
93
+
94
+ Explanation
95
+ ===========
96
+
97
+ The angular momentum H, about some point O of a particle, P, is given
98
+ by:
99
+
100
+ ``H = cross(r, m * v)``
101
+
102
+ where r is the position vector from point O to the particle P, m is
103
+ the mass of the particle, and v is the velocity of the particle in
104
+ the inertial frame, N.
105
+
106
+ Parameters
107
+ ==========
108
+
109
+ point : Point
110
+ The point about which angular momentum of the particle is desired.
111
+
112
+ frame : ReferenceFrame
113
+ The frame in which angular momentum is desired.
114
+
115
+ Examples
116
+ ========
117
+
118
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
119
+ >>> from sympy.physics.mechanics import dynamicsymbols
120
+ >>> from sympy.physics.vector import init_vprinting
121
+ >>> init_vprinting(pretty_print=False)
122
+ >>> m, v, r = dynamicsymbols('m v r')
123
+ >>> N = ReferenceFrame('N')
124
+ >>> O = Point('O')
125
+ >>> A = O.locatenew('A', r * N.x)
126
+ >>> P = Particle('P', A, m)
127
+ >>> P.point.set_vel(N, v * N.y)
128
+ >>> P.angular_momentum(O, N)
129
+ m*r*v*N.z
130
+
131
+ """
132
+
133
+ return cross(self.point.pos_from(point),
134
+ self.mass * self.point.vel(frame))
135
+
136
+ def kinetic_energy(self, frame):
137
+ """Kinetic energy of the particle.
138
+
139
+ Explanation
140
+ ===========
141
+
142
+ The kinetic energy, T, of a particle, P, is given by:
143
+
144
+ ``T = 1/2 (dot(m * v, v))``
145
+
146
+ where m is the mass of particle P, and v is the velocity of the
147
+ particle in the supplied ReferenceFrame.
148
+
149
+ Parameters
150
+ ==========
151
+
152
+ frame : ReferenceFrame
153
+ The Particle's velocity is typically defined with respect to
154
+ an inertial frame but any relevant frame in which the velocity is
155
+ known can be supplied.
156
+
157
+ Examples
158
+ ========
159
+
160
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
161
+ >>> from sympy import symbols
162
+ >>> m, v, r = symbols('m v r')
163
+ >>> N = ReferenceFrame('N')
164
+ >>> O = Point('O')
165
+ >>> P = Particle('P', O, m)
166
+ >>> P.point.set_vel(N, v * N.y)
167
+ >>> P.kinetic_energy(N)
168
+ m*v**2/2
169
+
170
+ """
171
+
172
+ return S.Half * self.mass * dot(self.point.vel(frame),
173
+ self.point.vel(frame))
174
+
175
+ def set_potential_energy(self, scalar):
176
+ sympy_deprecation_warning(
177
+ """
178
+ The sympy.physics.mechanics.Particle.set_potential_energy()
179
+ method is deprecated. Instead use
180
+
181
+ P.potential_energy = scalar
182
+ """,
183
+ deprecated_since_version="1.5",
184
+ active_deprecations_target="deprecated-set-potential-energy",
185
+ )
186
+ self.potential_energy = scalar
187
+
188
+ def parallel_axis(self, point, frame):
189
+ """Returns an inertia dyadic of the particle with respect to another
190
+ point and frame.
191
+
192
+ Parameters
193
+ ==========
194
+
195
+ point : sympy.physics.vector.Point
196
+ The point to express the inertia dyadic about.
197
+ frame : sympy.physics.vector.ReferenceFrame
198
+ The reference frame used to construct the dyadic.
199
+
200
+ Returns
201
+ =======
202
+
203
+ inertia : sympy.physics.vector.Dyadic
204
+ The inertia dyadic of the particle expressed about the provided
205
+ point and frame.
206
+
207
+ """
208
+ return inertia_of_point_mass(self.mass, self.point.pos_from(point),
209
+ frame)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/pathway.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementations of pathways for use by actuators."""
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy.core.singleton import S
6
+ from sympy.physics.mechanics.loads import Force
7
+ from sympy.physics.mechanics.wrapping_geometry import WrappingGeometryBase
8
+ from sympy.physics.vector import Point, dynamicsymbols
9
+
10
+
11
+ __all__ = ['PathwayBase', 'LinearPathway', 'ObstacleSetPathway',
12
+ 'WrappingPathway']
13
+
14
+
15
+ class PathwayBase(ABC):
16
+ """Abstract base class for all pathway classes to inherit from.
17
+
18
+ Notes
19
+ =====
20
+
21
+ Instances of this class cannot be directly instantiated by users. However,
22
+ it can be used to created custom pathway types through subclassing.
23
+
24
+ """
25
+
26
+ def __init__(self, *attachments):
27
+ """Initializer for ``PathwayBase``."""
28
+ self.attachments = attachments
29
+
30
+ @property
31
+ def attachments(self):
32
+ """The pair of points defining a pathway's ends."""
33
+ return self._attachments
34
+
35
+ @attachments.setter
36
+ def attachments(self, attachments):
37
+ if hasattr(self, '_attachments'):
38
+ msg = (
39
+ f'Can\'t set attribute `attachments` to {repr(attachments)} '
40
+ f'as it is immutable.'
41
+ )
42
+ raise AttributeError(msg)
43
+ if len(attachments) != 2:
44
+ msg = (
45
+ f'Value {repr(attachments)} passed to `attachments` was an '
46
+ f'iterable of length {len(attachments)}, must be an iterable '
47
+ f'of length 2.'
48
+ )
49
+ raise ValueError(msg)
50
+ for i, point in enumerate(attachments):
51
+ if not isinstance(point, Point):
52
+ msg = (
53
+ f'Value {repr(point)} passed to `attachments` at index '
54
+ f'{i} was of type {type(point)}, must be {Point}.'
55
+ )
56
+ raise TypeError(msg)
57
+ self._attachments = tuple(attachments)
58
+
59
+ @property
60
+ @abstractmethod
61
+ def length(self):
62
+ """An expression representing the pathway's length."""
63
+ pass
64
+
65
+ @property
66
+ @abstractmethod
67
+ def extension_velocity(self):
68
+ """An expression representing the pathway's extension velocity."""
69
+ pass
70
+
71
+ @abstractmethod
72
+ def to_loads(self, force):
73
+ """Loads required by the equations of motion method classes.
74
+
75
+ Explanation
76
+ ===========
77
+
78
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
79
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
80
+ when constructing the equations of motion. This method acts as a
81
+ utility to produce the correctly-structred pairs of points and vectors
82
+ required so that these can be easily concatenated with other items in
83
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
84
+ loads are also in the correct form to also be passed to the other
85
+ equations of motion method classes, e.g. ``LagrangesMethod``.
86
+
87
+ """
88
+ pass
89
+
90
+ def __repr__(self):
91
+ """Default representation of a pathway."""
92
+ attachments = ', '.join(str(a) for a in self.attachments)
93
+ return f'{self.__class__.__name__}({attachments})'
94
+
95
+
96
+ class LinearPathway(PathwayBase):
97
+ """Linear pathway between a pair of attachment points.
98
+
99
+ Explanation
100
+ ===========
101
+
102
+ A linear pathway forms a straight-line segment between two points and is
103
+ the simplest pathway that can be formed. It will not interact with any
104
+ other objects in the system, i.e. a ``LinearPathway`` will intersect other
105
+ objects to ensure that the path between its two ends (its attachments) is
106
+ the shortest possible.
107
+
108
+ A linear pathway is made up of two points that can move relative to each
109
+ other, and a pair of equal and opposite forces acting on the points. If the
110
+ positive time-varying Euclidean distance between the two points is defined,
111
+ then the "extension velocity" is the time derivative of this distance. The
112
+ extension velocity is positive when the two points are moving away from
113
+ each other and negative when moving closer to each other. The direction for
114
+ the force acting on either point is determined by constructing a unit
115
+ vector directed from the other point to this point. This establishes a sign
116
+ convention such that a positive force magnitude tends to push the points
117
+ apart. The following diagram shows the positive force sense and the
118
+ distance between the points::
119
+
120
+ P Q
121
+ o<--- F --->o
122
+ | |
123
+ |<--l(t)--->|
124
+
125
+ Examples
126
+ ========
127
+
128
+ >>> from sympy.physics.mechanics import LinearPathway
129
+
130
+ To construct a pathway, two points are required to be passed to the
131
+ ``attachments`` parameter as a ``tuple``.
132
+
133
+ >>> from sympy.physics.mechanics import Point
134
+ >>> pA, pB = Point('pA'), Point('pB')
135
+ >>> linear_pathway = LinearPathway(pA, pB)
136
+ >>> linear_pathway
137
+ LinearPathway(pA, pB)
138
+
139
+ The pathway created above isn't very interesting without the positions and
140
+ velocities of its attachment points being described. Without this its not
141
+ possible to describe how the pathway moves, i.e. its length or its
142
+ extension velocity.
143
+
144
+ >>> from sympy.physics.mechanics import ReferenceFrame
145
+ >>> from sympy.physics.vector import dynamicsymbols
146
+ >>> N = ReferenceFrame('N')
147
+ >>> q = dynamicsymbols('q')
148
+ >>> pB.set_pos(pA, q*N.x)
149
+ >>> pB.pos_from(pA)
150
+ q(t)*N.x
151
+
152
+ A pathway's length can be accessed via its ``length`` attribute.
153
+
154
+ >>> linear_pathway.length
155
+ sqrt(q(t)**2)
156
+
157
+ Note how what appears to be an overly-complex expression is returned. This
158
+ is actually required as it ensures that a pathway's length is always
159
+ positive.
160
+
161
+ A pathway's extension velocity can be accessed similarly via its
162
+ ``extension_velocity`` attribute.
163
+
164
+ >>> linear_pathway.extension_velocity
165
+ sqrt(q(t)**2)*Derivative(q(t), t)/q(t)
166
+
167
+ Parameters
168
+ ==========
169
+
170
+ attachments : tuple[Point, Point]
171
+ Pair of ``Point`` objects between which the linear pathway spans.
172
+ Constructor expects two points to be passed, e.g.
173
+ ``LinearPathway(Point('pA'), Point('pB'))``. More or fewer points will
174
+ cause an error to be thrown.
175
+
176
+ """
177
+
178
+ def __init__(self, *attachments):
179
+ """Initializer for ``LinearPathway``.
180
+
181
+ Parameters
182
+ ==========
183
+
184
+ attachments : Point
185
+ Pair of ``Point`` objects between which the linear pathway spans.
186
+ Constructor expects two points to be passed, e.g.
187
+ ``LinearPathway(Point('pA'), Point('pB'))``. More or fewer points
188
+ will cause an error to be thrown.
189
+
190
+ """
191
+ super().__init__(*attachments)
192
+
193
+ @property
194
+ def length(self):
195
+ """Exact analytical expression for the pathway's length."""
196
+ return _point_pair_length(*self.attachments)
197
+
198
+ @property
199
+ def extension_velocity(self):
200
+ """Exact analytical expression for the pathway's extension velocity."""
201
+ return _point_pair_extension_velocity(*self.attachments)
202
+
203
+ def to_loads(self, force):
204
+ """Loads required by the equations of motion method classes.
205
+
206
+ Explanation
207
+ ===========
208
+
209
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
210
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
211
+ when constructing the equations of motion. This method acts as a
212
+ utility to produce the correctly-structred pairs of points and vectors
213
+ required so that these can be easily concatenated with other items in
214
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
215
+ loads are also in the correct form to also be passed to the other
216
+ equations of motion method classes, e.g. ``LagrangesMethod``.
217
+
218
+ Examples
219
+ ========
220
+
221
+ The below example shows how to generate the loads produced in a linear
222
+ actuator that produces an expansile force ``F``. First, create a linear
223
+ actuator between two points separated by the coordinate ``q`` in the
224
+ ``x`` direction of the global frame ``N``.
225
+
226
+ >>> from sympy.physics.mechanics import (LinearPathway, Point,
227
+ ... ReferenceFrame)
228
+ >>> from sympy.physics.vector import dynamicsymbols
229
+ >>> q = dynamicsymbols('q')
230
+ >>> N = ReferenceFrame('N')
231
+ >>> pA, pB = Point('pA'), Point('pB')
232
+ >>> pB.set_pos(pA, q*N.x)
233
+ >>> linear_pathway = LinearPathway(pA, pB)
234
+
235
+ Now create a symbol ``F`` to describe the magnitude of the (expansile)
236
+ force that will be produced along the pathway. The list of loads that
237
+ ``KanesMethod`` requires can be produced by calling the pathway's
238
+ ``to_loads`` method with ``F`` passed as the only argument.
239
+
240
+ >>> from sympy import symbols
241
+ >>> F = symbols('F')
242
+ >>> linear_pathway.to_loads(F)
243
+ [(pA, - F*q(t)/sqrt(q(t)**2)*N.x), (pB, F*q(t)/sqrt(q(t)**2)*N.x)]
244
+
245
+ Parameters
246
+ ==========
247
+
248
+ force : Expr
249
+ Magnitude of the force acting along the length of the pathway. As
250
+ per the sign conventions for the pathway length, pathway extension
251
+ velocity, and pair of point forces, if this ``Expr`` is positive
252
+ then the force will act to push the pair of points away from one
253
+ another (it is expansile).
254
+
255
+ """
256
+ relative_position = _point_pair_relative_position(*self.attachments)
257
+ loads = [
258
+ Force(self.attachments[0], -force*relative_position/self.length),
259
+ Force(self.attachments[-1], force*relative_position/self.length),
260
+ ]
261
+ return loads
262
+
263
+
264
+ class ObstacleSetPathway(PathwayBase):
265
+ """Obstacle-set pathway between a set of attachment points.
266
+
267
+ Explanation
268
+ ===========
269
+
270
+ An obstacle-set pathway forms a series of straight-line segment between
271
+ pairs of consecutive points in a set of points. It is similiar to multiple
272
+ linear pathways joined end-to-end. It will not interact with any other
273
+ objects in the system, i.e. an ``ObstacleSetPathway`` will intersect other
274
+ objects to ensure that the path between its pairs of points (its
275
+ attachments) is the shortest possible.
276
+
277
+ Examples
278
+ ========
279
+
280
+ To construct an obstacle-set pathway, three or more points are required to
281
+ be passed to the ``attachments`` parameter as a ``tuple``.
282
+
283
+ >>> from sympy.physics.mechanics import ObstacleSetPathway, Point
284
+ >>> pA, pB, pC, pD = Point('pA'), Point('pB'), Point('pC'), Point('pD')
285
+ >>> obstacle_set_pathway = ObstacleSetPathway(pA, pB, pC, pD)
286
+ >>> obstacle_set_pathway
287
+ ObstacleSetPathway(pA, pB, pC, pD)
288
+
289
+ The pathway created above isn't very interesting without the positions and
290
+ velocities of its attachment points being described. Without this its not
291
+ possible to describe how the pathway moves, i.e. its length or its
292
+ extension velocity.
293
+
294
+ >>> from sympy import cos, sin
295
+ >>> from sympy.physics.mechanics import ReferenceFrame
296
+ >>> from sympy.physics.vector import dynamicsymbols
297
+ >>> N = ReferenceFrame('N')
298
+ >>> q = dynamicsymbols('q')
299
+ >>> pO = Point('pO')
300
+ >>> pA.set_pos(pO, N.y)
301
+ >>> pB.set_pos(pO, -N.x)
302
+ >>> pC.set_pos(pA, cos(q) * N.x - (sin(q) + 1) * N.y)
303
+ >>> pD.set_pos(pA, sin(q) * N.x + (cos(q) - 1) * N.y)
304
+ >>> pB.pos_from(pA)
305
+ - N.x - N.y
306
+ >>> pC.pos_from(pA)
307
+ cos(q(t))*N.x + (-sin(q(t)) - 1)*N.y
308
+ >>> pD.pos_from(pA)
309
+ sin(q(t))*N.x + (cos(q(t)) - 1)*N.y
310
+
311
+ A pathway's length can be accessed via its ``length`` attribute.
312
+
313
+ >>> obstacle_set_pathway.length.simplify()
314
+ sqrt(2)*(sqrt(cos(q(t)) + 1) + 2)
315
+
316
+ A pathway's extension velocity can be accessed similarly via its
317
+ ``extension_velocity`` attribute.
318
+
319
+ >>> obstacle_set_pathway.extension_velocity.simplify()
320
+ -sqrt(2)*sin(q(t))*Derivative(q(t), t)/(2*sqrt(cos(q(t)) + 1))
321
+
322
+ Parameters
323
+ ==========
324
+
325
+ attachments : tuple[Point, Point]
326
+ The set of ``Point`` objects that define the segmented obstacle-set
327
+ pathway.
328
+
329
+ """
330
+
331
+ def __init__(self, *attachments):
332
+ """Initializer for ``ObstacleSetPathway``.
333
+
334
+ Parameters
335
+ ==========
336
+
337
+ attachments : tuple[Point, ...]
338
+ The set of ``Point`` objects that define the segmented obstacle-set
339
+ pathway.
340
+
341
+ """
342
+ super().__init__(*attachments)
343
+
344
+ @property
345
+ def attachments(self):
346
+ """The set of points defining a pathway's segmented path."""
347
+ return self._attachments
348
+
349
+ @attachments.setter
350
+ def attachments(self, attachments):
351
+ if hasattr(self, '_attachments'):
352
+ msg = (
353
+ f'Can\'t set attribute `attachments` to {repr(attachments)} '
354
+ f'as it is immutable.'
355
+ )
356
+ raise AttributeError(msg)
357
+ if len(attachments) <= 2:
358
+ msg = (
359
+ f'Value {repr(attachments)} passed to `attachments` was an '
360
+ f'iterable of length {len(attachments)}, must be an iterable '
361
+ f'of length 3 or greater.'
362
+ )
363
+ raise ValueError(msg)
364
+ for i, point in enumerate(attachments):
365
+ if not isinstance(point, Point):
366
+ msg = (
367
+ f'Value {repr(point)} passed to `attachments` at index '
368
+ f'{i} was of type {type(point)}, must be {Point}.'
369
+ )
370
+ raise TypeError(msg)
371
+ self._attachments = tuple(attachments)
372
+
373
+ @property
374
+ def length(self):
375
+ """Exact analytical expression for the pathway's length."""
376
+ length = S.Zero
377
+ attachment_pairs = zip(self.attachments[:-1], self.attachments[1:])
378
+ for attachment_pair in attachment_pairs:
379
+ length += _point_pair_length(*attachment_pair)
380
+ return length
381
+
382
+ @property
383
+ def extension_velocity(self):
384
+ """Exact analytical expression for the pathway's extension velocity."""
385
+ extension_velocity = S.Zero
386
+ attachment_pairs = zip(self.attachments[:-1], self.attachments[1:])
387
+ for attachment_pair in attachment_pairs:
388
+ extension_velocity += _point_pair_extension_velocity(*attachment_pair)
389
+ return extension_velocity
390
+
391
+ def to_loads(self, force):
392
+ """Loads required by the equations of motion method classes.
393
+
394
+ Explanation
395
+ ===========
396
+
397
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
398
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
399
+ when constructing the equations of motion. This method acts as a
400
+ utility to produce the correctly-structred pairs of points and vectors
401
+ required so that these can be easily concatenated with other items in
402
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
403
+ loads are also in the correct form to also be passed to the other
404
+ equations of motion method classes, e.g. ``LagrangesMethod``.
405
+
406
+ Examples
407
+ ========
408
+
409
+ The below example shows how to generate the loads produced in an
410
+ actuator that follows an obstacle-set pathway between four points and
411
+ produces an expansile force ``F``. First, create a pair of reference
412
+ frames, ``A`` and ``B``, in which the four points ``pA``, ``pB``,
413
+ ``pC``, and ``pD`` will be located. The first two points in frame ``A``
414
+ and the second two in frame ``B``. Frame ``B`` will also be oriented
415
+ such that it relates to ``A`` via a rotation of ``q`` about an axis
416
+ ``N.z`` in a global frame (``N.z``, ``A.z``, and ``B.z`` are parallel).
417
+
418
+ >>> from sympy.physics.mechanics import (ObstacleSetPathway, Point,
419
+ ... ReferenceFrame)
420
+ >>> from sympy.physics.vector import dynamicsymbols
421
+ >>> q = dynamicsymbols('q')
422
+ >>> N = ReferenceFrame('N')
423
+ >>> N = ReferenceFrame('N')
424
+ >>> A = N.orientnew('A', 'axis', (0, N.x))
425
+ >>> B = A.orientnew('B', 'axis', (q, N.z))
426
+ >>> pO = Point('pO')
427
+ >>> pA, pB, pC, pD = Point('pA'), Point('pB'), Point('pC'), Point('pD')
428
+ >>> pA.set_pos(pO, A.x)
429
+ >>> pB.set_pos(pO, -A.y)
430
+ >>> pC.set_pos(pO, B.y)
431
+ >>> pD.set_pos(pO, B.x)
432
+ >>> obstacle_set_pathway = ObstacleSetPathway(pA, pB, pC, pD)
433
+
434
+ Now create a symbol ``F`` to describe the magnitude of the (expansile)
435
+ force that will be produced along the pathway. The list of loads that
436
+ ``KanesMethod`` requires can be produced by calling the pathway's
437
+ ``to_loads`` method with ``F`` passed as the only argument.
438
+
439
+ >>> from sympy import Symbol
440
+ >>> F = Symbol('F')
441
+ >>> obstacle_set_pathway.to_loads(F)
442
+ [(pA, sqrt(2)*F/2*A.x + sqrt(2)*F/2*A.y),
443
+ (pB, - sqrt(2)*F/2*A.x - sqrt(2)*F/2*A.y),
444
+ (pB, - F/sqrt(2*cos(q(t)) + 2)*A.y - F/sqrt(2*cos(q(t)) + 2)*B.y),
445
+ (pC, F/sqrt(2*cos(q(t)) + 2)*A.y + F/sqrt(2*cos(q(t)) + 2)*B.y),
446
+ (pC, - sqrt(2)*F/2*B.x + sqrt(2)*F/2*B.y),
447
+ (pD, sqrt(2)*F/2*B.x - sqrt(2)*F/2*B.y)]
448
+
449
+ Parameters
450
+ ==========
451
+
452
+ force : Expr
453
+ The force acting along the length of the pathway. It is assumed
454
+ that this ``Expr`` represents an expansile force.
455
+
456
+ """
457
+ loads = []
458
+ attachment_pairs = zip(self.attachments[:-1], self.attachments[1:])
459
+ for attachment_pair in attachment_pairs:
460
+ relative_position = _point_pair_relative_position(*attachment_pair)
461
+ length = _point_pair_length(*attachment_pair)
462
+ loads.extend([
463
+ Force(attachment_pair[0], -force*relative_position/length),
464
+ Force(attachment_pair[1], force*relative_position/length),
465
+ ])
466
+ return loads
467
+
468
+
469
+ class WrappingPathway(PathwayBase):
470
+ """Pathway that wraps a geometry object.
471
+
472
+ Explanation
473
+ ===========
474
+
475
+ A wrapping pathway interacts with a geometry object and forms a path that
476
+ wraps smoothly along its surface. The wrapping pathway along the geometry
477
+ object will be the geodesic that the geometry object defines based on the
478
+ two points. It will not interact with any other objects in the system, i.e.
479
+ a ``WrappingPathway`` will intersect other objects to ensure that the path
480
+ between its two ends (its attachments) is the shortest possible.
481
+
482
+ To explain the sign conventions used for pathway length, extension
483
+ velocity, and direction of applied forces, we can ignore the geometry with
484
+ which the wrapping pathway interacts. A wrapping pathway is made up of two
485
+ points that can move relative to each other, and a pair of equal and
486
+ opposite forces acting on the points. If the positive time-varying
487
+ Euclidean distance between the two points is defined, then the "extension
488
+ velocity" is the time derivative of this distance. The extension velocity
489
+ is positive when the two points are moving away from each other and
490
+ negative when moving closer to each other. The direction for the force
491
+ acting on either point is determined by constructing a unit vector directed
492
+ from the other point to this point. This establishes a sign convention such
493
+ that a positive force magnitude tends to push the points apart. The
494
+ following diagram shows the positive force sense and the distance between
495
+ the points::
496
+
497
+ P Q
498
+ o<--- F --->o
499
+ | |
500
+ |<--l(t)--->|
501
+
502
+ Examples
503
+ ========
504
+
505
+ >>> from sympy.physics.mechanics import WrappingPathway
506
+
507
+ To construct a wrapping pathway, like other pathways, a pair of points must
508
+ be passed, followed by an instance of a wrapping geometry class as a
509
+ keyword argument. We'll use a cylinder with radius ``r`` and its axis
510
+ parallel to ``N.x`` passing through a point ``pO``.
511
+
512
+ >>> from sympy import symbols
513
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, WrappingCylinder
514
+ >>> r = symbols('r')
515
+ >>> N = ReferenceFrame('N')
516
+ >>> pA, pB, pO = Point('pA'), Point('pB'), Point('pO')
517
+ >>> cylinder = WrappingCylinder(r, pO, N.x)
518
+ >>> wrapping_pathway = WrappingPathway(pA, pB, cylinder)
519
+ >>> wrapping_pathway
520
+ WrappingPathway(pA, pB, geometry=WrappingCylinder(radius=r, point=pO,
521
+ axis=N.x))
522
+
523
+ Parameters
524
+ ==========
525
+
526
+ attachment_1 : Point
527
+ First of the pair of ``Point`` objects between which the wrapping
528
+ pathway spans.
529
+ attachment_2 : Point
530
+ Second of the pair of ``Point`` objects between which the wrapping
531
+ pathway spans.
532
+ geometry : WrappingGeometryBase
533
+ Geometry about which the pathway wraps.
534
+
535
+ """
536
+
537
+ def __init__(self, attachment_1, attachment_2, geometry):
538
+ """Initializer for ``WrappingPathway``.
539
+
540
+ Parameters
541
+ ==========
542
+
543
+ attachment_1 : Point
544
+ First of the pair of ``Point`` objects between which the wrapping
545
+ pathway spans.
546
+ attachment_2 : Point
547
+ Second of the pair of ``Point`` objects between which the wrapping
548
+ pathway spans.
549
+ geometry : WrappingGeometryBase
550
+ Geometry about which the pathway wraps.
551
+ The geometry about which the pathway wraps.
552
+
553
+ """
554
+ super().__init__(attachment_1, attachment_2)
555
+ self.geometry = geometry
556
+
557
+ @property
558
+ def geometry(self):
559
+ """Geometry around which the pathway wraps."""
560
+ return self._geometry
561
+
562
+ @geometry.setter
563
+ def geometry(self, geometry):
564
+ if hasattr(self, '_geometry'):
565
+ msg = (
566
+ f'Can\'t set attribute `geometry` to {repr(geometry)} as it '
567
+ f'is immutable.'
568
+ )
569
+ raise AttributeError(msg)
570
+ if not isinstance(geometry, WrappingGeometryBase):
571
+ msg = (
572
+ f'Value {repr(geometry)} passed to `geometry` was of type '
573
+ f'{type(geometry)}, must be {WrappingGeometryBase}.'
574
+ )
575
+ raise TypeError(msg)
576
+ self._geometry = geometry
577
+
578
+ @property
579
+ def length(self):
580
+ """Exact analytical expression for the pathway's length."""
581
+ return self.geometry.geodesic_length(*self.attachments)
582
+
583
+ @property
584
+ def extension_velocity(self):
585
+ """Exact analytical expression for the pathway's extension velocity."""
586
+ return self.length.diff(dynamicsymbols._t)
587
+
588
+ def to_loads(self, force):
589
+ """Loads required by the equations of motion method classes.
590
+
591
+ Explanation
592
+ ===========
593
+
594
+ ``KanesMethod`` requires a list of ``Point``-``Vector`` tuples to be
595
+ passed to the ``loads`` parameters of its ``kanes_equations`` method
596
+ when constructing the equations of motion. This method acts as a
597
+ utility to produce the correctly-structred pairs of points and vectors
598
+ required so that these can be easily concatenated with other items in
599
+ the list of loads and passed to ``KanesMethod.kanes_equations``. These
600
+ loads are also in the correct form to also be passed to the other
601
+ equations of motion method classes, e.g. ``LagrangesMethod``.
602
+
603
+ Examples
604
+ ========
605
+
606
+ The below example shows how to generate the loads produced in an
607
+ actuator that produces an expansile force ``F`` while wrapping around a
608
+ cylinder. First, create a cylinder with radius ``r`` and an axis
609
+ parallel to the ``N.z`` direction of the global frame ``N`` that also
610
+ passes through a point ``pO``.
611
+
612
+ >>> from sympy import symbols
613
+ >>> from sympy.physics.mechanics import (Point, ReferenceFrame,
614
+ ... WrappingCylinder)
615
+ >>> N = ReferenceFrame('N')
616
+ >>> r = symbols('r', positive=True)
617
+ >>> pO = Point('pO')
618
+ >>> cylinder = WrappingCylinder(r, pO, N.z)
619
+
620
+ Create the pathway of the actuator using the ``WrappingPathway`` class,
621
+ defined to span between two points ``pA`` and ``pB``. Both points lie
622
+ on the surface of the cylinder and the location of ``pB`` is defined
623
+ relative to ``pA`` by the dynamics symbol ``q``.
624
+
625
+ >>> from sympy import cos, sin
626
+ >>> from sympy.physics.mechanics import WrappingPathway, dynamicsymbols
627
+ >>> q = dynamicsymbols('q')
628
+ >>> pA = Point('pA')
629
+ >>> pB = Point('pB')
630
+ >>> pA.set_pos(pO, r*N.x)
631
+ >>> pB.set_pos(pO, r*(cos(q)*N.x + sin(q)*N.y))
632
+ >>> pB.pos_from(pA)
633
+ (r*cos(q(t)) - r)*N.x + r*sin(q(t))*N.y
634
+ >>> pathway = WrappingPathway(pA, pB, cylinder)
635
+
636
+ Now create a symbol ``F`` to describe the magnitude of the (expansile)
637
+ force that will be produced along the pathway. The list of loads that
638
+ ``KanesMethod`` requires can be produced by calling the pathway's
639
+ ``to_loads`` method with ``F`` passed as the only argument.
640
+
641
+ >>> F = symbols('F')
642
+ >>> loads = pathway.to_loads(F)
643
+ >>> [load.__class__(load.location, load.vector.simplify()) for load in loads]
644
+ [(pA, F*N.y), (pB, F*sin(q(t))*N.x - F*cos(q(t))*N.y),
645
+ (pO, - F*sin(q(t))*N.x + F*(cos(q(t)) - 1)*N.y)]
646
+
647
+ Parameters
648
+ ==========
649
+
650
+ force : Expr
651
+ Magnitude of the force acting along the length of the pathway. It
652
+ is assumed that this ``Expr`` represents an expansile force.
653
+
654
+ """
655
+ pA, pB = self.attachments
656
+ pO = self.geometry.point
657
+ pA_force, pB_force = self.geometry.geodesic_end_vectors(pA, pB)
658
+ pO_force = -(pA_force + pB_force)
659
+
660
+ loads = [
661
+ Force(pA, force * pA_force),
662
+ Force(pB, force * pB_force),
663
+ Force(pO, force * pO_force),
664
+ ]
665
+ return loads
666
+
667
+ def __repr__(self):
668
+ """Representation of a ``WrappingPathway``."""
669
+ attachments = ', '.join(str(a) for a in self.attachments)
670
+ return (
671
+ f'{self.__class__.__name__}({attachments}, '
672
+ f'geometry={self.geometry})'
673
+ )
674
+
675
+
676
+ def _point_pair_relative_position(point_1, point_2):
677
+ """The relative position between a pair of points."""
678
+ return point_2.pos_from(point_1)
679
+
680
+
681
+ def _point_pair_length(point_1, point_2):
682
+ """The length of the direct linear path between two points."""
683
+ return _point_pair_relative_position(point_1, point_2).magnitude()
684
+
685
+
686
+ def _point_pair_extension_velocity(point_1, point_2):
687
+ """The extension velocity of the direct linear path between two points."""
688
+ return _point_pair_length(point_1, point_2).diff(dynamicsymbols._t)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import Symbol, S
2
+ from sympy.physics.vector import ReferenceFrame, Dyadic, Point, dot
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.physics.mechanics.inertia import inertia_of_point_mass, Inertia
5
+ from sympy.utilities.exceptions import sympy_deprecation_warning
6
+
7
+ __all__ = ['RigidBody']
8
+
9
+
10
+ class RigidBody(BodyBase):
11
+ """An idealized rigid body.
12
+
13
+ Explanation
14
+ ===========
15
+
16
+ This is essentially a container which holds the various components which
17
+ describe a rigid body: a name, mass, center of mass, reference frame, and
18
+ inertia.
19
+
20
+ All of these need to be supplied on creation, but can be changed
21
+ afterwards.
22
+
23
+ Attributes
24
+ ==========
25
+
26
+ name : string
27
+ The body's name.
28
+ masscenter : Point
29
+ The point which represents the center of mass of the rigid body.
30
+ frame : ReferenceFrame
31
+ The ReferenceFrame which the rigid body is fixed in.
32
+ mass : Sympifyable
33
+ The body's mass.
34
+ inertia : (Dyadic, Point)
35
+ The body's inertia about a point; stored in a tuple as shown above.
36
+ potential_energy : Sympifyable
37
+ The potential energy of the RigidBody.
38
+
39
+ Examples
40
+ ========
41
+
42
+ >>> from sympy import Symbol
43
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody
44
+ >>> from sympy.physics.mechanics import outer
45
+ >>> m = Symbol('m')
46
+ >>> A = ReferenceFrame('A')
47
+ >>> P = Point('P')
48
+ >>> I = outer (A.x, A.x)
49
+ >>> inertia_tuple = (I, P)
50
+ >>> B = RigidBody('B', P, A, m, inertia_tuple)
51
+ >>> # Or you could change them afterwards
52
+ >>> m2 = Symbol('m2')
53
+ >>> B.mass = m2
54
+
55
+ """
56
+
57
+ def __init__(self, name, masscenter=None, frame=None, mass=None,
58
+ inertia=None):
59
+ super().__init__(name, masscenter, mass)
60
+ if frame is None:
61
+ frame = ReferenceFrame(f'{name}_frame')
62
+ self.frame = frame
63
+ if inertia is None:
64
+ ixx = Symbol(f'{name}_ixx')
65
+ iyy = Symbol(f'{name}_iyy')
66
+ izz = Symbol(f'{name}_izz')
67
+ izx = Symbol(f'{name}_izx')
68
+ ixy = Symbol(f'{name}_ixy')
69
+ iyz = Symbol(f'{name}_iyz')
70
+ inertia = Inertia.from_inertia_scalars(self.masscenter, self.frame,
71
+ ixx, iyy, izz, ixy, iyz, izx)
72
+ self.inertia = inertia
73
+
74
+ def __repr__(self):
75
+ return (f'{self.__class__.__name__}({repr(self.name)}, masscenter='
76
+ f'{repr(self.masscenter)}, frame={repr(self.frame)}, mass='
77
+ f'{repr(self.mass)}, inertia={repr(self.inertia)})')
78
+
79
+ @property
80
+ def frame(self):
81
+ """The ReferenceFrame fixed to the body."""
82
+ return self._frame
83
+
84
+ @frame.setter
85
+ def frame(self, F):
86
+ if not isinstance(F, ReferenceFrame):
87
+ raise TypeError("RigidBody frame must be a ReferenceFrame object.")
88
+ self._frame = F
89
+
90
+ @property
91
+ def x(self):
92
+ """The basis Vector for the body, in the x direction. """
93
+ return self.frame.x
94
+
95
+ @property
96
+ def y(self):
97
+ """The basis Vector for the body, in the y direction. """
98
+ return self.frame.y
99
+
100
+ @property
101
+ def z(self):
102
+ """The basis Vector for the body, in the z direction. """
103
+ return self.frame.z
104
+
105
+ @property
106
+ def inertia(self):
107
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
108
+ return self._inertia
109
+
110
+ @inertia.setter
111
+ def inertia(self, I):
112
+ # check if I is of the form (Dyadic, Point)
113
+ if len(I) != 2 or not isinstance(I[0], Dyadic) or not isinstance(I[1], Point):
114
+ raise TypeError("RigidBody inertia must be a tuple of the form (Dyadic, Point).")
115
+
116
+ self._inertia = Inertia(I[0], I[1])
117
+ # have I S/O, want I S/S*
118
+ # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O
119
+ # I_S/S* = I_S/O - I_S*/O
120
+ I_Ss_O = inertia_of_point_mass(self.mass,
121
+ self.masscenter.pos_from(I[1]),
122
+ self.frame)
123
+ self._central_inertia = I[0] - I_Ss_O
124
+
125
+ @property
126
+ def central_inertia(self):
127
+ """The body's central inertia dyadic."""
128
+ return self._central_inertia
129
+
130
+ @central_inertia.setter
131
+ def central_inertia(self, I):
132
+ if not isinstance(I, Dyadic):
133
+ raise TypeError("RigidBody inertia must be a Dyadic object.")
134
+ self.inertia = Inertia(I, self.masscenter)
135
+
136
+ def linear_momentum(self, frame):
137
+ """ Linear momentum of the rigid body.
138
+
139
+ Explanation
140
+ ===========
141
+
142
+ The linear momentum L, of a rigid body B, with respect to frame N is
143
+ given by:
144
+
145
+ ``L = m * v``
146
+
147
+ where m is the mass of the rigid body, and v is the velocity of the mass
148
+ center of B in the frame N.
149
+
150
+ Parameters
151
+ ==========
152
+
153
+ frame : ReferenceFrame
154
+ The frame in which linear momentum is desired.
155
+
156
+ Examples
157
+ ========
158
+
159
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
160
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
161
+ >>> from sympy.physics.vector import init_vprinting
162
+ >>> init_vprinting(pretty_print=False)
163
+ >>> m, v = dynamicsymbols('m v')
164
+ >>> N = ReferenceFrame('N')
165
+ >>> P = Point('P')
166
+ >>> P.set_vel(N, v * N.x)
167
+ >>> I = outer (N.x, N.x)
168
+ >>> Inertia_tuple = (I, P)
169
+ >>> B = RigidBody('B', P, N, m, Inertia_tuple)
170
+ >>> B.linear_momentum(N)
171
+ m*v*N.x
172
+
173
+ """
174
+
175
+ return self.mass * self.masscenter.vel(frame)
176
+
177
+ def angular_momentum(self, point, frame):
178
+ """Returns the angular momentum of the rigid body about a point in the
179
+ given frame.
180
+
181
+ Explanation
182
+ ===========
183
+
184
+ The angular momentum H of a rigid body B about some point O in a frame N
185
+ is given by:
186
+
187
+ ``H = dot(I, w) + cross(r, m * v)``
188
+
189
+ where I and m are the central inertia dyadic and mass of rigid body B, w
190
+ is the angular velocity of body B in the frame N, r is the position
191
+ vector from point O to the mass center of B, and v is the velocity of
192
+ the mass center in the frame N.
193
+
194
+ Parameters
195
+ ==========
196
+
197
+ point : Point
198
+ The point about which angular momentum is desired.
199
+ frame : ReferenceFrame
200
+ The frame in which angular momentum is desired.
201
+
202
+ Examples
203
+ ========
204
+
205
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
206
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
207
+ >>> from sympy.physics.vector import init_vprinting
208
+ >>> init_vprinting(pretty_print=False)
209
+ >>> m, v, r, omega = dynamicsymbols('m v r omega')
210
+ >>> N = ReferenceFrame('N')
211
+ >>> b = ReferenceFrame('b')
212
+ >>> b.set_ang_vel(N, omega * b.x)
213
+ >>> P = Point('P')
214
+ >>> P.set_vel(N, 1 * N.x)
215
+ >>> I = outer(b.x, b.x)
216
+ >>> B = RigidBody('B', P, b, m, (I, P))
217
+ >>> B.angular_momentum(P, N)
218
+ omega*b.x
219
+
220
+ """
221
+ I = self.central_inertia
222
+ w = self.frame.ang_vel_in(frame)
223
+ m = self.mass
224
+ r = self.masscenter.pos_from(point)
225
+ v = self.masscenter.vel(frame)
226
+
227
+ return I.dot(w) + r.cross(m * v)
228
+
229
+ def kinetic_energy(self, frame):
230
+ """Kinetic energy of the rigid body.
231
+
232
+ Explanation
233
+ ===========
234
+
235
+ The kinetic energy, T, of a rigid body, B, is given by:
236
+
237
+ ``T = 1/2 * (dot(dot(I, w), w) + dot(m * v, v))``
238
+
239
+ where I and m are the central inertia dyadic and mass of rigid body B
240
+ respectively, w is the body's angular velocity, and v is the velocity of
241
+ the body's mass center in the supplied ReferenceFrame.
242
+
243
+ Parameters
244
+ ==========
245
+
246
+ frame : ReferenceFrame
247
+ The RigidBody's angular velocity and the velocity of it's mass
248
+ center are typically defined with respect to an inertial frame but
249
+ any relevant frame in which the velocities are known can be
250
+ supplied.
251
+
252
+ Examples
253
+ ========
254
+
255
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
256
+ >>> from sympy.physics.mechanics import RigidBody
257
+ >>> from sympy import symbols
258
+ >>> m, v, r, omega = symbols('m v r omega')
259
+ >>> N = ReferenceFrame('N')
260
+ >>> b = ReferenceFrame('b')
261
+ >>> b.set_ang_vel(N, omega * b.x)
262
+ >>> P = Point('P')
263
+ >>> P.set_vel(N, v * N.x)
264
+ >>> I = outer (b.x, b.x)
265
+ >>> inertia_tuple = (I, P)
266
+ >>> B = RigidBody('B', P, b, m, inertia_tuple)
267
+ >>> B.kinetic_energy(N)
268
+ m*v**2/2 + omega**2/2
269
+
270
+ """
271
+
272
+ rotational_KE = S.Half * dot(
273
+ self.frame.ang_vel_in(frame),
274
+ dot(self.central_inertia, self.frame.ang_vel_in(frame)))
275
+ translational_KE = S.Half * self.mass * dot(self.masscenter.vel(frame),
276
+ self.masscenter.vel(frame))
277
+ return rotational_KE + translational_KE
278
+
279
+ def set_potential_energy(self, scalar):
280
+ sympy_deprecation_warning(
281
+ """
282
+ The sympy.physics.mechanics.RigidBody.set_potential_energy()
283
+ method is deprecated. Instead use
284
+
285
+ B.potential_energy = scalar
286
+ """,
287
+ deprecated_since_version="1.5",
288
+ active_deprecations_target="deprecated-set-potential-energy",
289
+ )
290
+ self.potential_energy = scalar
291
+
292
+ def parallel_axis(self, point, frame=None):
293
+ """Returns the inertia dyadic of the body with respect to another point.
294
+
295
+ Parameters
296
+ ==========
297
+
298
+ point : sympy.physics.vector.Point
299
+ The point to express the inertia dyadic about.
300
+ frame : sympy.physics.vector.ReferenceFrame
301
+ The reference frame used to construct the dyadic.
302
+
303
+ Returns
304
+ =======
305
+
306
+ inertia : sympy.physics.vector.Dyadic
307
+ The inertia dyadic of the rigid body expressed about the provided
308
+ point.
309
+
310
+ """
311
+ if frame is None:
312
+ frame = self.frame
313
+ return self.central_inertia + inertia_of_point_mass(
314
+ self.mass, self.masscenter.pos_from(point), frame)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_actuator.py ADDED
@@ -0,0 +1,851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.mechanics.actuator.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy import (
6
+ S,
7
+ Matrix,
8
+ Symbol,
9
+ SympifyError,
10
+ sqrt,
11
+ Abs
12
+ )
13
+ from sympy.physics.mechanics import (
14
+ ActuatorBase,
15
+ Force,
16
+ ForceActuator,
17
+ KanesMethod,
18
+ LinearDamper,
19
+ LinearPathway,
20
+ LinearSpring,
21
+ Particle,
22
+ PinJoint,
23
+ Point,
24
+ ReferenceFrame,
25
+ RigidBody,
26
+ TorqueActuator,
27
+ Vector,
28
+ dynamicsymbols,
29
+ DuffingSpring,
30
+ )
31
+
32
+ from sympy.core.expr import Expr as ExprType
33
+
34
+ target = RigidBody('target')
35
+ reaction = RigidBody('reaction')
36
+
37
+
38
+ class TestForceActuator:
39
+
40
+ @pytest.fixture(autouse=True)
41
+ def _linear_pathway_fixture(self):
42
+ self.force = Symbol('F')
43
+ self.pA = Point('pA')
44
+ self.pB = Point('pB')
45
+ self.pathway = LinearPathway(self.pA, self.pB)
46
+ self.q1 = dynamicsymbols('q1')
47
+ self.q2 = dynamicsymbols('q2')
48
+ self.q3 = dynamicsymbols('q3')
49
+ self.q1d = dynamicsymbols('q1', 1)
50
+ self.q2d = dynamicsymbols('q2', 1)
51
+ self.q3d = dynamicsymbols('q3', 1)
52
+ self.N = ReferenceFrame('N')
53
+
54
+ def test_is_actuator_base_subclass(self):
55
+ assert issubclass(ForceActuator, ActuatorBase)
56
+
57
+ @pytest.mark.parametrize(
58
+ 'force, expected_force',
59
+ [
60
+ (1, S.One),
61
+ (S.One, S.One),
62
+ (Symbol('F'), Symbol('F')),
63
+ (dynamicsymbols('F'), dynamicsymbols('F')),
64
+ (Symbol('F')**2 + Symbol('F'), Symbol('F')**2 + Symbol('F')),
65
+ ]
66
+ )
67
+ def test_valid_constructor_force(self, force, expected_force):
68
+ instance = ForceActuator(force, self.pathway)
69
+ assert isinstance(instance, ForceActuator)
70
+ assert hasattr(instance, 'force')
71
+ assert isinstance(instance.force, ExprType)
72
+ assert instance.force == expected_force
73
+
74
+ @pytest.mark.parametrize('force', [None, 'F'])
75
+ def test_invalid_constructor_force_not_sympifyable(self, force):
76
+ with pytest.raises(SympifyError):
77
+ _ = ForceActuator(force, self.pathway)
78
+
79
+ @pytest.mark.parametrize(
80
+ 'pathway',
81
+ [
82
+ LinearPathway(Point('pA'), Point('pB')),
83
+ ]
84
+ )
85
+ def test_valid_constructor_pathway(self, pathway):
86
+ instance = ForceActuator(self.force, pathway)
87
+ assert isinstance(instance, ForceActuator)
88
+ assert hasattr(instance, 'pathway')
89
+ assert isinstance(instance.pathway, LinearPathway)
90
+ assert instance.pathway == pathway
91
+
92
+ def test_invalid_constructor_pathway_not_pathway_base(self):
93
+ with pytest.raises(TypeError):
94
+ _ = ForceActuator(self.force, None)
95
+
96
+ @pytest.mark.parametrize(
97
+ 'property_name, fixture_attr_name',
98
+ [
99
+ ('force', 'force'),
100
+ ('pathway', 'pathway'),
101
+ ]
102
+ )
103
+ def test_properties_are_immutable(self, property_name, fixture_attr_name):
104
+ instance = ForceActuator(self.force, self.pathway)
105
+ value = getattr(self, fixture_attr_name)
106
+ with pytest.raises(AttributeError):
107
+ setattr(instance, property_name, value)
108
+
109
+ def test_repr(self):
110
+ actuator = ForceActuator(self.force, self.pathway)
111
+ expected = "ForceActuator(F, LinearPathway(pA, pB))"
112
+ assert repr(actuator) == expected
113
+
114
+ def test_to_loads_static_pathway(self):
115
+ self.pB.set_pos(self.pA, 2*self.N.x)
116
+ actuator = ForceActuator(self.force, self.pathway)
117
+ expected = [
118
+ (self.pA, - self.force*self.N.x),
119
+ (self.pB, self.force*self.N.x),
120
+ ]
121
+ assert actuator.to_loads() == expected
122
+
123
+ def test_to_loads_2D_pathway(self):
124
+ self.pB.set_pos(self.pA, 2*self.q1*self.N.x)
125
+ actuator = ForceActuator(self.force, self.pathway)
126
+ expected = [
127
+ (self.pA, - self.force*(self.q1/sqrt(self.q1**2))*self.N.x),
128
+ (self.pB, self.force*(self.q1/sqrt(self.q1**2))*self.N.x),
129
+ ]
130
+ assert actuator.to_loads() == expected
131
+
132
+ def test_to_loads_3D_pathway(self):
133
+ self.pB.set_pos(
134
+ self.pA,
135
+ self.q1*self.N.x - self.q2*self.N.y + 2*self.q3*self.N.z,
136
+ )
137
+ actuator = ForceActuator(self.force, self.pathway)
138
+ length = sqrt(self.q1**2 + self.q2**2 + 4*self.q3**2)
139
+ pO_force = (
140
+ - self.force*self.q1*self.N.x/length
141
+ + self.force*self.q2*self.N.y/length
142
+ - 2*self.force*self.q3*self.N.z/length
143
+ )
144
+ pI_force = (
145
+ self.force*self.q1*self.N.x/length
146
+ - self.force*self.q2*self.N.y/length
147
+ + 2*self.force*self.q3*self.N.z/length
148
+ )
149
+ expected = [
150
+ (self.pA, pO_force),
151
+ (self.pB, pI_force),
152
+ ]
153
+ assert actuator.to_loads() == expected
154
+
155
+
156
+ class TestLinearSpring:
157
+
158
+ @pytest.fixture(autouse=True)
159
+ def _linear_spring_fixture(self):
160
+ self.stiffness = Symbol('k')
161
+ self.l = Symbol('l')
162
+ self.pA = Point('pA')
163
+ self.pB = Point('pB')
164
+ self.pathway = LinearPathway(self.pA, self.pB)
165
+ self.q = dynamicsymbols('q')
166
+ self.N = ReferenceFrame('N')
167
+
168
+ def test_is_force_actuator_subclass(self):
169
+ assert issubclass(LinearSpring, ForceActuator)
170
+
171
+ def test_is_actuator_base_subclass(self):
172
+ assert issubclass(LinearSpring, ActuatorBase)
173
+
174
+ @pytest.mark.parametrize(
175
+ (
176
+ 'stiffness, '
177
+ 'expected_stiffness, '
178
+ 'equilibrium_length, '
179
+ 'expected_equilibrium_length, '
180
+ 'force'
181
+ ),
182
+ [
183
+ (
184
+ 1,
185
+ S.One,
186
+ 0,
187
+ S.Zero,
188
+ -sqrt(dynamicsymbols('q')**2),
189
+ ),
190
+ (
191
+ Symbol('k'),
192
+ Symbol('k'),
193
+ 0,
194
+ S.Zero,
195
+ -Symbol('k')*sqrt(dynamicsymbols('q')**2),
196
+ ),
197
+ (
198
+ Symbol('k'),
199
+ Symbol('k'),
200
+ S.Zero,
201
+ S.Zero,
202
+ -Symbol('k')*sqrt(dynamicsymbols('q')**2),
203
+ ),
204
+ (
205
+ Symbol('k'),
206
+ Symbol('k'),
207
+ Symbol('l'),
208
+ Symbol('l'),
209
+ -Symbol('k')*(sqrt(dynamicsymbols('q')**2) - Symbol('l')),
210
+ ),
211
+ ]
212
+ )
213
+ def test_valid_constructor(
214
+ self,
215
+ stiffness,
216
+ expected_stiffness,
217
+ equilibrium_length,
218
+ expected_equilibrium_length,
219
+ force,
220
+ ):
221
+ self.pB.set_pos(self.pA, self.q*self.N.x)
222
+ spring = LinearSpring(stiffness, self.pathway, equilibrium_length)
223
+
224
+ assert isinstance(spring, LinearSpring)
225
+
226
+ assert hasattr(spring, 'stiffness')
227
+ assert isinstance(spring.stiffness, ExprType)
228
+ assert spring.stiffness == expected_stiffness
229
+
230
+ assert hasattr(spring, 'pathway')
231
+ assert isinstance(spring.pathway, LinearPathway)
232
+ assert spring.pathway == self.pathway
233
+
234
+ assert hasattr(spring, 'equilibrium_length')
235
+ assert isinstance(spring.equilibrium_length, ExprType)
236
+ assert spring.equilibrium_length == expected_equilibrium_length
237
+
238
+ assert hasattr(spring, 'force')
239
+ assert isinstance(spring.force, ExprType)
240
+ assert spring.force == force
241
+
242
+ @pytest.mark.parametrize('stiffness', [None, 'k'])
243
+ def test_invalid_constructor_stiffness_not_sympifyable(self, stiffness):
244
+ with pytest.raises(SympifyError):
245
+ _ = LinearSpring(stiffness, self.pathway, self.l)
246
+
247
+ def test_invalid_constructor_pathway_not_pathway_base(self):
248
+ with pytest.raises(TypeError):
249
+ _ = LinearSpring(self.stiffness, None, self.l)
250
+
251
+ @pytest.mark.parametrize('equilibrium_length', [None, 'l'])
252
+ def test_invalid_constructor_equilibrium_length_not_sympifyable(
253
+ self,
254
+ equilibrium_length,
255
+ ):
256
+ with pytest.raises(SympifyError):
257
+ _ = LinearSpring(self.stiffness, self.pathway, equilibrium_length)
258
+
259
+ @pytest.mark.parametrize(
260
+ 'property_name, fixture_attr_name',
261
+ [
262
+ ('stiffness', 'stiffness'),
263
+ ('pathway', 'pathway'),
264
+ ('equilibrium_length', 'l'),
265
+ ]
266
+ )
267
+ def test_properties_are_immutable(self, property_name, fixture_attr_name):
268
+ spring = LinearSpring(self.stiffness, self.pathway, self.l)
269
+ value = getattr(self, fixture_attr_name)
270
+ with pytest.raises(AttributeError):
271
+ setattr(spring, property_name, value)
272
+
273
+ @pytest.mark.parametrize(
274
+ 'equilibrium_length, expected',
275
+ [
276
+ (S.Zero, 'LinearSpring(k, LinearPathway(pA, pB))'),
277
+ (
278
+ Symbol('l'),
279
+ 'LinearSpring(k, LinearPathway(pA, pB), equilibrium_length=l)',
280
+ ),
281
+ ]
282
+ )
283
+ def test_repr(self, equilibrium_length, expected):
284
+ self.pB.set_pos(self.pA, self.q*self.N.x)
285
+ spring = LinearSpring(self.stiffness, self.pathway, equilibrium_length)
286
+ assert repr(spring) == expected
287
+
288
+ def test_to_loads(self):
289
+ self.pB.set_pos(self.pA, self.q*self.N.x)
290
+ spring = LinearSpring(self.stiffness, self.pathway, self.l)
291
+ normal = self.q/sqrt(self.q**2)*self.N.x
292
+ pA_force = self.stiffness*(sqrt(self.q**2) - self.l)*normal
293
+ pB_force = -self.stiffness*(sqrt(self.q**2) - self.l)*normal
294
+ expected = [Force(self.pA, pA_force), Force(self.pB, pB_force)]
295
+ loads = spring.to_loads()
296
+
297
+ for load, (point, vector) in zip(loads, expected):
298
+ assert isinstance(load, Force)
299
+ assert load.point == point
300
+ assert (load.vector - vector).simplify() == 0
301
+
302
+
303
+ class TestLinearDamper:
304
+
305
+ @pytest.fixture(autouse=True)
306
+ def _linear_damper_fixture(self):
307
+ self.damping = Symbol('c')
308
+ self.l = Symbol('l')
309
+ self.pA = Point('pA')
310
+ self.pB = Point('pB')
311
+ self.pathway = LinearPathway(self.pA, self.pB)
312
+ self.q = dynamicsymbols('q')
313
+ self.dq = dynamicsymbols('q', 1)
314
+ self.u = dynamicsymbols('u')
315
+ self.N = ReferenceFrame('N')
316
+
317
+ def test_is_force_actuator_subclass(self):
318
+ assert issubclass(LinearDamper, ForceActuator)
319
+
320
+ def test_is_actuator_base_subclass(self):
321
+ assert issubclass(LinearDamper, ActuatorBase)
322
+
323
+ def test_valid_constructor(self):
324
+ self.pB.set_pos(self.pA, self.q*self.N.x)
325
+ damper = LinearDamper(self.damping, self.pathway)
326
+
327
+ assert isinstance(damper, LinearDamper)
328
+
329
+ assert hasattr(damper, 'damping')
330
+ assert isinstance(damper.damping, ExprType)
331
+ assert damper.damping == self.damping
332
+
333
+ assert hasattr(damper, 'pathway')
334
+ assert isinstance(damper.pathway, LinearPathway)
335
+ assert damper.pathway == self.pathway
336
+
337
+ def test_valid_constructor_force(self):
338
+ self.pB.set_pos(self.pA, self.q*self.N.x)
339
+ damper = LinearDamper(self.damping, self.pathway)
340
+
341
+ expected_force = -self.damping*sqrt(self.q**2)*self.dq/self.q
342
+ assert hasattr(damper, 'force')
343
+ assert isinstance(damper.force, ExprType)
344
+ assert damper.force == expected_force
345
+
346
+ @pytest.mark.parametrize('damping', [None, 'c'])
347
+ def test_invalid_constructor_damping_not_sympifyable(self, damping):
348
+ with pytest.raises(SympifyError):
349
+ _ = LinearDamper(damping, self.pathway)
350
+
351
+ def test_invalid_constructor_pathway_not_pathway_base(self):
352
+ with pytest.raises(TypeError):
353
+ _ = LinearDamper(self.damping, None)
354
+
355
+ @pytest.mark.parametrize(
356
+ 'property_name, fixture_attr_name',
357
+ [
358
+ ('damping', 'damping'),
359
+ ('pathway', 'pathway'),
360
+ ]
361
+ )
362
+ def test_properties_are_immutable(self, property_name, fixture_attr_name):
363
+ damper = LinearDamper(self.damping, self.pathway)
364
+ value = getattr(self, fixture_attr_name)
365
+ with pytest.raises(AttributeError):
366
+ setattr(damper, property_name, value)
367
+
368
+ def test_repr(self):
369
+ self.pB.set_pos(self.pA, self.q*self.N.x)
370
+ damper = LinearDamper(self.damping, self.pathway)
371
+ expected = 'LinearDamper(c, LinearPathway(pA, pB))'
372
+ assert repr(damper) == expected
373
+
374
+ def test_to_loads(self):
375
+ self.pB.set_pos(self.pA, self.q*self.N.x)
376
+ damper = LinearDamper(self.damping, self.pathway)
377
+ direction = self.q**2/self.q**2*self.N.x
378
+ pA_force = self.damping*self.dq*direction
379
+ pB_force = -self.damping*self.dq*direction
380
+ expected = [Force(self.pA, pA_force), Force(self.pB, pB_force)]
381
+ assert damper.to_loads() == expected
382
+
383
+
384
+ class TestForcedMassSpringDamperModel():
385
+ r"""A single degree of freedom translational forced mass-spring-damper.
386
+
387
+ Notes
388
+ =====
389
+
390
+ This system is well known to have the governing equation:
391
+
392
+ .. math::
393
+ m \ddot{x} = F - k x - c \dot{x}
394
+
395
+ where $F$ is an externally applied force, $m$ is the mass of the particle
396
+ to which the spring and damper are attached, $k$ is the spring's stiffness,
397
+ $c$ is the dampers damping coefficient, and $x$ is the generalized
398
+ coordinate representing the system's single (translational) degree of
399
+ freedom.
400
+
401
+ """
402
+
403
+ @pytest.fixture(autouse=True)
404
+ def _force_mass_spring_damper_model_fixture(self):
405
+ self.m = Symbol('m')
406
+ self.k = Symbol('k')
407
+ self.c = Symbol('c')
408
+ self.F = Symbol('F')
409
+
410
+ self.q = dynamicsymbols('q')
411
+ self.dq = dynamicsymbols('q', 1)
412
+ self.u = dynamicsymbols('u')
413
+
414
+ self.frame = ReferenceFrame('N')
415
+ self.origin = Point('pO')
416
+ self.origin.set_vel(self.frame, 0)
417
+
418
+ self.attachment = Point('pA')
419
+ self.attachment.set_pos(self.origin, self.q*self.frame.x)
420
+
421
+ self.mass = Particle('mass', self.attachment, self.m)
422
+ self.pathway = LinearPathway(self.origin, self.attachment)
423
+
424
+ self.kanes_method = KanesMethod(
425
+ self.frame,
426
+ q_ind=[self.q],
427
+ u_ind=[self.u],
428
+ kd_eqs=[self.dq - self.u],
429
+ )
430
+ self.bodies = [self.mass]
431
+
432
+ self.mass_matrix = Matrix([[self.m]])
433
+ self.forcing = Matrix([[self.F - self.c*self.u - self.k*self.q]])
434
+
435
+ def test_force_acuator(self):
436
+ stiffness = -self.k*self.pathway.length
437
+ spring = ForceActuator(stiffness, self.pathway)
438
+ damping = -self.c*self.pathway.extension_velocity
439
+ damper = ForceActuator(damping, self.pathway)
440
+
441
+ loads = [
442
+ (self.attachment, self.F*self.frame.x),
443
+ *spring.to_loads(),
444
+ *damper.to_loads(),
445
+ ]
446
+ self.kanes_method.kanes_equations(self.bodies, loads)
447
+
448
+ assert self.kanes_method.mass_matrix == self.mass_matrix
449
+ assert self.kanes_method.forcing == self.forcing
450
+
451
+ def test_linear_spring_linear_damper(self):
452
+ spring = LinearSpring(self.k, self.pathway)
453
+ damper = LinearDamper(self.c, self.pathway)
454
+
455
+ loads = [
456
+ (self.attachment, self.F*self.frame.x),
457
+ *spring.to_loads(),
458
+ *damper.to_loads(),
459
+ ]
460
+ self.kanes_method.kanes_equations(self.bodies, loads)
461
+
462
+ assert self.kanes_method.mass_matrix == self.mass_matrix
463
+ assert self.kanes_method.forcing == self.forcing
464
+
465
+
466
+ class TestTorqueActuator:
467
+
468
+ @pytest.fixture(autouse=True)
469
+ def _torque_actuator_fixture(self):
470
+ self.torque = Symbol('T')
471
+ self.N = ReferenceFrame('N')
472
+ self.A = ReferenceFrame('A')
473
+ self.axis = self.N.z
474
+ self.target = RigidBody('target', frame=self.N)
475
+ self.reaction = RigidBody('reaction', frame=self.A)
476
+
477
+ def test_is_actuator_base_subclass(self):
478
+ assert issubclass(TorqueActuator, ActuatorBase)
479
+
480
+ @pytest.mark.parametrize(
481
+ 'torque',
482
+ [
483
+ Symbol('T'),
484
+ dynamicsymbols('T'),
485
+ Symbol('T')**2 + Symbol('T'),
486
+ ]
487
+ )
488
+ @pytest.mark.parametrize(
489
+ 'target_frame, reaction_frame',
490
+ [
491
+ (target.frame, reaction.frame),
492
+ (target, reaction.frame),
493
+ (target.frame, reaction),
494
+ (target, reaction),
495
+ ]
496
+ )
497
+ def test_valid_constructor_with_reaction(
498
+ self,
499
+ torque,
500
+ target_frame,
501
+ reaction_frame,
502
+ ):
503
+ instance = TorqueActuator(
504
+ torque,
505
+ self.axis,
506
+ target_frame,
507
+ reaction_frame,
508
+ )
509
+ assert isinstance(instance, TorqueActuator)
510
+
511
+ assert hasattr(instance, 'torque')
512
+ assert isinstance(instance.torque, ExprType)
513
+ assert instance.torque == torque
514
+
515
+ assert hasattr(instance, 'axis')
516
+ assert isinstance(instance.axis, Vector)
517
+ assert instance.axis == self.axis
518
+
519
+ assert hasattr(instance, 'target_frame')
520
+ assert isinstance(instance.target_frame, ReferenceFrame)
521
+ assert instance.target_frame == target.frame
522
+
523
+ assert hasattr(instance, 'reaction_frame')
524
+ assert isinstance(instance.reaction_frame, ReferenceFrame)
525
+ assert instance.reaction_frame == reaction.frame
526
+
527
+ @pytest.mark.parametrize(
528
+ 'torque',
529
+ [
530
+ Symbol('T'),
531
+ dynamicsymbols('T'),
532
+ Symbol('T')**2 + Symbol('T'),
533
+ ]
534
+ )
535
+ @pytest.mark.parametrize('target_frame', [target.frame, target])
536
+ def test_valid_constructor_without_reaction(self, torque, target_frame):
537
+ instance = TorqueActuator(torque, self.axis, target_frame)
538
+ assert isinstance(instance, TorqueActuator)
539
+
540
+ assert hasattr(instance, 'torque')
541
+ assert isinstance(instance.torque, ExprType)
542
+ assert instance.torque == torque
543
+
544
+ assert hasattr(instance, 'axis')
545
+ assert isinstance(instance.axis, Vector)
546
+ assert instance.axis == self.axis
547
+
548
+ assert hasattr(instance, 'target_frame')
549
+ assert isinstance(instance.target_frame, ReferenceFrame)
550
+ assert instance.target_frame == target.frame
551
+
552
+ assert hasattr(instance, 'reaction_frame')
553
+ assert instance.reaction_frame is None
554
+
555
+ @pytest.mark.parametrize('torque', [None, 'T'])
556
+ def test_invalid_constructor_torque_not_sympifyable(self, torque):
557
+ with pytest.raises(SympifyError):
558
+ _ = TorqueActuator(torque, self.axis, self.target)
559
+
560
+ @pytest.mark.parametrize('axis', [Symbol('a'), dynamicsymbols('a')])
561
+ def test_invalid_constructor_axis_not_vector(self, axis):
562
+ with pytest.raises(TypeError):
563
+ _ = TorqueActuator(self.torque, axis, self.target, self.reaction)
564
+
565
+ @pytest.mark.parametrize(
566
+ 'frames',
567
+ [
568
+ (None, ReferenceFrame('child')),
569
+ (ReferenceFrame('parent'), True),
570
+ (None, RigidBody('child')),
571
+ (RigidBody('parent'), True),
572
+ ]
573
+ )
574
+ def test_invalid_constructor_frames_not_frame(self, frames):
575
+ with pytest.raises(TypeError):
576
+ _ = TorqueActuator(self.torque, self.axis, *frames)
577
+
578
+ @pytest.mark.parametrize(
579
+ 'property_name, fixture_attr_name',
580
+ [
581
+ ('torque', 'torque'),
582
+ ('axis', 'axis'),
583
+ ('target_frame', 'target'),
584
+ ('reaction_frame', 'reaction'),
585
+ ]
586
+ )
587
+ def test_properties_are_immutable(self, property_name, fixture_attr_name):
588
+ actuator = TorqueActuator(
589
+ self.torque,
590
+ self.axis,
591
+ self.target,
592
+ self.reaction,
593
+ )
594
+ value = getattr(self, fixture_attr_name)
595
+ with pytest.raises(AttributeError):
596
+ setattr(actuator, property_name, value)
597
+
598
+ def test_repr_without_reaction(self):
599
+ actuator = TorqueActuator(self.torque, self.axis, self.target)
600
+ expected = 'TorqueActuator(T, axis=N.z, target_frame=N)'
601
+ assert repr(actuator) == expected
602
+
603
+ def test_repr_with_reaction(self):
604
+ actuator = TorqueActuator(
605
+ self.torque,
606
+ self.axis,
607
+ self.target,
608
+ self.reaction,
609
+ )
610
+ expected = 'TorqueActuator(T, axis=N.z, target_frame=N, reaction_frame=A)'
611
+ assert repr(actuator) == expected
612
+
613
+ def test_at_pin_joint_constructor(self):
614
+ pin_joint = PinJoint(
615
+ 'pin',
616
+ self.target,
617
+ self.reaction,
618
+ coordinates=dynamicsymbols('q'),
619
+ speeds=dynamicsymbols('u'),
620
+ parent_interframe=self.N,
621
+ joint_axis=self.axis,
622
+ )
623
+ instance = TorqueActuator.at_pin_joint(self.torque, pin_joint)
624
+ assert isinstance(instance, TorqueActuator)
625
+
626
+ assert hasattr(instance, 'torque')
627
+ assert isinstance(instance.torque, ExprType)
628
+ assert instance.torque == self.torque
629
+
630
+ assert hasattr(instance, 'axis')
631
+ assert isinstance(instance.axis, Vector)
632
+ assert instance.axis == self.axis
633
+
634
+ assert hasattr(instance, 'target_frame')
635
+ assert isinstance(instance.target_frame, ReferenceFrame)
636
+ assert instance.target_frame == self.A
637
+
638
+ assert hasattr(instance, 'reaction_frame')
639
+ assert isinstance(instance.reaction_frame, ReferenceFrame)
640
+ assert instance.reaction_frame == self.N
641
+
642
+ def test_at_pin_joint_pin_joint_not_pin_joint_invalid(self):
643
+ with pytest.raises(TypeError):
644
+ _ = TorqueActuator.at_pin_joint(self.torque, Symbol('pin'))
645
+
646
+ def test_to_loads_without_reaction(self):
647
+ actuator = TorqueActuator(self.torque, self.axis, self.target)
648
+ expected = [
649
+ (self.N, self.torque*self.axis),
650
+ ]
651
+ assert actuator.to_loads() == expected
652
+
653
+ def test_to_loads_with_reaction(self):
654
+ actuator = TorqueActuator(
655
+ self.torque,
656
+ self.axis,
657
+ self.target,
658
+ self.reaction,
659
+ )
660
+ expected = [
661
+ (self.N, self.torque*self.axis),
662
+ (self.A, - self.torque*self.axis),
663
+ ]
664
+ assert actuator.to_loads() == expected
665
+
666
+
667
+ class NonSympifyable:
668
+ pass
669
+
670
+
671
+ class TestDuffingSpring:
672
+ @pytest.fixture(autouse=True)
673
+ # Set up common vairables that will be used in multiple tests
674
+ def _duffing_spring_fixture(self):
675
+ self.linear_stiffness = Symbol('beta')
676
+ self.nonlinear_stiffness = Symbol('alpha')
677
+ self.equilibrium_length = Symbol('l')
678
+ self.pA = Point('pA')
679
+ self.pB = Point('pB')
680
+ self.pathway = LinearPathway(self.pA, self.pB)
681
+ self.q = dynamicsymbols('q')
682
+ self.N = ReferenceFrame('N')
683
+
684
+ # Simples tests to check that DuffingSpring is a subclass of ForceActuator and ActuatorBase
685
+ def test_is_force_actuator_subclass(self):
686
+ assert issubclass(DuffingSpring, ForceActuator)
687
+
688
+ def test_is_actuator_base_subclass(self):
689
+ assert issubclass(DuffingSpring, ActuatorBase)
690
+
691
+ @pytest.mark.parametrize(
692
+ # Create parametrized tests that allows running the same test function multiple times with different sets of arguments
693
+ (
694
+ 'linear_stiffness, '
695
+ 'expected_linear_stiffness, '
696
+ 'nonlinear_stiffness, '
697
+ 'expected_nonlinear_stiffness, '
698
+ 'equilibrium_length, '
699
+ 'expected_equilibrium_length, '
700
+ 'force'
701
+ ),
702
+ [
703
+ (
704
+ 1,
705
+ S.One,
706
+ 1,
707
+ S.One,
708
+ 0,
709
+ S.Zero,
710
+ -sqrt(dynamicsymbols('q')**2)-(sqrt(dynamicsymbols('q')**2))**3,
711
+ ),
712
+ (
713
+ Symbol('beta'),
714
+ Symbol('beta'),
715
+ Symbol('alpha'),
716
+ Symbol('alpha'),
717
+ 0,
718
+ S.Zero,
719
+ -Symbol('beta')*sqrt(dynamicsymbols('q')**2)-Symbol('alpha')*(sqrt(dynamicsymbols('q')**2))**3,
720
+ ),
721
+ (
722
+ Symbol('beta'),
723
+ Symbol('beta'),
724
+ Symbol('alpha'),
725
+ Symbol('alpha'),
726
+ S.Zero,
727
+ S.Zero,
728
+ -Symbol('beta')*sqrt(dynamicsymbols('q')**2)-Symbol('alpha')*(sqrt(dynamicsymbols('q')**2))**3,
729
+ ),
730
+ (
731
+ Symbol('beta'),
732
+ Symbol('beta'),
733
+ Symbol('alpha'),
734
+ Symbol('alpha'),
735
+ Symbol('l'),
736
+ Symbol('l'),
737
+ -Symbol('beta') * (sqrt(dynamicsymbols('q')**2) - Symbol('l')) - Symbol('alpha') * (sqrt(dynamicsymbols('q')**2) - Symbol('l'))**3,
738
+ ),
739
+ ]
740
+ )
741
+
742
+ # Check if DuffingSpring correctly inializes its attributes
743
+ # It tests various combinations of linear & nonlinear stiffness, equilibriun length, and the resulting force expression
744
+ def test_valid_constructor(
745
+ self,
746
+ linear_stiffness,
747
+ expected_linear_stiffness,
748
+ nonlinear_stiffness,
749
+ expected_nonlinear_stiffness,
750
+ equilibrium_length,
751
+ expected_equilibrium_length,
752
+ force,
753
+ ):
754
+ self.pB.set_pos(self.pA, self.q*self.N.x)
755
+ spring = DuffingSpring(linear_stiffness, nonlinear_stiffness, self.pathway, equilibrium_length)
756
+
757
+ assert isinstance(spring, DuffingSpring)
758
+
759
+ assert hasattr(spring, 'linear_stiffness')
760
+ assert isinstance(spring.linear_stiffness, ExprType)
761
+ assert spring.linear_stiffness == expected_linear_stiffness
762
+
763
+ assert hasattr(spring, 'nonlinear_stiffness')
764
+ assert isinstance(spring.nonlinear_stiffness, ExprType)
765
+ assert spring.nonlinear_stiffness == expected_nonlinear_stiffness
766
+
767
+ assert hasattr(spring, 'pathway')
768
+ assert isinstance(spring.pathway, LinearPathway)
769
+ assert spring.pathway == self.pathway
770
+
771
+ assert hasattr(spring, 'equilibrium_length')
772
+ assert isinstance(spring.equilibrium_length, ExprType)
773
+ assert spring.equilibrium_length == expected_equilibrium_length
774
+
775
+ assert hasattr(spring, 'force')
776
+ assert isinstance(spring.force, ExprType)
777
+ assert spring.force == force
778
+
779
+ @pytest.mark.parametrize('linear_stiffness', [None, NonSympifyable()])
780
+ def test_invalid_constructor_linear_stiffness_not_sympifyable(self, linear_stiffness):
781
+ with pytest.raises(SympifyError):
782
+ _ = DuffingSpring(linear_stiffness, self.nonlinear_stiffness, self.pathway, self.equilibrium_length)
783
+
784
+ @pytest.mark.parametrize('nonlinear_stiffness', [None, NonSympifyable()])
785
+ def test_invalid_constructor_nonlinear_stiffness_not_sympifyable(self, nonlinear_stiffness):
786
+ with pytest.raises(SympifyError):
787
+ _ = DuffingSpring(self.linear_stiffness, nonlinear_stiffness, self.pathway, self.equilibrium_length)
788
+
789
+ def test_invalid_constructor_pathway_not_pathway_base(self):
790
+ with pytest.raises(TypeError):
791
+ _ = DuffingSpring(self.linear_stiffness, self.nonlinear_stiffness, NonSympifyable(), self.equilibrium_length)
792
+
793
+ @pytest.mark.parametrize('equilibrium_length', [None, NonSympifyable()])
794
+ def test_invalid_constructor_equilibrium_length_not_sympifyable(self, equilibrium_length):
795
+ with pytest.raises(SympifyError):
796
+ _ = DuffingSpring(self.linear_stiffness, self.nonlinear_stiffness, self.pathway, equilibrium_length)
797
+
798
+ @pytest.mark.parametrize(
799
+ 'property_name, fixture_attr_name',
800
+ [
801
+ ('linear_stiffness', 'linear_stiffness'),
802
+ ('nonlinear_stiffness', 'nonlinear_stiffness'),
803
+ ('pathway', 'pathway'),
804
+ ('equilibrium_length', 'equilibrium_length')
805
+ ]
806
+ )
807
+ # Check if certain properties of DuffingSpring object are immutable after initialization
808
+ # Ensure that once DuffingSpring is created, its key properties cannot be changed
809
+ def test_properties_are_immutable(self, property_name, fixture_attr_name):
810
+ spring = DuffingSpring(self.linear_stiffness, self.nonlinear_stiffness, self.pathway, self.equilibrium_length)
811
+ with pytest.raises(AttributeError):
812
+ setattr(spring, property_name, getattr(self, fixture_attr_name))
813
+
814
+ @pytest.mark.parametrize(
815
+ 'equilibrium_length, expected',
816
+ [
817
+ (0, 'DuffingSpring(beta, alpha, LinearPathway(pA, pB), equilibrium_length=0)'),
818
+ (Symbol('l'), 'DuffingSpring(beta, alpha, LinearPathway(pA, pB), equilibrium_length=l)'),
819
+ ]
820
+ )
821
+ # Check the __repr__ method of DuffingSpring class
822
+ # Check if the actual string representation of DuffingSpring instance matches the expected string for each provided parameter values
823
+ def test_repr(self, equilibrium_length, expected):
824
+ spring = DuffingSpring(self.linear_stiffness, self.nonlinear_stiffness, self.pathway, equilibrium_length)
825
+ assert repr(spring) == expected
826
+
827
+ def test_to_loads(self):
828
+ self.pB.set_pos(self.pA, self.q*self.N.x)
829
+ spring = DuffingSpring(self.linear_stiffness, self.nonlinear_stiffness, self.pathway, self.equilibrium_length)
830
+
831
+ # Calculate the displacement from the equilibrium length
832
+ displacement = self.q - self.equilibrium_length
833
+
834
+ # Make sure this matches the computation in DuffingSpring class
835
+ force = -self.linear_stiffness * displacement - self.nonlinear_stiffness * displacement**3
836
+
837
+ # The expected loads on pA and pB due to the spring
838
+ expected_loads = [Force(self.pA, force * self.N.x), Force(self.pB, -force * self.N.x)]
839
+
840
+ # Compare expected loads to what is returned from DuffingSpring.to_loads()
841
+ calculated_loads = spring.to_loads()
842
+ for calculated, expected in zip(calculated_loads, expected_loads):
843
+ assert calculated.point == expected.point
844
+ for dim in self.N: # Assuming self.N is the reference frame
845
+ calculated_component = calculated.vector.dot(dim)
846
+ expected_component = expected.vector.dot(dim)
847
+ # Substitute all symbols with numeric values
848
+ substitutions = {self.q: 1, Symbol('l'): 1, Symbol('alpha'): 1, Symbol('beta'): 1} # Add other necessary symbols as needed
849
+ diff = (calculated_component - expected_component).subs(substitutions).evalf()
850
+ # Check if the absolute value of the difference is below a threshold
851
+ assert Abs(diff) < 1e-9, f"The forces do not match. Difference: {diff}"
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_functions.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import sin, cos, tan, pi, symbols, Matrix, S, Function
2
+ from sympy.physics.mechanics import (Particle, Point, ReferenceFrame,
3
+ RigidBody)
4
+ from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
5
+ kinetic_energy, linear_momentum,
6
+ outer, potential_energy, msubs,
7
+ find_dynamicsymbols, Lagrangian)
8
+
9
+ from sympy.physics.mechanics.functions import (
10
+ center_of_mass, _validate_coordinates, _parse_linear_solver)
11
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
12
+
13
+
14
+ q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
15
+ N = ReferenceFrame('N')
16
+ A = N.orientnew('A', 'Axis', [q1, N.z])
17
+ B = A.orientnew('B', 'Axis', [q2, A.x])
18
+ C = B.orientnew('C', 'Axis', [q3, B.y])
19
+
20
+
21
+ def test_linear_momentum():
22
+ N = ReferenceFrame('N')
23
+ Ac = Point('Ac')
24
+ Ac.set_vel(N, 25 * N.y)
25
+ I = outer(N.x, N.x)
26
+ A = RigidBody('A', Ac, N, 20, (I, Ac))
27
+ P = Point('P')
28
+ Pa = Particle('Pa', P, 1)
29
+ Pa.point.set_vel(N, 10 * N.x)
30
+ raises(TypeError, lambda: linear_momentum(A, A, Pa))
31
+ raises(TypeError, lambda: linear_momentum(N, N, Pa))
32
+ assert linear_momentum(N, A, Pa) == 10 * N.x + 500 * N.y
33
+
34
+
35
+ def test_angular_momentum_and_linear_momentum():
36
+ """A rod with length 2l, centroidal inertia I, and mass M along with a
37
+ particle of mass m fixed to the end of the rod rotate with an angular rate
38
+ of omega about point O which is fixed to the non-particle end of the rod.
39
+ The rod's reference frame is A and the inertial frame is N."""
40
+ m, M, l, I = symbols('m, M, l, I')
41
+ omega = dynamicsymbols('omega')
42
+ N = ReferenceFrame('N')
43
+ a = ReferenceFrame('a')
44
+ O = Point('O')
45
+ Ac = O.locatenew('Ac', l * N.x)
46
+ P = Ac.locatenew('P', l * N.x)
47
+ O.set_vel(N, 0 * N.x)
48
+ a.set_ang_vel(N, omega * N.z)
49
+ Ac.v2pt_theory(O, N, a)
50
+ P.v2pt_theory(O, N, a)
51
+ Pa = Particle('Pa', P, m)
52
+ A = RigidBody('A', Ac, a, M, (I * outer(N.z, N.z), Ac))
53
+ expected = 2 * m * omega * l * N.y + M * l * omega * N.y
54
+ assert linear_momentum(N, A, Pa) == expected
55
+ raises(TypeError, lambda: angular_momentum(N, N, A, Pa))
56
+ raises(TypeError, lambda: angular_momentum(O, O, A, Pa))
57
+ raises(TypeError, lambda: angular_momentum(O, N, O, Pa))
58
+ expected = (I + M * l**2 + 4 * m * l**2) * omega * N.z
59
+ assert angular_momentum(O, N, A, Pa) == expected
60
+
61
+
62
+ def test_kinetic_energy():
63
+ m, M, l1 = symbols('m M l1')
64
+ omega = dynamicsymbols('omega')
65
+ N = ReferenceFrame('N')
66
+ O = Point('O')
67
+ O.set_vel(N, 0 * N.x)
68
+ Ac = O.locatenew('Ac', l1 * N.x)
69
+ P = Ac.locatenew('P', l1 * N.x)
70
+ a = ReferenceFrame('a')
71
+ a.set_ang_vel(N, omega * N.z)
72
+ Ac.v2pt_theory(O, N, a)
73
+ P.v2pt_theory(O, N, a)
74
+ Pa = Particle('Pa', P, m)
75
+ I = outer(N.z, N.z)
76
+ A = RigidBody('A', Ac, a, M, (I, Ac))
77
+ raises(TypeError, lambda: kinetic_energy(Pa, Pa, A))
78
+ raises(TypeError, lambda: kinetic_energy(N, N, A))
79
+ assert 0 == (kinetic_energy(N, Pa, A) - (M*l1**2*omega**2/2
80
+ + 2*l1**2*m*omega**2 + omega**2/2)).expand()
81
+
82
+
83
+ def test_potential_energy():
84
+ m, M, l1, g, h, H = symbols('m M l1 g h H')
85
+ omega = dynamicsymbols('omega')
86
+ N = ReferenceFrame('N')
87
+ O = Point('O')
88
+ O.set_vel(N, 0 * N.x)
89
+ Ac = O.locatenew('Ac', l1 * N.x)
90
+ P = Ac.locatenew('P', l1 * N.x)
91
+ a = ReferenceFrame('a')
92
+ a.set_ang_vel(N, omega * N.z)
93
+ Ac.v2pt_theory(O, N, a)
94
+ P.v2pt_theory(O, N, a)
95
+ Pa = Particle('Pa', P, m)
96
+ I = outer(N.z, N.z)
97
+ A = RigidBody('A', Ac, a, M, (I, Ac))
98
+ Pa.potential_energy = m * g * h
99
+ A.potential_energy = M * g * H
100
+ assert potential_energy(A, Pa) == m * g * h + M * g * H
101
+
102
+
103
+ def test_Lagrangian():
104
+ M, m, g, h = symbols('M m g h')
105
+ N = ReferenceFrame('N')
106
+ O = Point('O')
107
+ O.set_vel(N, 0 * N.x)
108
+ P = O.locatenew('P', 1 * N.x)
109
+ P.set_vel(N, 10 * N.x)
110
+ Pa = Particle('Pa', P, 1)
111
+ Ac = O.locatenew('Ac', 2 * N.y)
112
+ Ac.set_vel(N, 5 * N.y)
113
+ a = ReferenceFrame('a')
114
+ a.set_ang_vel(N, 10 * N.z)
115
+ I = outer(N.z, N.z)
116
+ A = RigidBody('A', Ac, a, 20, (I, Ac))
117
+ Pa.potential_energy = m * g * h
118
+ A.potential_energy = M * g * h
119
+ raises(TypeError, lambda: Lagrangian(A, A, Pa))
120
+ raises(TypeError, lambda: Lagrangian(N, N, Pa))
121
+
122
+
123
+ def test_msubs():
124
+ a, b = symbols('a, b')
125
+ x, y, z = dynamicsymbols('x, y, z')
126
+ # Test simple substitution
127
+ expr = Matrix([[a*x + b, x*y.diff() + y],
128
+ [x.diff().diff(), z + sin(z.diff())]])
129
+ sol = Matrix([[a + b, y],
130
+ [x.diff().diff(), 1]])
131
+ sd = {x: 1, z: 1, z.diff(): 0, y.diff(): 0}
132
+ assert msubs(expr, sd) == sol
133
+ # Test smart substitution
134
+ expr = cos(x + y)*tan(x + y) + b*x.diff()
135
+ sd = {x: 0, y: pi/2, x.diff(): 1}
136
+ assert msubs(expr, sd, smart=True) == b + 1
137
+ N = ReferenceFrame('N')
138
+ v = x*N.x + y*N.y
139
+ d = x*(N.x|N.x) + y*(N.y|N.y)
140
+ v_sol = 1*N.y
141
+ d_sol = 1*(N.y|N.y)
142
+ sd = {x: 0, y: 1}
143
+ assert msubs(v, sd) == v_sol
144
+ assert msubs(d, sd) == d_sol
145
+
146
+
147
+ def test_find_dynamicsymbols():
148
+ a, b = symbols('a, b')
149
+ x, y, z = dynamicsymbols('x, y, z')
150
+ expr = Matrix([[a*x + b, x*y.diff() + y],
151
+ [x.diff().diff(), z + sin(z.diff())]])
152
+ # Test finding all dynamicsymbols
153
+ sol = {x, y.diff(), y, x.diff().diff(), z, z.diff()}
154
+ assert find_dynamicsymbols(expr) == sol
155
+ # Test finding all but those in sym_list
156
+ exclude_list = [x, y, z]
157
+ sol = {y.diff(), x.diff().diff(), z.diff()}
158
+ assert find_dynamicsymbols(expr, exclude=exclude_list) == sol
159
+ # Test finding all dynamicsymbols in a vector with a given reference frame
160
+ d, e, f = dynamicsymbols('d, e, f')
161
+ A = ReferenceFrame('A')
162
+ v = d * A.x + e * A.y + f * A.z
163
+ sol = {d, e, f}
164
+ assert find_dynamicsymbols(v, reference_frame=A) == sol
165
+ # Test if a ValueError is raised on supplying only a vector as input
166
+ raises(ValueError, lambda: find_dynamicsymbols(v))
167
+
168
+
169
+ # This function tests the center_of_mass() function
170
+ # that was added in PR #14758 to compute the center of
171
+ # mass of a system of bodies.
172
+ def test_center_of_mass():
173
+ a = ReferenceFrame('a')
174
+ m = symbols('m', real=True)
175
+ p1 = Particle('p1', Point('p1_pt'), S.One)
176
+ p2 = Particle('p2', Point('p2_pt'), S(2))
177
+ p3 = Particle('p3', Point('p3_pt'), S(3))
178
+ p4 = Particle('p4', Point('p4_pt'), m)
179
+ b_f = ReferenceFrame('b_f')
180
+ b_cm = Point('b_cm')
181
+ mb = symbols('mb')
182
+ b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
183
+ p2.point.set_pos(p1.point, a.x)
184
+ p3.point.set_pos(p1.point, a.x + a.y)
185
+ p4.point.set_pos(p1.point, a.y)
186
+ b.masscenter.set_pos(p1.point, a.y + a.z)
187
+ point_o=Point('o')
188
+ point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
189
+ expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
190
+ assert point_o.pos_from(p1.point)-expr == 0
191
+
192
+
193
+ def test_validate_coordinates():
194
+ q1, q2, q3, u1, u2, u3, ua1, ua2, ua3 = dynamicsymbols('q1:4 u1:4 ua1:4')
195
+ s1, s2, s3 = symbols('s1:4')
196
+ # Test normal
197
+ _validate_coordinates([q1, q2, q3], [u1, u2, u3],
198
+ u_auxiliary=[ua1, ua2, ua3])
199
+ # Test not equal number of coordinates and speeds
200
+ _validate_coordinates([q1, q2])
201
+ _validate_coordinates([q1, q2], [u1])
202
+ _validate_coordinates(speeds=[u1, u2])
203
+ # Test duplicate
204
+ _validate_coordinates([q1, q2, q2], [u1, u2, u3], check_duplicates=False)
205
+ raises(ValueError, lambda: _validate_coordinates(
206
+ [q1, q2, q2], [u1, u2, u3]))
207
+ _validate_coordinates([q1, q2, q3], [u1, u2, u2], check_duplicates=False)
208
+ raises(ValueError, lambda: _validate_coordinates(
209
+ [q1, q2, q3], [u1, u2, u2], check_duplicates=True))
210
+ raises(ValueError, lambda: _validate_coordinates(
211
+ [q1, q2, q3], [q1, u2, u3], check_duplicates=True))
212
+ _validate_coordinates([q1, q2, q3], [u1, u2, u3], check_duplicates=False,
213
+ u_auxiliary=[u1, ua2, ua2])
214
+ raises(ValueError, lambda: _validate_coordinates(
215
+ [q1, q2, q3], [u1, u2, u3], u_auxiliary=[u1, ua2, ua3]))
216
+ raises(ValueError, lambda: _validate_coordinates(
217
+ [q1, q2, q3], [u1, u2, u3], u_auxiliary=[q1, ua2, ua3]))
218
+ raises(ValueError, lambda: _validate_coordinates(
219
+ [q1, q2, q3], [u1, u2, u3], u_auxiliary=[ua1, ua2, ua2]))
220
+ # Test is_dynamicsymbols
221
+ _validate_coordinates([q1 + q2, q3], is_dynamicsymbols=False)
222
+ raises(ValueError, lambda: _validate_coordinates([q1 + q2, q3]))
223
+ _validate_coordinates([s1, q1, q2], [0, u1, u2], is_dynamicsymbols=False)
224
+ raises(ValueError, lambda: _validate_coordinates(
225
+ [s1, q1, q2], [0, u1, u2], is_dynamicsymbols=True))
226
+ _validate_coordinates([s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=False)
227
+ raises(ValueError, lambda: _validate_coordinates(
228
+ [s1 + s2 + s3, q1], [0, u1], is_dynamicsymbols=True))
229
+ _validate_coordinates(u_auxiliary=[s1, ua1], is_dynamicsymbols=False)
230
+ raises(ValueError, lambda: _validate_coordinates(u_auxiliary=[s1, ua1]))
231
+ # Test normal function
232
+ t = dynamicsymbols._t
233
+ a = symbols('a')
234
+ f1, f2 = symbols('f1:3', cls=Function)
235
+ _validate_coordinates([f1(a), f2(a)], is_dynamicsymbols=False)
236
+ raises(ValueError, lambda: _validate_coordinates([f1(a), f2(a)]))
237
+ raises(ValueError, lambda: _validate_coordinates(speeds=[f1(a), f2(a)]))
238
+ dynamicsymbols._t = a
239
+ _validate_coordinates([f1(a), f2(a)])
240
+ raises(ValueError, lambda: _validate_coordinates([f1(t), f2(t)]))
241
+ dynamicsymbols._t = t
242
+
243
+
244
+ def test_parse_linear_solver():
245
+ A, b = Matrix(3, 3, symbols('a:9')), Matrix(3, 2, symbols('b:6'))
246
+ assert _parse_linear_solver(Matrix.LUsolve) == Matrix.LUsolve # Test callable
247
+ assert _parse_linear_solver('LU')(A, b) == Matrix.LUsolve(A, b)
248
+
249
+
250
+ def test_deprecated_moved_functions():
251
+ from sympy.physics.mechanics.functions import (
252
+ inertia, inertia_of_point_mass, gravity)
253
+ N = ReferenceFrame('N')
254
+ with warns_deprecated_sympy():
255
+ assert inertia(N, 0, 1, 0, 1) == (N.x | N.y) + (N.y | N.x) + (N.y | N.y)
256
+ with warns_deprecated_sympy():
257
+ assert inertia_of_point_mass(1, N.x + N.y, N) == (
258
+ (N.x | N.x) + (N.y | N.y) + 2 * (N.z | N.z) -
259
+ (N.x | N.y) - (N.y | N.x))
260
+ p = Particle('P')
261
+ with warns_deprecated_sympy():
262
+ assert gravity(-2 * N.z, p) == [(p.masscenter, -2 * p.mass * N.z)]
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import solve
2
+ from sympy import (cos, expand, Matrix, sin, symbols, tan, sqrt, S,
3
+ zeros, eye)
4
+ from sympy.simplify.simplify import simplify
5
+ from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
6
+ RigidBody, KanesMethod, inertia, Particle,
7
+ dot, find_dynamicsymbols)
8
+ from sympy.testing.pytest import raises
9
+
10
+
11
+ def test_invalid_coordinates():
12
+ # Simple pendulum, but use symbols instead of dynamicsymbols
13
+ l, m, g = symbols('l m g')
14
+ q, u = symbols('q u') # Generalized coordinate
15
+ kd = [q.diff(dynamicsymbols._t) - u]
16
+ N, O = ReferenceFrame('N'), Point('O')
17
+ O.set_vel(N, 0)
18
+ P = Particle('P', Point('P'), m)
19
+ P.point.set_pos(O, l * (sin(q) * N.x - cos(q) * N.y))
20
+ F = (P.point, -m * g * N.y)
21
+ raises(ValueError, lambda: KanesMethod(N, [q], [u], kd, bodies=[P],
22
+ forcelist=[F]))
23
+
24
+
25
+ def test_one_dof():
26
+ # This is for a 1 dof spring-mass-damper case.
27
+ # It is described in more detail in the KanesMethod docstring.
28
+ q, u = dynamicsymbols('q u')
29
+ qd, ud = dynamicsymbols('q u', 1)
30
+ m, c, k = symbols('m c k')
31
+ N = ReferenceFrame('N')
32
+ P = Point('P')
33
+ P.set_vel(N, u * N.x)
34
+
35
+ kd = [qd - u]
36
+ FL = [(P, (-k * q - c * u) * N.x)]
37
+ pa = Particle('pa', P, m)
38
+ BL = [pa]
39
+
40
+ KM = KanesMethod(N, [q], [u], kd)
41
+ KM.kanes_equations(BL, FL)
42
+
43
+ assert KM.bodies == BL
44
+ assert KM.loads == FL
45
+
46
+ MM = KM.mass_matrix
47
+ forcing = KM.forcing
48
+ rhs = MM.inv() * forcing
49
+ assert expand(rhs[0]) == expand(-(q * k + u * c) / m)
50
+
51
+ assert simplify(KM.rhs() -
52
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
53
+
54
+ assert (KM.linearize(A_and_B=True, )[0] == Matrix([[0, 1], [-k/m, -c/m]]))
55
+
56
+
57
+ def test_two_dof():
58
+ # This is for a 2 d.o.f., 2 particle spring-mass-damper.
59
+ # The first coordinate is the displacement of the first particle, and the
60
+ # second is the relative displacement between the first and second
61
+ # particles. Speeds are defined as the time derivatives of the particles.
62
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
63
+ q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
64
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
65
+ N = ReferenceFrame('N')
66
+ P1 = Point('P1')
67
+ P2 = Point('P2')
68
+ P1.set_vel(N, u1 * N.x)
69
+ P2.set_vel(N, (u1 + u2) * N.x)
70
+ # Note we multiply the kinematic equation by an arbitrary factor
71
+ # to test the implicit vs explicit kinematics attribute
72
+ kd = [q1d/2 - u1/2, 2*q2d - 2*u2]
73
+
74
+ # Now we create the list of forces, then assign properties to each
75
+ # particle, then create a list of all particles.
76
+ FL = [(P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
77
+ q2 - c2 * u2) * N.x)]
78
+ pa1 = Particle('pa1', P1, m)
79
+ pa2 = Particle('pa2', P2, m)
80
+ BL = [pa1, pa2]
81
+
82
+ # Finally we create the KanesMethod object, specify the inertial frame,
83
+ # pass relevant information, and form Fr & Fr*. Then we calculate the mass
84
+ # matrix and forcing terms, and finally solve for the udots.
85
+ KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
86
+ KM.kanes_equations(BL, FL)
87
+ MM = KM.mass_matrix
88
+ forcing = KM.forcing
89
+ rhs = MM.inv() * forcing
90
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
91
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
92
+ c2 * u2) / m)
93
+
94
+ # Check that the explicit form is the default and kinematic mass matrix is identity
95
+ assert KM.explicit_kinematics
96
+ assert KM.mass_matrix_kin == eye(2)
97
+
98
+ # Check that for the implicit form the mass matrix is not identity
99
+ KM.explicit_kinematics = False
100
+ assert KM.mass_matrix_kin == Matrix([[S(1)/2, 0], [0, 2]])
101
+
102
+ # Check that whether using implicit or explicit kinematics the RHS
103
+ # equations are consistent with the matrix form
104
+ for explicit_kinematics in [False, True]:
105
+ KM.explicit_kinematics = explicit_kinematics
106
+ assert simplify(KM.rhs() -
107
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(4, 1)
108
+
109
+ # Make sure an error is raised if nonlinear kinematic differential
110
+ # equations are supplied.
111
+ kd = [q1d - u1**2, sin(q2d) - cos(u2)]
112
+ raises(ValueError, lambda: KanesMethod(N, q_ind=[q1, q2],
113
+ u_ind=[u1, u2], kd_eqs=kd))
114
+
115
+ def test_pend():
116
+ q, u = dynamicsymbols('q u')
117
+ qd, ud = dynamicsymbols('q u', 1)
118
+ m, l, g = symbols('m l g')
119
+ N = ReferenceFrame('N')
120
+ P = Point('P')
121
+ P.set_vel(N, -l * u * sin(q) * N.x + l * u * cos(q) * N.y)
122
+ kd = [qd - u]
123
+
124
+ FL = [(P, m * g * N.x)]
125
+ pa = Particle('pa', P, m)
126
+ BL = [pa]
127
+
128
+ KM = KanesMethod(N, [q], [u], kd)
129
+ KM.kanes_equations(BL, FL)
130
+ MM = KM.mass_matrix
131
+ forcing = KM.forcing
132
+ rhs = MM.inv() * forcing
133
+ rhs.simplify()
134
+ assert expand(rhs[0]) == expand(-g / l * sin(q))
135
+ assert simplify(KM.rhs() -
136
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(2, 1)
137
+
138
+
139
+ def test_rolling_disc():
140
+ # Rolling Disc Example
141
+ # Here the rolling disc is formed from the contact point up, removing the
142
+ # need to introduce generalized speeds. Only 3 configuration and three
143
+ # speed variables are need to describe this system, along with the disc's
144
+ # mass and radius, and the local gravity (note that mass will drop out).
145
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
146
+ q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
147
+ r, m, g = symbols('r m g')
148
+
149
+ # The kinematics are formed by a series of simple rotations. Each simple
150
+ # rotation creates a new frame, and the next rotation is defined by the new
151
+ # frame's basis vectors. This example uses a 3-1-2 series of rotations, or
152
+ # Z, X, Y series of rotations. Angular velocity for this is defined using
153
+ # the second frame's basis (the lean frame).
154
+ N = ReferenceFrame('N')
155
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
156
+ L = Y.orientnew('L', 'Axis', [q2, Y.x])
157
+ R = L.orientnew('R', 'Axis', [q3, L.y])
158
+ w_R_N_qd = R.ang_vel_in(N)
159
+ R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
160
+
161
+ # This is the translational kinematics. We create a point with no velocity
162
+ # in N; this is the contact point between the disc and ground. Next we form
163
+ # the position vector from the contact point to the disc's center of mass.
164
+ # Finally we form the velocity and acceleration of the disc.
165
+ C = Point('C')
166
+ C.set_vel(N, 0)
167
+ Dmc = C.locatenew('Dmc', r * L.z)
168
+ Dmc.v2pt_theory(C, N, R)
169
+
170
+ # This is a simple way to form the inertia dyadic.
171
+ I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
172
+
173
+ # Kinematic differential equations; how the generalized coordinate time
174
+ # derivatives relate to generalized speeds.
175
+ kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
176
+
177
+ # Creation of the force list; it is the gravitational force at the mass
178
+ # center of the disc. Then we create the disc by assigning a Point to the
179
+ # center of mass attribute, a ReferenceFrame to the frame attribute, and mass
180
+ # and inertia. Then we form the body list.
181
+ ForceList = [(Dmc, - m * g * Y.z)]
182
+ BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
183
+ BodyList = [BodyD]
184
+
185
+ # Finally we form the equations of motion, using the same steps we did
186
+ # before. Specify inertial frame, supply generalized speeds, supply
187
+ # kinematic differential equation dictionary, compute Fr from the force
188
+ # list and Fr* from the body list, compute the mass matrix and forcing
189
+ # terms, then solve for the u dots (time derivatives of the generalized
190
+ # speeds).
191
+ KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd)
192
+ KM.kanes_equations(BodyList, ForceList)
193
+ MM = KM.mass_matrix
194
+ forcing = KM.forcing
195
+ rhs = MM.inv() * forcing
196
+ kdd = KM.kindiffdict()
197
+ rhs = rhs.subs(kdd)
198
+ rhs.simplify()
199
+ assert rhs.expand() == Matrix([(6*u2*u3*r - u3**2*r*tan(q2) +
200
+ 4*g*sin(q2))/(5*r), -2*u1*u3/3, u1*(-2*u2 + u3*tan(q2))]).expand()
201
+ assert simplify(KM.rhs() -
202
+ KM.mass_matrix_full.LUsolve(KM.forcing_full)) == zeros(6, 1)
203
+
204
+ # This code tests our output vs. benchmark values. When r=g=m=1, the
205
+ # critical speed (where all eigenvalues of the linearized equations are 0)
206
+ # is 1 / sqrt(3) for the upright case.
207
+ A = KM.linearize(A_and_B=True)[0]
208
+ A_upright = A.subs({r: 1, g: 1, m: 1}).subs({q1: 0, q2: 0, q3: 0, u1: 0, u3: 0})
209
+ import sympy
210
+ assert sympy.sympify(A_upright.subs({u2: 1 / sqrt(3)})).eigenvals() == {S.Zero: 6}
211
+
212
+
213
+ def test_aux():
214
+ # Same as above, except we have 2 auxiliary speeds for the ground contact
215
+ # point, which is known to be zero. In one case, we go through then
216
+ # substitute the aux. speeds in at the end (they are zero, as well as their
217
+ # derivative), in the other case, we use the built-in auxiliary speed part
218
+ # of KanesMethod. The equations from each should be the same.
219
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
220
+ q1d, q2d, q3d, u1d, u2d, u3d = dynamicsymbols('q1 q2 q3 u1 u2 u3', 1)
221
+ u4, u5, f1, f2 = dynamicsymbols('u4, u5, f1, f2')
222
+ u4d, u5d = dynamicsymbols('u4, u5', 1)
223
+ r, m, g = symbols('r m g')
224
+
225
+ N = ReferenceFrame('N')
226
+ Y = N.orientnew('Y', 'Axis', [q1, N.z])
227
+ L = Y.orientnew('L', 'Axis', [q2, Y.x])
228
+ R = L.orientnew('R', 'Axis', [q3, L.y])
229
+ w_R_N_qd = R.ang_vel_in(N)
230
+ R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
231
+
232
+ C = Point('C')
233
+ C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
234
+ Dmc = C.locatenew('Dmc', r * L.z)
235
+ Dmc.v2pt_theory(C, N, R)
236
+ Dmc.a2pt_theory(C, N, R)
237
+
238
+ I = inertia(L, m / 4 * r**2, m / 2 * r**2, m / 4 * r**2)
239
+
240
+ kd = [dot(R.ang_vel_in(N) - w_R_N_qd, uv) for uv in L]
241
+
242
+ ForceList = [(Dmc, - m * g * Y.z), (C, f1 * L.x + f2 * (Y.z ^ L.x))]
243
+ BodyD = RigidBody('BodyD', Dmc, R, m, (I, Dmc))
244
+ BodyList = [BodyD]
245
+
246
+ KM = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3, u4, u5],
247
+ kd_eqs=kd)
248
+ (fr, frstar) = KM.kanes_equations(BodyList, ForceList)
249
+ fr = fr.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
250
+ frstar = frstar.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
251
+
252
+ KM2 = KanesMethod(N, q_ind=[q1, q2, q3], u_ind=[u1, u2, u3], kd_eqs=kd,
253
+ u_auxiliary=[u4, u5])
254
+ (fr2, frstar2) = KM2.kanes_equations(BodyList, ForceList)
255
+ fr2 = fr2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
256
+ frstar2 = frstar2.subs({u4d: 0, u5d: 0}).subs({u4: 0, u5: 0})
257
+
258
+ frstar.simplify()
259
+ frstar2.simplify()
260
+
261
+ assert (fr - fr2).expand() == Matrix([0, 0, 0, 0, 0])
262
+ assert (frstar - frstar2).expand() == Matrix([0, 0, 0, 0, 0])
263
+
264
+
265
+ def test_parallel_axis():
266
+ # This is for a 2 dof inverted pendulum on a cart.
267
+ # This tests the parallel axis code in KanesMethod. The inertia of the
268
+ # pendulum is defined about the hinge, not about the center of mass.
269
+
270
+ # Defining the constants and knowns of the system
271
+ gravity = symbols('g')
272
+ k, ls = symbols('k ls')
273
+ a, mA, mC = symbols('a mA mC')
274
+ F = dynamicsymbols('F')
275
+ Ix, Iy, Iz = symbols('Ix Iy Iz')
276
+
277
+ # Declaring the Generalized coordinates and speeds
278
+ q1, q2 = dynamicsymbols('q1 q2')
279
+ q1d, q2d = dynamicsymbols('q1 q2', 1)
280
+ u1, u2 = dynamicsymbols('u1 u2')
281
+ u1d, u2d = dynamicsymbols('u1 u2', 1)
282
+
283
+ # Creating reference frames
284
+ N = ReferenceFrame('N')
285
+ A = ReferenceFrame('A')
286
+
287
+ A.orient(N, 'Axis', [-q2, N.z])
288
+ A.set_ang_vel(N, -u2 * N.z)
289
+
290
+ # Origin of Newtonian reference frame
291
+ O = Point('O')
292
+
293
+ # Creating and Locating the positions of the cart, C, and the
294
+ # center of mass of the pendulum, A
295
+ C = O.locatenew('C', q1 * N.x)
296
+ Ao = C.locatenew('Ao', a * A.y)
297
+
298
+ # Defining velocities of the points
299
+ O.set_vel(N, 0)
300
+ C.set_vel(N, u1 * N.x)
301
+ Ao.v2pt_theory(C, N, A)
302
+ Cart = Particle('Cart', C, mC)
303
+ Pendulum = RigidBody('Pendulum', Ao, A, mA, (inertia(A, Ix, Iy, Iz), C))
304
+
305
+ # kinematical differential equations
306
+
307
+ kindiffs = [q1d - u1, q2d - u2]
308
+
309
+ bodyList = [Cart, Pendulum]
310
+
311
+ forceList = [(Ao, -N.y * gravity * mA),
312
+ (C, -N.y * gravity * mC),
313
+ (C, -N.x * k * (q1 - ls)),
314
+ (C, N.x * F)]
315
+
316
+ km = KanesMethod(N, [q1, q2], [u1, u2], kindiffs)
317
+ (fr, frstar) = km.kanes_equations(bodyList, forceList)
318
+ mm = km.mass_matrix_full
319
+ assert mm[3, 3] == Iz
320
+
321
+ def test_input_format():
322
+ # 1 dof problem from test_one_dof
323
+ q, u = dynamicsymbols('q u')
324
+ qd, ud = dynamicsymbols('q u', 1)
325
+ m, c, k = symbols('m c k')
326
+ N = ReferenceFrame('N')
327
+ P = Point('P')
328
+ P.set_vel(N, u * N.x)
329
+
330
+ kd = [qd - u]
331
+ FL = [(P, (-k * q - c * u) * N.x)]
332
+ pa = Particle('pa', P, m)
333
+ BL = [pa]
334
+
335
+ KM = KanesMethod(N, [q], [u], kd)
336
+ # test for input format kane.kanes_equations((body1, body2, particle1))
337
+ assert KM.kanes_equations(BL)[0] == Matrix([0])
338
+ # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=(load1,load2))
339
+ assert KM.kanes_equations(bodies=BL, loads=None)[0] == Matrix([0])
340
+ # test for input format kane.kanes_equations(bodies=(body1, body 2), loads=None)
341
+ assert KM.kanes_equations(BL, loads=None)[0] == Matrix([0])
342
+ # test for input format kane.kanes_equations(bodies=(body1, body 2))
343
+ assert KM.kanes_equations(BL)[0] == Matrix([0])
344
+ # test for input format kane.kanes_equations(bodies=(body1, body2), loads=[])
345
+ assert KM.kanes_equations(BL, [])[0] == Matrix([0])
346
+ # test for error raised when a wrong force list (in this case a string) is provided
347
+ raises(ValueError, lambda: KM._form_fr('bad input'))
348
+
349
+ # 1 dof problem from test_one_dof with FL & BL in instance
350
+ KM = KanesMethod(N, [q], [u], kd, bodies=BL, forcelist=FL)
351
+ assert KM.kanes_equations()[0] == Matrix([-c*u - k*q])
352
+
353
+ # 2 dof problem from test_two_dof
354
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
355
+ q1d, q2d, u1d, u2d = dynamicsymbols('q1 q2 u1 u2', 1)
356
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
357
+ N = ReferenceFrame('N')
358
+ P1 = Point('P1')
359
+ P2 = Point('P2')
360
+ P1.set_vel(N, u1 * N.x)
361
+ P2.set_vel(N, (u1 + u2) * N.x)
362
+ kd = [q1d - u1, q2d - u2]
363
+
364
+ FL = ((P1, (-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2) * N.x), (P2, (-k2 *
365
+ q2 - c2 * u2) * N.x))
366
+ pa1 = Particle('pa1', P1, m)
367
+ pa2 = Particle('pa2', P2, m)
368
+ BL = (pa1, pa2)
369
+
370
+ KM = KanesMethod(N, q_ind=[q1, q2], u_ind=[u1, u2], kd_eqs=kd)
371
+ # test for input format
372
+ # kane.kanes_equations((body1, body2), (load1, load2))
373
+ KM.kanes_equations(BL, FL)
374
+ MM = KM.mass_matrix
375
+ forcing = KM.forcing
376
+ rhs = MM.inv() * forcing
377
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
378
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
379
+ c2 * u2) / m)
380
+
381
+
382
+ def test_implicit_kinematics():
383
+ # Test that implicit kinematics can handle complicated
384
+ # equations that explicit form struggles with
385
+ # See https://github.com/sympy/sympy/issues/22626
386
+
387
+ # Inertial frame
388
+ NED = ReferenceFrame('NED')
389
+ NED_o = Point('NED_o')
390
+ NED_o.set_vel(NED, 0)
391
+
392
+ # body frame
393
+ q_att = dynamicsymbols('lambda_0:4', real=True)
394
+ B = NED.orientnew('B', 'Quaternion', q_att)
395
+
396
+ # Generalized coordinates
397
+ q_pos = dynamicsymbols('B_x:z')
398
+ B_cm = NED_o.locatenew('B_cm', q_pos[0]*B.x + q_pos[1]*B.y + q_pos[2]*B.z)
399
+
400
+ q_ind = q_att[1:] + q_pos
401
+ q_dep = [q_att[0]]
402
+
403
+ kinematic_eqs = []
404
+
405
+ # Generalized velocities
406
+ B_ang_vel = B.ang_vel_in(NED)
407
+ P, Q, R = dynamicsymbols('P Q R')
408
+ B.set_ang_vel(NED, P*B.x + Q*B.y + R*B.z)
409
+
410
+ B_ang_vel_kd = (B.ang_vel_in(NED) - B_ang_vel).simplify()
411
+
412
+ # Equating the two gives us the kinematic equation
413
+ kinematic_eqs += [
414
+ B_ang_vel_kd & B.x,
415
+ B_ang_vel_kd & B.y,
416
+ B_ang_vel_kd & B.z
417
+ ]
418
+
419
+ B_cm_vel = B_cm.vel(NED)
420
+ U, V, W = dynamicsymbols('U V W')
421
+ B_cm.set_vel(NED, U*B.x + V*B.y + W*B.z)
422
+
423
+ # Compute the velocity of the point using the two methods
424
+ B_ref_vel_kd = (B_cm.vel(NED) - B_cm_vel)
425
+
426
+ # taking dot product with unit vectors to get kinematic equations
427
+ # relating body coordinates and velocities
428
+
429
+ # Note, there is a choice to dot with NED.xyz here. That makes
430
+ # the implicit form have some bigger terms but is still fine, the
431
+ # explicit form still struggles though
432
+ kinematic_eqs += [
433
+ B_ref_vel_kd & B.x,
434
+ B_ref_vel_kd & B.y,
435
+ B_ref_vel_kd & B.z,
436
+ ]
437
+
438
+ u_ind = [U, V, W, P, Q, R]
439
+
440
+ # constraints
441
+ q_att_vec = Matrix(q_att)
442
+ config_cons = [(q_att_vec.T*q_att_vec)[0] - 1] #unit norm
443
+ kinematic_eqs = kinematic_eqs + [(q_att_vec.T * q_att_vec.diff())[0]]
444
+
445
+ try:
446
+ KM = KanesMethod(NED, q_ind, u_ind,
447
+ q_dependent= q_dep,
448
+ kd_eqs = kinematic_eqs,
449
+ configuration_constraints = config_cons,
450
+ velocity_constraints= [],
451
+ u_dependent= [], #no dependent speeds
452
+ u_auxiliary = [], # No auxiliary speeds
453
+ explicit_kinematics = False # implicit kinematics
454
+ )
455
+ except Exception as e:
456
+ raise e
457
+
458
+ # mass and inertia dyadic relative to CM
459
+ M_B = symbols('M_B')
460
+ J_B = inertia(B, *[S(f'J_B_{ax}')*(1 if ax[0] == ax[1] else -1)
461
+ for ax in ['xx', 'yy', 'zz', 'xy', 'yz', 'xz']])
462
+ J_B = J_B.subs({S('J_B_xy'): 0, S('J_B_yz'): 0})
463
+ RB = RigidBody('RB', B_cm, B, M_B, (J_B, B_cm))
464
+
465
+ rigid_bodies = [RB]
466
+ # Forces
467
+ force_list = [
468
+ #gravity pointing down
469
+ (RB.masscenter, RB.mass*S('g')*NED.z),
470
+ #generic forces and torques in body frame(inputs)
471
+ (RB.frame, dynamicsymbols('T_z')*B.z),
472
+ (RB.masscenter, dynamicsymbols('F_z')*B.z)
473
+ ]
474
+
475
+ KM.kanes_equations(rigid_bodies, force_list)
476
+
477
+ # Expecting implicit form to be less than 5% of the flops
478
+ n_ops_implicit = sum(
479
+ [x.count_ops() for x in KM.forcing_full] +
480
+ [x.count_ops() for x in KM.mass_matrix_full]
481
+ )
482
+ # Save implicit kinematic matrices to use later
483
+ mass_matrix_kin_implicit = KM.mass_matrix_kin
484
+ forcing_kin_implicit = KM.forcing_kin
485
+
486
+ KM.explicit_kinematics = True
487
+ n_ops_explicit = sum(
488
+ [x.count_ops() for x in KM.forcing_full] +
489
+ [x.count_ops() for x in KM.mass_matrix_full]
490
+ )
491
+ forcing_kin_explicit = KM.forcing_kin
492
+
493
+ assert n_ops_implicit / n_ops_explicit < .05
494
+
495
+ # Ideally we would check that implicit and explicit equations give the same result as done in test_one_dof
496
+ # But the whole raison-d'etre of the implicit equations is to deal with problems such
497
+ # as this one where the explicit form is too complicated to handle, especially the angular part
498
+ # (i.e. tests would be too slow)
499
+ # Instead, we check that the kinematic equations are correct using more fundamental tests:
500
+ #
501
+ # (1) that we recover the kinematic equations we have provided
502
+ assert (mass_matrix_kin_implicit * KM.q.diff() - forcing_kin_implicit) == Matrix(kinematic_eqs)
503
+
504
+ # (2) that rate of quaternions matches what 'textbook' solutions give
505
+ # Note that we just use the explicit kinematics for the linear velocities
506
+ # as they are not as complicated as the angular ones
507
+ qdot_candidate = forcing_kin_explicit
508
+
509
+ quat_dot_textbook = Matrix([
510
+ [0, -P, -Q, -R],
511
+ [P, 0, R, -Q],
512
+ [Q, -R, 0, P],
513
+ [R, Q, -P, 0],
514
+ ]) * q_att_vec / 2
515
+
516
+ # Again, if we don't use this "textbook" solution
517
+ # sympy will struggle to deal with the terms related to quaternion rates
518
+ # due to the number of operations involved
519
+ qdot_candidate[-1] = quat_dot_textbook[0] # lambda_0, note the [-1] as sympy's Kane puts the dependent coordinate last
520
+ qdot_candidate[0] = quat_dot_textbook[1] # lambda_1
521
+ qdot_candidate[1] = quat_dot_textbook[2] # lambda_2
522
+ qdot_candidate[2] = quat_dot_textbook[3] # lambda_3
523
+
524
+ # sub the config constraint in the candidate solution and compare to the implicit rhs
525
+ lambda_0_sol = solve(config_cons[0], q_att_vec[0])[1]
526
+ lhs_candidate = simplify(mass_matrix_kin_implicit * qdot_candidate).subs({q_att_vec[0]: lambda_0_sol})
527
+ assert lhs_candidate == forcing_kin_implicit
528
+
529
+ def test_issue_24887():
530
+ # Spherical pendulum
531
+ g, l, m, c = symbols('g l m c')
532
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4 u1:4')
533
+ N = ReferenceFrame('N')
534
+ A = ReferenceFrame('A')
535
+ A.orient_body_fixed(N, (q1, q2, q3), 'zxy')
536
+ N_w_A = A.ang_vel_in(N)
537
+ # A.set_ang_vel(N, u1 * A.x + u2 * A.y + u3 * A.z)
538
+ kdes = [N_w_A.dot(A.x) - u1, N_w_A.dot(A.y) - u2, N_w_A.dot(A.z) - u3]
539
+ O = Point('O')
540
+ O.set_vel(N, 0)
541
+ Po = O.locatenew('Po', -l * A.y)
542
+ Po.set_vel(A, 0)
543
+ P = Particle('P', Po, m)
544
+ kane = KanesMethod(N, [q1, q2, q3], [u1, u2, u3], kdes, bodies=[P],
545
+ forcelist=[(Po, -m * g * N.y)])
546
+ kane.kanes_equations()
547
+ expected_md = m * l ** 2 * Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 1]])
548
+ expected_fd = Matrix([
549
+ [l*m*(g*(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)) - l*u2*u3)],
550
+ [0], [l*m*(-g*(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)) + l*u1*u2)]])
551
+ assert find_dynamicsymbols(kane.forcing).issubset({q1, q2, q3, u1, u2, u3})
552
+ assert simplify(kane.mass_matrix - expected_md) == zeros(3, 3)
553
+ assert simplify(kane.forcing - expected_fd) == zeros(3, 1)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import symbols
2
+ from sympy.physics.mechanics import dynamicsymbols
3
+ from sympy.physics.mechanics import ReferenceFrame, Point, Particle
4
+ from sympy.physics.mechanics import LagrangesMethod, Lagrangian
5
+
6
+ ### This test asserts that a system with more than one external forces
7
+ ### is acurately formed with Lagrange method (see issue #8626)
8
+
9
+ def test_lagrange_2forces():
10
+ ### Equations for two damped springs in serie with two forces
11
+
12
+ ### generalized coordinates
13
+ q1, q2 = dynamicsymbols('q1, q2')
14
+ ### generalized speeds
15
+ q1d, q2d = dynamicsymbols('q1, q2', 1)
16
+
17
+ ### Mass, spring strength, friction coefficient
18
+ m, k, nu = symbols('m, k, nu')
19
+
20
+ N = ReferenceFrame('N')
21
+ O = Point('O')
22
+
23
+ ### Two points
24
+ P1 = O.locatenew('P1', q1 * N.x)
25
+ P1.set_vel(N, q1d * N.x)
26
+ P2 = O.locatenew('P1', q2 * N.x)
27
+ P2.set_vel(N, q2d * N.x)
28
+
29
+ pP1 = Particle('pP1', P1, m)
30
+ pP1.potential_energy = k * q1**2 / 2
31
+
32
+ pP2 = Particle('pP2', P2, m)
33
+ pP2.potential_energy = k * (q1 - q2)**2 / 2
34
+
35
+ #### Friction forces
36
+ forcelist = [(P1, - nu * q1d * N.x),
37
+ (P2, - nu * q2d * N.x)]
38
+ lag = Lagrangian(N, pP1, pP2)
39
+
40
+ l_method = LagrangesMethod(lag, (q1, q2), forcelist=forcelist, frame=N)
41
+ l_method.form_lagranges_equations()
42
+
43
+ eq1 = l_method.eom[0]
44
+ assert eq1.diff(q1d) == nu
45
+ eq2 = l_method.eom[1]
46
+ assert eq2.diff(q2d) == nu
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from sympy.physics.mechanics.method import _Methods
2
+ from sympy.testing.pytest import raises
3
+
4
+ def test_method():
5
+ raises(TypeError, lambda: _Methods())
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sympy.physics.mechanics.models as models
2
+ from sympy import (cos, sin, Matrix, symbols, zeros)
3
+ from sympy.simplify.simplify import simplify
4
+ from sympy.physics.mechanics import (dynamicsymbols)
5
+
6
+
7
+ def test_multi_mass_spring_damper_inputs():
8
+
9
+ c0, k0, m0 = symbols("c0 k0 m0")
10
+ g = symbols("g")
11
+ v0, x0, f0 = dynamicsymbols("v0 x0 f0")
12
+
13
+ kane1 = models.multi_mass_spring_damper(1)
14
+ massmatrix1 = Matrix([[m0]])
15
+ forcing1 = Matrix([[-c0*v0 - k0*x0]])
16
+ assert simplify(massmatrix1 - kane1.mass_matrix) == Matrix([0])
17
+ assert simplify(forcing1 - kane1.forcing) == Matrix([0])
18
+
19
+ kane2 = models.multi_mass_spring_damper(1, True)
20
+ massmatrix2 = Matrix([[m0]])
21
+ forcing2 = Matrix([[-c0*v0 + g*m0 - k0*x0]])
22
+ assert simplify(massmatrix2 - kane2.mass_matrix) == Matrix([0])
23
+ assert simplify(forcing2 - kane2.forcing) == Matrix([0])
24
+
25
+ kane3 = models.multi_mass_spring_damper(1, True, True)
26
+ massmatrix3 = Matrix([[m0]])
27
+ forcing3 = Matrix([[-c0*v0 + g*m0 - k0*x0 + f0]])
28
+ assert simplify(massmatrix3 - kane3.mass_matrix) == Matrix([0])
29
+ assert simplify(forcing3 - kane3.forcing) == Matrix([0])
30
+
31
+ kane4 = models.multi_mass_spring_damper(1, False, True)
32
+ massmatrix4 = Matrix([[m0]])
33
+ forcing4 = Matrix([[-c0*v0 - k0*x0 + f0]])
34
+ assert simplify(massmatrix4 - kane4.mass_matrix) == Matrix([0])
35
+ assert simplify(forcing4 - kane4.forcing) == Matrix([0])
36
+
37
+
38
+ def test_multi_mass_spring_damper_higher_order():
39
+ c0, k0, m0 = symbols("c0 k0 m0")
40
+ c1, k1, m1 = symbols("c1 k1 m1")
41
+ c2, k2, m2 = symbols("c2 k2 m2")
42
+ v0, x0 = dynamicsymbols("v0 x0")
43
+ v1, x1 = dynamicsymbols("v1 x1")
44
+ v2, x2 = dynamicsymbols("v2 x2")
45
+
46
+ kane1 = models.multi_mass_spring_damper(3)
47
+ massmatrix1 = Matrix([[m0 + m1 + m2, m1 + m2, m2],
48
+ [m1 + m2, m1 + m2, m2],
49
+ [m2, m2, m2]])
50
+ forcing1 = Matrix([[-c0*v0 - k0*x0],
51
+ [-c1*v1 - k1*x1],
52
+ [-c2*v2 - k2*x2]])
53
+ assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
54
+ assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
55
+
56
+
57
+ def test_n_link_pendulum_on_cart_inputs():
58
+ l0, m0 = symbols("l0 m0")
59
+ m1 = symbols("m1")
60
+ g = symbols("g")
61
+ q0, q1, F, T1 = dynamicsymbols("q0 q1 F T1")
62
+ u0, u1 = dynamicsymbols("u0 u1")
63
+
64
+ kane1 = models.n_link_pendulum_on_cart(1)
65
+ massmatrix1 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
66
+ [-l0*m1*cos(q1), l0**2*m1]])
67
+ forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
68
+ assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(2)
69
+ assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0])
70
+
71
+ kane2 = models.n_link_pendulum_on_cart(1, False)
72
+ massmatrix2 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
73
+ [-l0*m1*cos(q1), l0**2*m1]])
74
+ forcing2 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1)]])
75
+ assert simplify(massmatrix2 - kane2.mass_matrix) == zeros(2)
76
+ assert simplify(forcing2 - kane2.forcing) == Matrix([0, 0])
77
+
78
+ kane3 = models.n_link_pendulum_on_cart(1, False, True)
79
+ massmatrix3 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
80
+ [-l0*m1*cos(q1), l0**2*m1]])
81
+ forcing3 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1) + T1]])
82
+ assert simplify(massmatrix3 - kane3.mass_matrix) == zeros(2)
83
+ assert simplify(forcing3 - kane3.forcing) == Matrix([0, 0])
84
+
85
+ kane4 = models.n_link_pendulum_on_cart(1, True, False)
86
+ massmatrix4 = Matrix([[m0 + m1, -l0*m1*cos(q1)],
87
+ [-l0*m1*cos(q1), l0**2*m1]])
88
+ forcing4 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]])
89
+ assert simplify(massmatrix4 - kane4.mass_matrix) == zeros(2)
90
+ assert simplify(forcing4 - kane4.forcing) == Matrix([0, 0])
91
+
92
+
93
+ def test_n_link_pendulum_on_cart_higher_order():
94
+ l0, m0 = symbols("l0 m0")
95
+ l1, m1 = symbols("l1 m1")
96
+ m2 = symbols("m2")
97
+ g = symbols("g")
98
+ q0, q1, q2 = dynamicsymbols("q0 q1 q2")
99
+ u0, u1, u2 = dynamicsymbols("u0 u1 u2")
100
+ F, T1 = dynamicsymbols("F T1")
101
+
102
+ kane1 = models.n_link_pendulum_on_cart(2)
103
+ massmatrix1 = Matrix([[m0 + m1 + m2, -l0*m1*cos(q1) - l0*m2*cos(q1),
104
+ -l1*m2*cos(q2)],
105
+ [-l0*m1*cos(q1) - l0*m2*cos(q1), l0**2*m1 + l0**2*m2,
106
+ l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2))],
107
+ [-l1*m2*cos(q2),
108
+ l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2)),
109
+ l1**2*m2]])
110
+ forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) - l0*m2*u1**2*sin(q1) -
111
+ l1*m2*u2**2*sin(q2) + F],
112
+ [g*l0*m1*sin(q1) + g*l0*m2*sin(q1) -
113
+ l0*l1*m2*(sin(q1)*cos(q2) - sin(q2)*cos(q1))*u2**2],
114
+ [g*l1*m2*sin(q2) - l0*l1*m2*(-sin(q1)*cos(q2) +
115
+ sin(q2)*cos(q1))*u1**2]])
116
+ assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3)
117
+ assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0])
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_particle.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import symbols
2
+ from sympy.physics.mechanics import Point, Particle, ReferenceFrame, inertia
3
+ from sympy.physics.mechanics.body_base import BodyBase
4
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
5
+
6
+
7
+ def test_particle_default():
8
+ # Test default
9
+ p = Particle('P')
10
+ assert p.name == 'P'
11
+ assert p.mass == symbols('P_mass')
12
+ assert p.masscenter.name == 'P_masscenter'
13
+ assert p.potential_energy == 0
14
+ assert p.__str__() == 'P'
15
+ assert p.__repr__() == ("Particle('P', masscenter=P_masscenter, "
16
+ "mass=P_mass)")
17
+ raises(AttributeError, lambda: p.frame)
18
+
19
+
20
+ def test_particle():
21
+ # Test initializing with parameters
22
+ m, m2, v1, v2, v3, r, g, h = symbols('m m2 v1 v2 v3 r g h')
23
+ P = Point('P')
24
+ P2 = Point('P2')
25
+ p = Particle('pa', P, m)
26
+ assert isinstance(p, BodyBase)
27
+ assert p.mass == m
28
+ assert p.point == P
29
+ # Test the mass setter
30
+ p.mass = m2
31
+ assert p.mass == m2
32
+ # Test the point setter
33
+ p.point = P2
34
+ assert p.point == P2
35
+ # Test the linear momentum function
36
+ N = ReferenceFrame('N')
37
+ O = Point('O')
38
+ P2.set_pos(O, r * N.y)
39
+ P2.set_vel(N, v1 * N.x)
40
+ raises(TypeError, lambda: Particle(P, P, m))
41
+ raises(TypeError, lambda: Particle('pa', m, m))
42
+ assert p.linear_momentum(N) == m2 * v1 * N.x
43
+ assert p.angular_momentum(O, N) == -m2 * r * v1 * N.z
44
+ P2.set_vel(N, v2 * N.y)
45
+ assert p.linear_momentum(N) == m2 * v2 * N.y
46
+ assert p.angular_momentum(O, N) == 0
47
+ P2.set_vel(N, v3 * N.z)
48
+ assert p.linear_momentum(N) == m2 * v3 * N.z
49
+ assert p.angular_momentum(O, N) == m2 * r * v3 * N.x
50
+ P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
51
+ assert p.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
52
+ assert p.angular_momentum(O, N) == m2 * r * (v3 * N.x - v1 * N.z)
53
+ p.potential_energy = m * g * h
54
+ assert p.potential_energy == m * g * h
55
+ # TODO make the result not be system-dependent
56
+ assert p.kinetic_energy(
57
+ N) in [m2 * (v1 ** 2 + v2 ** 2 + v3 ** 2) / 2,
58
+ m2 * v1 ** 2 / 2 + m2 * v2 ** 2 / 2 + m2 * v3 ** 2 / 2]
59
+
60
+
61
+ def test_parallel_axis():
62
+ N = ReferenceFrame('N')
63
+ m, a, b = symbols('m, a, b')
64
+ o = Point('o')
65
+ p = o.locatenew('p', a * N.x + b * N.y)
66
+ P = Particle('P', o, m)
67
+ Ip = P.parallel_axis(p, N)
68
+ Ip_expected = inertia(N, m * b ** 2, m * a ** 2, m * (a ** 2 + b ** 2),
69
+ ixy=-m * a * b)
70
+ assert Ip == Ip_expected
71
+
72
+
73
+ def test_deprecated_set_potential_energy():
74
+ m, g, h = symbols('m g h')
75
+ P = Point('P')
76
+ p = Particle('pa', P, m)
77
+ with warns_deprecated_sympy():
78
+ p.set_potential_energy(m * g * h)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_rigidbody.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import Point, ReferenceFrame, Dyadic, RigidBody
2
+ from sympy.physics.mechanics import dynamicsymbols, outer, inertia, Inertia
3
+ from sympy.physics.mechanics import inertia_of_point_mass
4
+ from sympy import expand, zeros, simplify, symbols
5
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
6
+
7
+
8
+ def test_rigidbody_default():
9
+ # Test default
10
+ b = RigidBody('B')
11
+ I = inertia(b.frame, *symbols('B_ixx B_iyy B_izz B_ixy B_iyz B_izx'))
12
+ assert b.name == 'B'
13
+ assert b.mass == symbols('B_mass')
14
+ assert b.masscenter.name == 'B_masscenter'
15
+ assert b.inertia == (I, b.masscenter)
16
+ assert b.central_inertia == I
17
+ assert b.frame.name == 'B_frame'
18
+ assert b.__str__() == 'B'
19
+ assert b.__repr__() == (
20
+ "RigidBody('B', masscenter=B_masscenter, frame=B_frame, mass=B_mass, "
21
+ "inertia=Inertia(dyadic=B_ixx*(B_frame.x|B_frame.x) + "
22
+ "B_ixy*(B_frame.x|B_frame.y) + B_izx*(B_frame.x|B_frame.z) + "
23
+ "B_ixy*(B_frame.y|B_frame.x) + B_iyy*(B_frame.y|B_frame.y) + "
24
+ "B_iyz*(B_frame.y|B_frame.z) + B_izx*(B_frame.z|B_frame.x) + "
25
+ "B_iyz*(B_frame.z|B_frame.y) + B_izz*(B_frame.z|B_frame.z), "
26
+ "point=B_masscenter))")
27
+
28
+
29
+ def test_rigidbody():
30
+ m, m2, v1, v2, v3, omega = symbols('m m2 v1 v2 v3 omega')
31
+ A = ReferenceFrame('A')
32
+ A2 = ReferenceFrame('A2')
33
+ P = Point('P')
34
+ P2 = Point('P2')
35
+ I = Dyadic(0)
36
+ I2 = Dyadic(0)
37
+ B = RigidBody('B', P, A, m, (I, P))
38
+ assert B.mass == m
39
+ assert B.frame == A
40
+ assert B.masscenter == P
41
+ assert B.inertia == (I, B.masscenter)
42
+
43
+ B.mass = m2
44
+ B.frame = A2
45
+ B.masscenter = P2
46
+ B.inertia = (I2, B.masscenter)
47
+ raises(TypeError, lambda: RigidBody(P, P, A, m, (I, P)))
48
+ raises(TypeError, lambda: RigidBody('B', P, P, m, (I, P)))
49
+ raises(TypeError, lambda: RigidBody('B', P, A, m, (P, P)))
50
+ raises(TypeError, lambda: RigidBody('B', P, A, m, (I, I)))
51
+ assert B.__str__() == 'B'
52
+ assert B.mass == m2
53
+ assert B.frame == A2
54
+ assert B.masscenter == P2
55
+ assert B.inertia == (I2, B.masscenter)
56
+ assert isinstance(B.inertia, Inertia)
57
+
58
+ # Testing linear momentum function assuming A2 is the inertial frame
59
+ N = ReferenceFrame('N')
60
+ P2.set_vel(N, v1 * N.x + v2 * N.y + v3 * N.z)
61
+ assert B.linear_momentum(N) == m2 * (v1 * N.x + v2 * N.y + v3 * N.z)
62
+
63
+
64
+ def test_rigidbody2():
65
+ M, v, r, omega, g, h = dynamicsymbols('M v r omega g h')
66
+ N = ReferenceFrame('N')
67
+ b = ReferenceFrame('b')
68
+ b.set_ang_vel(N, omega * b.x)
69
+ P = Point('P')
70
+ I = outer(b.x, b.x)
71
+ Inertia_tuple = (I, P)
72
+ B = RigidBody('B', P, b, M, Inertia_tuple)
73
+ P.set_vel(N, v * b.x)
74
+ assert B.angular_momentum(P, N) == omega * b.x
75
+ O = Point('O')
76
+ O.set_vel(N, v * b.x)
77
+ P.set_pos(O, r * b.y)
78
+ assert B.angular_momentum(O, N) == omega * b.x - M*v*r*b.z
79
+ B.potential_energy = M * g * h
80
+ assert B.potential_energy == M * g * h
81
+ assert expand(2 * B.kinetic_energy(N)) == omega**2 + M * v**2
82
+
83
+
84
+ def test_rigidbody3():
85
+ q1, q2, q3, q4 = dynamicsymbols('q1:5')
86
+ p1, p2, p3 = symbols('p1:4')
87
+ m = symbols('m')
88
+
89
+ A = ReferenceFrame('A')
90
+ B = A.orientnew('B', 'axis', [q1, A.x])
91
+ O = Point('O')
92
+ O.set_vel(A, q2*A.x + q3*A.y + q4*A.z)
93
+ P = O.locatenew('P', p1*B.x + p2*B.y + p3*B.z)
94
+ P.v2pt_theory(O, A, B)
95
+ I = outer(B.x, B.x)
96
+
97
+ rb1 = RigidBody('rb1', P, B, m, (I, P))
98
+ # I_S/O = I_S/S* + I_S*/O
99
+ rb2 = RigidBody('rb2', P, B, m,
100
+ (I + inertia_of_point_mass(m, P.pos_from(O), B), O))
101
+
102
+ assert rb1.central_inertia == rb2.central_inertia
103
+ assert rb1.angular_momentum(O, A) == rb2.angular_momentum(O, A)
104
+
105
+
106
+ def test_pendulum_angular_momentum():
107
+ """Consider a pendulum of length OA = 2a, of mass m as a rigid body of
108
+ center of mass G (OG = a) which turn around (O,z). The angle between the
109
+ reference frame R and the rod is q. The inertia of the body is I =
110
+ (G,0,ma^2/3,ma^2/3). """
111
+
112
+ m, a = symbols('m, a')
113
+ q = dynamicsymbols('q')
114
+
115
+ R = ReferenceFrame('R')
116
+ R1 = R.orientnew('R1', 'Axis', [q, R.z])
117
+ R1.set_ang_vel(R, q.diff() * R.z)
118
+
119
+ I = inertia(R1, 0, m * a**2 / 3, m * a**2 / 3)
120
+
121
+ O = Point('O')
122
+
123
+ A = O.locatenew('A', 2*a * R1.x)
124
+ G = O.locatenew('G', a * R1.x)
125
+
126
+ S = RigidBody('S', G, R1, m, (I, G))
127
+
128
+ O.set_vel(R, 0)
129
+ A.v2pt_theory(O, R, R1)
130
+ G.v2pt_theory(O, R, R1)
131
+
132
+ assert (4 * m * a**2 / 3 * q.diff() * R.z -
133
+ S.angular_momentum(O, R).express(R)) == 0
134
+
135
+
136
+ def test_rigidbody_inertia():
137
+ N = ReferenceFrame('N')
138
+ m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
139
+ Io = inertia(N, Ix, Iy, Iz)
140
+ o = Point('o')
141
+ p = o.locatenew('p', a * N.x + b * N.y)
142
+ R = RigidBody('R', o, N, m, (Io, p))
143
+ I_check = inertia(N, Ix - b ** 2 * m, Iy - a ** 2 * m,
144
+ Iz - m * (a ** 2 + b ** 2), m * a * b)
145
+ assert isinstance(R.inertia, Inertia)
146
+ assert R.inertia == (Io, p)
147
+ assert R.central_inertia == I_check
148
+ R.central_inertia = Io
149
+ assert R.inertia == (Io, o)
150
+ assert R.central_inertia == Io
151
+ R.inertia = (Io, p)
152
+ assert R.inertia == (Io, p)
153
+ assert R.central_inertia == I_check
154
+ # parse Inertia object
155
+ R.inertia = Inertia(Io, o)
156
+ assert R.inertia == (Io, o)
157
+
158
+
159
+ def test_parallel_axis():
160
+ N = ReferenceFrame('N')
161
+ m, Ix, Iy, Iz, a, b = symbols('m, I_x, I_y, I_z, a, b')
162
+ Io = inertia(N, Ix, Iy, Iz)
163
+ o = Point('o')
164
+ p = o.locatenew('p', a * N.x + b * N.y)
165
+ R = RigidBody('R', o, N, m, (Io, o))
166
+ Ip = R.parallel_axis(p)
167
+ Ip_expected = inertia(N, Ix + m * b**2, Iy + m * a**2,
168
+ Iz + m * (a**2 + b**2), ixy=-m * a * b)
169
+ assert Ip == Ip_expected
170
+ # Reference frame from which the parallel axis is viewed should not matter
171
+ A = ReferenceFrame('A')
172
+ A.orient_axis(N, N.z, 1)
173
+ assert simplify(
174
+ (R.parallel_axis(p, A) - Ip_expected).to_matrix(A)) == zeros(3, 3)
175
+
176
+
177
+ def test_deprecated_set_potential_energy():
178
+ m, g, h = symbols('m g h')
179
+ A = ReferenceFrame('A')
180
+ P = Point('P')
181
+ I = Dyadic(0)
182
+ B = RigidBody('B', P, A, m, (I, P))
183
+ with warns_deprecated_sympy():
184
+ B.set_potential_energy(m*g*h)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy import symbols, Matrix, atan, zeros
2
+ from sympy.simplify.simplify import simplify
3
+ from sympy.physics.mechanics import (dynamicsymbols, Particle, Point,
4
+ ReferenceFrame, SymbolicSystem)
5
+ from sympy.testing.pytest import raises
6
+
7
+ # This class is going to be tested using a simple pendulum set up in x and y
8
+ # coordinates
9
+ x, y, u, v, lam = dynamicsymbols('x y u v lambda')
10
+ m, l, g = symbols('m l g')
11
+
12
+ # Set up the different forms the equations can take
13
+ # [1] Explicit form where the kinematics and dynamics are combined
14
+ # x' = F(x, t, r, p)
15
+ #
16
+ # [2] Implicit form where the kinematics and dynamics are combined
17
+ # M(x, p) x' = F(x, t, r, p)
18
+ #
19
+ # [3] Implicit form where the kinematics and dynamics are separate
20
+ # M(q, p) u' = F(q, u, t, r, p)
21
+ # q' = G(q, u, t, r, p)
22
+ dyn_implicit_mat = Matrix([[1, 0, -x/m],
23
+ [0, 1, -y/m],
24
+ [0, 0, l**2/m]])
25
+
26
+ dyn_implicit_rhs = Matrix([0, 0, u**2 + v**2 - g*y])
27
+
28
+ comb_implicit_mat = Matrix([[1, 0, 0, 0, 0],
29
+ [0, 1, 0, 0, 0],
30
+ [0, 0, 1, 0, -x/m],
31
+ [0, 0, 0, 1, -y/m],
32
+ [0, 0, 0, 0, l**2/m]])
33
+
34
+ comb_implicit_rhs = Matrix([u, v, 0, 0, u**2 + v**2 - g*y])
35
+
36
+ kin_explicit_rhs = Matrix([u, v])
37
+
38
+ comb_explicit_rhs = comb_implicit_mat.LUsolve(comb_implicit_rhs)
39
+
40
+ # Set up a body and load to pass into the system
41
+ theta = atan(x/y)
42
+ N = ReferenceFrame('N')
43
+ A = N.orientnew('A', 'Axis', [theta, N.z])
44
+ O = Point('O')
45
+ P = O.locatenew('P', l * A.x)
46
+
47
+ Pa = Particle('Pa', P, m)
48
+
49
+ bodies = [Pa]
50
+ loads = [(P, g * m * N.x)]
51
+
52
+ # Set up some output equations to be given to SymbolicSystem
53
+ # Change to make these fit the pendulum
54
+ PE = symbols("PE")
55
+ out_eqns = {PE: m*g*(l+y)}
56
+
57
+ # Set up remaining arguments that can be passed to SymbolicSystem
58
+ alg_con = [2]
59
+ alg_con_full = [4]
60
+ coordinates = (x, y, lam)
61
+ speeds = (u, v)
62
+ states = (x, y, u, v, lam)
63
+ coord_idxs = (0, 1)
64
+ speed_idxs = (2, 3)
65
+
66
+
67
+ def test_form_1():
68
+ symsystem1 = SymbolicSystem(states, comb_explicit_rhs,
69
+ alg_con=alg_con_full, output_eqns=out_eqns,
70
+ coord_idxs=coord_idxs, speed_idxs=speed_idxs,
71
+ bodies=bodies, loads=loads)
72
+
73
+ assert symsystem1.coordinates == Matrix([x, y])
74
+ assert symsystem1.speeds == Matrix([u, v])
75
+ assert symsystem1.states == Matrix([x, y, u, v, lam])
76
+
77
+ assert symsystem1.alg_con == [4]
78
+
79
+ inter = comb_explicit_rhs
80
+ assert simplify(symsystem1.comb_explicit_rhs - inter) == zeros(5, 1)
81
+
82
+ assert set(symsystem1.dynamic_symbols()) == {y, v, lam, u, x}
83
+ assert type(symsystem1.dynamic_symbols()) == tuple
84
+ assert set(symsystem1.constant_symbols()) == {l, g, m}
85
+ assert type(symsystem1.constant_symbols()) == tuple
86
+
87
+ assert symsystem1.output_eqns == out_eqns
88
+
89
+ assert symsystem1.bodies == (Pa,)
90
+ assert symsystem1.loads == ((P, g * m * N.x),)
91
+
92
+
93
+ def test_form_2():
94
+ symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds,
95
+ mass_matrix=comb_implicit_mat,
96
+ alg_con=alg_con_full, output_eqns=out_eqns,
97
+ bodies=bodies, loads=loads)
98
+
99
+ assert symsystem2.coordinates == Matrix([x, y, lam])
100
+ assert symsystem2.speeds == Matrix([u, v])
101
+ assert symsystem2.states == Matrix([x, y, lam, u, v])
102
+
103
+ assert symsystem2.alg_con == [4]
104
+
105
+ inter = comb_implicit_rhs
106
+ assert simplify(symsystem2.comb_implicit_rhs - inter) == zeros(5, 1)
107
+ assert simplify(symsystem2.comb_implicit_mat-comb_implicit_mat) == zeros(5)
108
+
109
+ assert set(symsystem2.dynamic_symbols()) == {y, v, lam, u, x}
110
+ assert type(symsystem2.dynamic_symbols()) == tuple
111
+ assert set(symsystem2.constant_symbols()) == {l, g, m}
112
+ assert type(symsystem2.constant_symbols()) == tuple
113
+
114
+ inter = comb_explicit_rhs
115
+ symsystem2.compute_explicit_form()
116
+ assert simplify(symsystem2.comb_explicit_rhs - inter) == zeros(5, 1)
117
+
118
+
119
+ assert symsystem2.output_eqns == out_eqns
120
+
121
+ assert symsystem2.bodies == (Pa,)
122
+ assert symsystem2.loads == ((P, g * m * N.x),)
123
+
124
+
125
+ def test_form_3():
126
+ symsystem3 = SymbolicSystem(states, dyn_implicit_rhs,
127
+ mass_matrix=dyn_implicit_mat,
128
+ coordinate_derivatives=kin_explicit_rhs,
129
+ alg_con=alg_con, coord_idxs=coord_idxs,
130
+ speed_idxs=speed_idxs, bodies=bodies,
131
+ loads=loads)
132
+
133
+ assert symsystem3.coordinates == Matrix([x, y])
134
+ assert symsystem3.speeds == Matrix([u, v])
135
+ assert symsystem3.states == Matrix([x, y, u, v, lam])
136
+
137
+ assert symsystem3.alg_con == [4]
138
+
139
+ inter1 = kin_explicit_rhs
140
+ inter2 = dyn_implicit_rhs
141
+ assert simplify(symsystem3.kin_explicit_rhs - inter1) == zeros(2, 1)
142
+ assert simplify(symsystem3.dyn_implicit_mat - dyn_implicit_mat) == zeros(3)
143
+ assert simplify(symsystem3.dyn_implicit_rhs - inter2) == zeros(3, 1)
144
+
145
+ inter = comb_implicit_rhs
146
+ assert simplify(symsystem3.comb_implicit_rhs - inter) == zeros(5, 1)
147
+ assert simplify(symsystem3.comb_implicit_mat-comb_implicit_mat) == zeros(5)
148
+
149
+ inter = comb_explicit_rhs
150
+ symsystem3.compute_explicit_form()
151
+ assert simplify(symsystem3.comb_explicit_rhs - inter) == zeros(5, 1)
152
+
153
+ assert set(symsystem3.dynamic_symbols()) == {y, v, lam, u, x}
154
+ assert type(symsystem3.dynamic_symbols()) == tuple
155
+ assert set(symsystem3.constant_symbols()) == {l, g, m}
156
+ assert type(symsystem3.constant_symbols()) == tuple
157
+
158
+ assert symsystem3.output_eqns == {}
159
+
160
+ assert symsystem3.bodies == (Pa,)
161
+ assert symsystem3.loads == ((P, g * m * N.x),)
162
+
163
+
164
+ def test_property_attributes():
165
+ symsystem = SymbolicSystem(states, comb_explicit_rhs,
166
+ alg_con=alg_con_full, output_eqns=out_eqns,
167
+ coord_idxs=coord_idxs, speed_idxs=speed_idxs,
168
+ bodies=bodies, loads=loads)
169
+
170
+ with raises(AttributeError):
171
+ symsystem.bodies = 42
172
+ with raises(AttributeError):
173
+ symsystem.coordinates = 42
174
+ with raises(AttributeError):
175
+ symsystem.dyn_implicit_rhs = 42
176
+ with raises(AttributeError):
177
+ symsystem.comb_implicit_rhs = 42
178
+ with raises(AttributeError):
179
+ symsystem.loads = 42
180
+ with raises(AttributeError):
181
+ symsystem.dyn_implicit_mat = 42
182
+ with raises(AttributeError):
183
+ symsystem.comb_implicit_mat = 42
184
+ with raises(AttributeError):
185
+ symsystem.kin_explicit_rhs = 42
186
+ with raises(AttributeError):
187
+ symsystem.comb_explicit_rhs = 42
188
+ with raises(AttributeError):
189
+ symsystem.speeds = 42
190
+ with raises(AttributeError):
191
+ symsystem.states = 42
192
+ with raises(AttributeError):
193
+ symsystem.alg_con = 42
194
+
195
+
196
+ def test_not_specified_errors():
197
+ """This test will cover errors that arise from trying to access attributes
198
+ that were not specified upon object creation or were specified on creation
199
+ and the user tries to recalculate them."""
200
+ # Trying to access form 2 when form 1 given
201
+ # Trying to access form 3 when form 2 given
202
+
203
+ symsystem1 = SymbolicSystem(states, comb_explicit_rhs)
204
+
205
+ with raises(AttributeError):
206
+ symsystem1.comb_implicit_mat
207
+ with raises(AttributeError):
208
+ symsystem1.comb_implicit_rhs
209
+ with raises(AttributeError):
210
+ symsystem1.dyn_implicit_mat
211
+ with raises(AttributeError):
212
+ symsystem1.dyn_implicit_rhs
213
+ with raises(AttributeError):
214
+ symsystem1.kin_explicit_rhs
215
+ with raises(AttributeError):
216
+ symsystem1.compute_explicit_form()
217
+
218
+ symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds,
219
+ mass_matrix=comb_implicit_mat)
220
+
221
+ with raises(AttributeError):
222
+ symsystem2.dyn_implicit_mat
223
+ with raises(AttributeError):
224
+ symsystem2.dyn_implicit_rhs
225
+ with raises(AttributeError):
226
+ symsystem2.kin_explicit_rhs
227
+
228
+ # Attribute error when trying to access coordinates and speeds when only the
229
+ # states were given.
230
+ with raises(AttributeError):
231
+ symsystem1.coordinates
232
+ with raises(AttributeError):
233
+ symsystem1.speeds
234
+
235
+ # Attribute error when trying to access bodies and loads when they are not
236
+ # given
237
+ with raises(AttributeError):
238
+ symsystem1.bodies
239
+ with raises(AttributeError):
240
+ symsystem1.loads
241
+
242
+ # Attribute error when trying to access comb_explicit_rhs before it was
243
+ # calculated
244
+ with raises(AttributeError):
245
+ symsystem2.comb_explicit_rhs
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_wrapping_geometry.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the ``sympy.physics.mechanics.wrapping_geometry.py`` module."""
2
+
3
+ import pytest
4
+
5
+ from sympy import (
6
+ Integer,
7
+ Rational,
8
+ S,
9
+ Symbol,
10
+ acos,
11
+ cos,
12
+ pi,
13
+ sin,
14
+ sqrt,
15
+ )
16
+ from sympy.core.relational import Eq
17
+ from sympy.physics.mechanics import (
18
+ Point,
19
+ ReferenceFrame,
20
+ WrappingCylinder,
21
+ WrappingSphere,
22
+ dynamicsymbols,
23
+ )
24
+ from sympy.simplify.simplify import simplify
25
+
26
+
27
+ r = Symbol('r', positive=True)
28
+ x = Symbol('x')
29
+ q = dynamicsymbols('q')
30
+ N = ReferenceFrame('N')
31
+
32
+
33
+ class TestWrappingSphere:
34
+
35
+ @staticmethod
36
+ def test_valid_constructor():
37
+ r = Symbol('r', positive=True)
38
+ pO = Point('pO')
39
+ sphere = WrappingSphere(r, pO)
40
+ assert isinstance(sphere, WrappingSphere)
41
+ assert hasattr(sphere, 'radius')
42
+ assert sphere.radius == r
43
+ assert hasattr(sphere, 'point')
44
+ assert sphere.point == pO
45
+
46
+ @staticmethod
47
+ @pytest.mark.parametrize('position', [S.Zero, Integer(2)*r*N.x])
48
+ def test_geodesic_length_point_not_on_surface_invalid(position):
49
+ r = Symbol('r', positive=True)
50
+ pO = Point('pO')
51
+ sphere = WrappingSphere(r, pO)
52
+
53
+ p1 = Point('p1')
54
+ p1.set_pos(pO, position)
55
+ p2 = Point('p2')
56
+ p2.set_pos(pO, position)
57
+
58
+ error_msg = r'point .* does not lie on the surface of'
59
+ with pytest.raises(ValueError, match=error_msg):
60
+ sphere.geodesic_length(p1, p2)
61
+
62
+ @staticmethod
63
+ @pytest.mark.parametrize(
64
+ 'position_1, position_2, expected',
65
+ [
66
+ (r*N.x, r*N.x, S.Zero),
67
+ (r*N.x, r*N.y, S.Half*pi*r),
68
+ (r*N.x, r*-N.x, pi*r),
69
+ (r*-N.x, r*N.x, pi*r),
70
+ (r*N.x, r*sqrt(2)*S.Half*(N.x + N.y), Rational(1, 4)*pi*r),
71
+ (
72
+ r*sqrt(2)*S.Half*(N.x + N.y),
73
+ r*sqrt(3)*Rational(1, 3)*(N.x + N.y + N.z),
74
+ r*acos(sqrt(6)*Rational(1, 3)),
75
+ ),
76
+ ]
77
+ )
78
+ def test_geodesic_length(position_1, position_2, expected):
79
+ r = Symbol('r', positive=True)
80
+ pO = Point('pO')
81
+ sphere = WrappingSphere(r, pO)
82
+
83
+ p1 = Point('p1')
84
+ p1.set_pos(pO, position_1)
85
+ p2 = Point('p2')
86
+ p2.set_pos(pO, position_2)
87
+
88
+ assert simplify(Eq(sphere.geodesic_length(p1, p2), expected))
89
+
90
+ @staticmethod
91
+ @pytest.mark.parametrize(
92
+ 'position_1, position_2, vector_1, vector_2',
93
+ [
94
+ (r * N.x, r * N.y, N.y, N.x),
95
+ (r * N.x, -r * N.y, -N.y, N.x),
96
+ (
97
+ r * N.y,
98
+ sqrt(2)/2 * r * N.x - sqrt(2)/2 * r * N.y,
99
+ N.x,
100
+ sqrt(2)/2 * N.x + sqrt(2)/2 * N.y,
101
+ ),
102
+ (
103
+ r * N.x,
104
+ r / 2 * N.x + sqrt(3)/2 * r * N.y,
105
+ N.y,
106
+ sqrt(3)/2 * N.x - 1/2 * N.y,
107
+ ),
108
+ (
109
+ r * N.x,
110
+ sqrt(2)/2 * r * N.x + sqrt(2)/2 * r * N.y,
111
+ N.y,
112
+ sqrt(2)/2 * N.x - sqrt(2)/2 * N.y,
113
+ ),
114
+ ]
115
+ )
116
+ def test_geodesic_end_vectors(position_1, position_2, vector_1, vector_2):
117
+ r = Symbol('r', positive=True)
118
+ pO = Point('pO')
119
+ sphere = WrappingSphere(r, pO)
120
+
121
+ p1 = Point('p1')
122
+ p1.set_pos(pO, position_1)
123
+ p2 = Point('p2')
124
+ p2.set_pos(pO, position_2)
125
+
126
+ expected = (vector_1, vector_2)
127
+
128
+ assert sphere.geodesic_end_vectors(p1, p2) == expected
129
+
130
+ @staticmethod
131
+ @pytest.mark.parametrize(
132
+ 'position',
133
+ [r * N.x, r * cos(q) * N.x + r * sin(q) * N.y]
134
+ )
135
+ def test_geodesic_end_vectors_invalid_coincident(position):
136
+ r = Symbol('r', positive=True)
137
+ pO = Point('pO')
138
+ sphere = WrappingSphere(r, pO)
139
+
140
+ p1 = Point('p1')
141
+ p1.set_pos(pO, position)
142
+ p2 = Point('p2')
143
+ p2.set_pos(pO, position)
144
+
145
+ with pytest.raises(ValueError):
146
+ _ = sphere.geodesic_end_vectors(p1, p2)
147
+
148
+ @staticmethod
149
+ @pytest.mark.parametrize(
150
+ 'position_1, position_2',
151
+ [
152
+ (r * N.x, -r * N.x),
153
+ (-r * N.y, r * N.y),
154
+ (
155
+ r * cos(q) * N.x + r * sin(q) * N.y,
156
+ -r * cos(q) * N.x - r * sin(q) * N.y,
157
+ )
158
+ ]
159
+ )
160
+ def test_geodesic_end_vectors_invalid_diametrically_opposite(
161
+ position_1,
162
+ position_2,
163
+ ):
164
+ r = Symbol('r', positive=True)
165
+ pO = Point('pO')
166
+ sphere = WrappingSphere(r, pO)
167
+
168
+ p1 = Point('p1')
169
+ p1.set_pos(pO, position_1)
170
+ p2 = Point('p2')
171
+ p2.set_pos(pO, position_2)
172
+
173
+ with pytest.raises(ValueError):
174
+ _ = sphere.geodesic_end_vectors(p1, p2)
175
+
176
+
177
+ class TestWrappingCylinder:
178
+
179
+ @staticmethod
180
+ def test_valid_constructor():
181
+ N = ReferenceFrame('N')
182
+ r = Symbol('r', positive=True)
183
+ pO = Point('pO')
184
+ cylinder = WrappingCylinder(r, pO, N.x)
185
+ assert isinstance(cylinder, WrappingCylinder)
186
+ assert hasattr(cylinder, 'radius')
187
+ assert cylinder.radius == r
188
+ assert hasattr(cylinder, 'point')
189
+ assert cylinder.point == pO
190
+ assert hasattr(cylinder, 'axis')
191
+ assert cylinder.axis == N.x
192
+
193
+ @staticmethod
194
+ @pytest.mark.parametrize(
195
+ 'position, expected',
196
+ [
197
+ (S.Zero, False),
198
+ (r*N.y, True),
199
+ (r*N.z, True),
200
+ (r*(N.y + N.z).normalize(), True),
201
+ (Integer(2)*r*N.y, False),
202
+ (r*(N.x + N.y), True),
203
+ (r*(Integer(2)*N.x + N.y), True),
204
+ (Integer(2)*N.x + r*(Integer(2)*N.y + N.z).normalize(), True),
205
+ (r*(cos(q)*N.y + sin(q)*N.z), True)
206
+ ]
207
+ )
208
+ def test_point_is_on_surface(position, expected):
209
+ r = Symbol('r', positive=True)
210
+ pO = Point('pO')
211
+ cylinder = WrappingCylinder(r, pO, N.x)
212
+
213
+ p1 = Point('p1')
214
+ p1.set_pos(pO, position)
215
+
216
+ assert cylinder.point_on_surface(p1) is expected
217
+
218
+ @staticmethod
219
+ @pytest.mark.parametrize('position', [S.Zero, Integer(2)*r*N.y])
220
+ def test_geodesic_length_point_not_on_surface_invalid(position):
221
+ r = Symbol('r', positive=True)
222
+ pO = Point('pO')
223
+ cylinder = WrappingCylinder(r, pO, N.x)
224
+
225
+ p1 = Point('p1')
226
+ p1.set_pos(pO, position)
227
+ p2 = Point('p2')
228
+ p2.set_pos(pO, position)
229
+
230
+ error_msg = r'point .* does not lie on the surface of'
231
+ with pytest.raises(ValueError, match=error_msg):
232
+ cylinder.geodesic_length(p1, p2)
233
+
234
+ @staticmethod
235
+ @pytest.mark.parametrize(
236
+ 'axis, position_1, position_2, expected',
237
+ [
238
+ (N.x, r*N.y, r*N.y, S.Zero),
239
+ (N.x, r*N.y, N.x + r*N.y, S.One),
240
+ (N.x, r*N.y, -x*N.x + r*N.y, sqrt(x**2)),
241
+ (-N.x, r*N.y, x*N.x + r*N.y, sqrt(x**2)),
242
+ (N.x, r*N.y, r*N.z, S.Half*pi*sqrt(r**2)),
243
+ (-N.x, r*N.y, r*N.z, Integer(3)*S.Half*pi*sqrt(r**2)),
244
+ (N.x, r*N.z, r*N.y, Integer(3)*S.Half*pi*sqrt(r**2)),
245
+ (-N.x, r*N.z, r*N.y, S.Half*pi*sqrt(r**2)),
246
+ (N.x, r*N.y, r*(cos(q)*N.y + sin(q)*N.z), sqrt(r**2*q**2)),
247
+ (
248
+ -N.x, r*N.y,
249
+ r*(cos(q)*N.y + sin(q)*N.z),
250
+ sqrt(r**2*(Integer(2)*pi - q)**2),
251
+ ),
252
+ ]
253
+ )
254
+ def test_geodesic_length(axis, position_1, position_2, expected):
255
+ r = Symbol('r', positive=True)
256
+ pO = Point('pO')
257
+ cylinder = WrappingCylinder(r, pO, axis)
258
+
259
+ p1 = Point('p1')
260
+ p1.set_pos(pO, position_1)
261
+ p2 = Point('p2')
262
+ p2.set_pos(pO, position_2)
263
+
264
+ assert simplify(Eq(cylinder.geodesic_length(p1, p2), expected))
265
+
266
+ @staticmethod
267
+ @pytest.mark.parametrize(
268
+ 'axis, position_1, position_2, vector_1, vector_2',
269
+ [
270
+ (N.z, r * N.x, r * N.y, N.y, N.x),
271
+ (N.z, r * N.x, -r * N.x, N.y, N.y),
272
+ (N.z, -r * N.x, r * N.x, -N.y, -N.y),
273
+ (-N.z, r * N.x, -r * N.x, -N.y, -N.y),
274
+ (-N.z, -r * N.x, r * N.x, N.y, N.y),
275
+ (N.z, r * N.x, -r * N.y, N.y, -N.x),
276
+ (
277
+ N.z,
278
+ r * N.y,
279
+ sqrt(2)/2 * r * N.x - sqrt(2)/2 * r * N.y,
280
+ - N.x,
281
+ - sqrt(2)/2 * N.x - sqrt(2)/2 * N.y,
282
+ ),
283
+ (
284
+ N.z,
285
+ r * N.x,
286
+ r / 2 * N.x + sqrt(3)/2 * r * N.y,
287
+ N.y,
288
+ sqrt(3)/2 * N.x - 1/2 * N.y,
289
+ ),
290
+ (
291
+ N.z,
292
+ r * N.x,
293
+ sqrt(2)/2 * r * N.x + sqrt(2)/2 * r * N.y,
294
+ N.y,
295
+ sqrt(2)/2 * N.x - sqrt(2)/2 * N.y,
296
+ ),
297
+ (
298
+ N.z,
299
+ r * N.x,
300
+ r * N.x + N.z,
301
+ N.z,
302
+ -N.z,
303
+ ),
304
+ (
305
+ N.z,
306
+ r * N.x,
307
+ r * N.y + pi/2 * r * N.z,
308
+ sqrt(2)/2 * N.y + sqrt(2)/2 * N.z,
309
+ sqrt(2)/2 * N.x - sqrt(2)/2 * N.z,
310
+ ),
311
+ (
312
+ N.z,
313
+ r * N.x,
314
+ r * cos(q) * N.x + r * sin(q) * N.y,
315
+ N.y,
316
+ sin(q) * N.x - cos(q) * N.y,
317
+ ),
318
+ ]
319
+ )
320
+ def test_geodesic_end_vectors(
321
+ axis,
322
+ position_1,
323
+ position_2,
324
+ vector_1,
325
+ vector_2,
326
+ ):
327
+ r = Symbol('r', positive=True)
328
+ pO = Point('pO')
329
+ cylinder = WrappingCylinder(r, pO, axis)
330
+
331
+ p1 = Point('p1')
332
+ p1.set_pos(pO, position_1)
333
+ p2 = Point('p2')
334
+ p2.set_pos(pO, position_2)
335
+
336
+ expected = (vector_1, vector_2)
337
+ end_vectors = tuple(
338
+ end_vector.simplify()
339
+ for end_vector in cylinder.geodesic_end_vectors(p1, p2)
340
+ )
341
+
342
+ assert end_vectors == expected
343
+
344
+ @staticmethod
345
+ @pytest.mark.parametrize(
346
+ 'axis, position',
347
+ [
348
+ (N.z, r * N.x),
349
+ (N.z, r * cos(q) * N.x + r * sin(q) * N.y + N.z),
350
+ ]
351
+ )
352
+ def test_geodesic_end_vectors_invalid_coincident(axis, position):
353
+ r = Symbol('r', positive=True)
354
+ pO = Point('pO')
355
+ cylinder = WrappingCylinder(r, pO, axis)
356
+
357
+ p1 = Point('p1')
358
+ p1.set_pos(pO, position)
359
+ p2 = Point('p2')
360
+ p2.set_pos(pO, position)
361
+
362
+ with pytest.raises(ValueError):
363
+ _ = cylinder.geodesic_end_vectors(p1, p2)
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/mechanics/wrapping_geometry.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometry objects for use by wrapping pathways."""
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy import Integer, acos, pi, sqrt, sympify, tan
6
+ from sympy.core.relational import Eq
7
+ from sympy.functions.elementary.trigonometric import atan2
8
+ from sympy.polys.polytools import cancel
9
+ from sympy.physics.vector import Vector, dot
10
+ from sympy.simplify.simplify import trigsimp
11
+
12
+
13
+ __all__ = [
14
+ 'WrappingGeometryBase',
15
+ 'WrappingCylinder',
16
+ 'WrappingSphere',
17
+ ]
18
+
19
+
20
+ class WrappingGeometryBase(ABC):
21
+ """Abstract base class for all geometry classes to inherit from.
22
+
23
+ Notes
24
+ =====
25
+
26
+ Instances of this class cannot be directly instantiated by users. However,
27
+ it can be used to created custom geometry types through subclassing.
28
+
29
+ """
30
+
31
+ @property
32
+ @abstractmethod
33
+ def point(cls):
34
+ """The point with which the geometry is associated."""
35
+ pass
36
+
37
+ @abstractmethod
38
+ def point_on_surface(self, point):
39
+ """Returns ``True`` if a point is on the geometry's surface.
40
+
41
+ Parameters
42
+ ==========
43
+ point : Point
44
+ The point for which it's to be ascertained if it's on the
45
+ geometry's surface or not.
46
+
47
+ """
48
+ pass
49
+
50
+ @abstractmethod
51
+ def geodesic_length(self, point_1, point_2):
52
+ """Returns the shortest distance between two points on a geometry's
53
+ surface.
54
+
55
+ Parameters
56
+ ==========
57
+
58
+ point_1 : Point
59
+ The point from which the geodesic length should be calculated.
60
+ point_2 : Point
61
+ The point to which the geodesic length should be calculated.
62
+
63
+ """
64
+ pass
65
+
66
+ @abstractmethod
67
+ def geodesic_end_vectors(self, point_1, point_2):
68
+ """The vectors parallel to the geodesic at the two end points.
69
+
70
+ Parameters
71
+ ==========
72
+
73
+ point_1 : Point
74
+ The point from which the geodesic originates.
75
+ point_2 : Point
76
+ The point at which the geodesic terminates.
77
+
78
+ """
79
+ pass
80
+
81
+ def __repr__(self):
82
+ """Default representation of a geometry object."""
83
+ return f'{self.__class__.__name__}()'
84
+
85
+
86
+ class WrappingSphere(WrappingGeometryBase):
87
+ """A solid spherical object.
88
+
89
+ Explanation
90
+ ===========
91
+
92
+ A wrapping geometry that allows for circular arcs to be defined between
93
+ pairs of points. These paths are always geodetic (the shortest possible).
94
+
95
+ Examples
96
+ ========
97
+
98
+ To create a ``WrappingSphere`` instance, a ``Symbol`` denoting its radius
99
+ and ``Point`` at which its center will be located are needed:
100
+
101
+ >>> from sympy import symbols
102
+ >>> from sympy.physics.mechanics import Point, WrappingSphere
103
+ >>> r = symbols('r')
104
+ >>> pO = Point('pO')
105
+
106
+ A sphere with radius ``r`` centered on ``pO`` can be instantiated with:
107
+
108
+ >>> WrappingSphere(r, pO)
109
+ WrappingSphere(radius=r, point=pO)
110
+
111
+ Parameters
112
+ ==========
113
+
114
+ radius : Symbol
115
+ Radius of the sphere. This symbol must represent a value that is
116
+ positive and constant, i.e. it cannot be a dynamic symbol, nor can it
117
+ be an expression.
118
+ point : Point
119
+ A point at which the sphere is centered.
120
+
121
+ See Also
122
+ ========
123
+
124
+ WrappingCylinder: Cylindrical geometry where the wrapping direction can be
125
+ defined.
126
+
127
+ """
128
+
129
+ def __init__(self, radius, point):
130
+ """Initializer for ``WrappingSphere``.
131
+
132
+ Parameters
133
+ ==========
134
+
135
+ radius : Symbol
136
+ The radius of the sphere.
137
+ point : Point
138
+ A point on which the sphere is centered.
139
+
140
+ """
141
+ self.radius = radius
142
+ self.point = point
143
+
144
+ @property
145
+ def radius(self):
146
+ """Radius of the sphere."""
147
+ return self._radius
148
+
149
+ @radius.setter
150
+ def radius(self, radius):
151
+ self._radius = radius
152
+
153
+ @property
154
+ def point(self):
155
+ """A point on which the sphere is centered."""
156
+ return self._point
157
+
158
+ @point.setter
159
+ def point(self, point):
160
+ self._point = point
161
+
162
+ def point_on_surface(self, point):
163
+ """Returns ``True`` if a point is on the sphere's surface.
164
+
165
+ Parameters
166
+ ==========
167
+
168
+ point : Point
169
+ The point for which it's to be ascertained if it's on the sphere's
170
+ surface or not. This point's position relative to the sphere's
171
+ center must be a simple expression involving the radius of the
172
+ sphere, otherwise this check will likely not work.
173
+
174
+ """
175
+ point_vector = point.pos_from(self.point)
176
+ if isinstance(point_vector, Vector):
177
+ point_radius_squared = dot(point_vector, point_vector)
178
+ else:
179
+ point_radius_squared = point_vector**2
180
+ return Eq(point_radius_squared, self.radius**2) == True
181
+
182
+ def geodesic_length(self, point_1, point_2):
183
+ r"""Returns the shortest distance between two points on the sphere's
184
+ surface.
185
+
186
+ Explanation
187
+ ===========
188
+
189
+ The geodesic length, i.e. the shortest arc along the surface of a
190
+ sphere, connecting two points can be calculated using the formula:
191
+
192
+ .. math::
193
+
194
+ l = \arccos\left(\mathbf{v}_1 \cdot \mathbf{v}_2\right)
195
+
196
+ where $\mathbf{v}_1$ and $\mathbf{v}_2$ are the unit vectors from the
197
+ sphere's center to the first and second points on the sphere's surface
198
+ respectively. Note that the actual path that the geodesic will take is
199
+ undefined when the two points are directly opposite one another.
200
+
201
+ Examples
202
+ ========
203
+
204
+ A geodesic length can only be calculated between two points on the
205
+ sphere's surface. Firstly, a ``WrappingSphere`` instance must be
206
+ created along with two points that will lie on its surface:
207
+
208
+ >>> from sympy import symbols
209
+ >>> from sympy.physics.mechanics import (Point, ReferenceFrame,
210
+ ... WrappingSphere)
211
+ >>> N = ReferenceFrame('N')
212
+ >>> r = symbols('r')
213
+ >>> pO = Point('pO')
214
+ >>> pO.set_vel(N, 0)
215
+ >>> sphere = WrappingSphere(r, pO)
216
+ >>> p1 = Point('p1')
217
+ >>> p2 = Point('p2')
218
+
219
+ Let's assume that ``p1`` lies at a distance of ``r`` in the ``N.x``
220
+ direction from ``pO`` and that ``p2`` is located on the sphere's
221
+ surface in the ``N.y + N.z`` direction from ``pO``. These positions can
222
+ be set with:
223
+
224
+ >>> p1.set_pos(pO, r*N.x)
225
+ >>> p1.pos_from(pO)
226
+ r*N.x
227
+ >>> p2.set_pos(pO, r*(N.y + N.z).normalize())
228
+ >>> p2.pos_from(pO)
229
+ sqrt(2)*r/2*N.y + sqrt(2)*r/2*N.z
230
+
231
+ The geodesic length, which is in this case is a quarter of the sphere's
232
+ circumference, can be calculated using the ``geodesic_length`` method:
233
+
234
+ >>> sphere.geodesic_length(p1, p2)
235
+ pi*r/2
236
+
237
+ If the ``geodesic_length`` method is passed an argument, the ``Point``
238
+ that doesn't lie on the sphere's surface then a ``ValueError`` is
239
+ raised because it's not possible to calculate a value in this case.
240
+
241
+ Parameters
242
+ ==========
243
+
244
+ point_1 : Point
245
+ Point from which the geodesic length should be calculated.
246
+ point_2 : Point
247
+ Point to which the geodesic length should be calculated.
248
+
249
+ """
250
+ for point in (point_1, point_2):
251
+ if not self.point_on_surface(point):
252
+ msg = (
253
+ f'Geodesic length cannot be calculated as point {point} '
254
+ f'with radius {point.pos_from(self.point).magnitude()} '
255
+ f'from the sphere\'s center {self.point} does not lie on '
256
+ f'the surface of {self} with radius {self.radius}.'
257
+ )
258
+ raise ValueError(msg)
259
+ point_1_vector = point_1.pos_from(self.point).normalize()
260
+ point_2_vector = point_2.pos_from(self.point).normalize()
261
+ central_angle = acos(point_2_vector.dot(point_1_vector))
262
+ geodesic_length = self.radius*central_angle
263
+ return geodesic_length
264
+
265
+ def geodesic_end_vectors(self, point_1, point_2):
266
+ """The vectors parallel to the geodesic at the two end points.
267
+
268
+ Parameters
269
+ ==========
270
+
271
+ point_1 : Point
272
+ The point from which the geodesic originates.
273
+ point_2 : Point
274
+ The point at which the geodesic terminates.
275
+
276
+ """
277
+ pA, pB = point_1, point_2
278
+ pO = self.point
279
+ pA_vec = pA.pos_from(pO)
280
+ pB_vec = pB.pos_from(pO)
281
+
282
+ if pA_vec.cross(pB_vec) == 0:
283
+ msg = (
284
+ f'Can\'t compute geodesic end vectors for the pair of points '
285
+ f'{pA} and {pB} on a sphere {self} as they are diametrically '
286
+ f'opposed, thus the geodesic is not defined.'
287
+ )
288
+ raise ValueError(msg)
289
+
290
+ return (
291
+ pA_vec.cross(pB.pos_from(pA)).cross(pA_vec).normalize(),
292
+ pB_vec.cross(pA.pos_from(pB)).cross(pB_vec).normalize(),
293
+ )
294
+
295
+ def __repr__(self):
296
+ """Representation of a ``WrappingSphere``."""
297
+ return (
298
+ f'{self.__class__.__name__}(radius={self.radius}, '
299
+ f'point={self.point})'
300
+ )
301
+
302
+
303
+ class WrappingCylinder(WrappingGeometryBase):
304
+ """A solid (infinite) cylindrical object.
305
+
306
+ Explanation
307
+ ===========
308
+
309
+ A wrapping geometry that allows for circular arcs to be defined between
310
+ pairs of points. These paths are always geodetic (the shortest possible) in
311
+ the sense that they will be a straight line on the unwrapped cylinder's
312
+ surface. However, it is also possible for a direction to be specified, i.e.
313
+ paths can be influenced such that they either wrap along the shortest side
314
+ or the longest side of the cylinder. To define these directions, rotations
315
+ are in the positive direction following the right-hand rule.
316
+
317
+ Examples
318
+ ========
319
+
320
+ To create a ``WrappingCylinder`` instance, a ``Symbol`` denoting its
321
+ radius, a ``Vector`` defining its axis, and a ``Point`` through which its
322
+ axis passes are needed:
323
+
324
+ >>> from sympy import symbols
325
+ >>> from sympy.physics.mechanics import (Point, ReferenceFrame,
326
+ ... WrappingCylinder)
327
+ >>> N = ReferenceFrame('N')
328
+ >>> r = symbols('r')
329
+ >>> pO = Point('pO')
330
+ >>> ax = N.x
331
+
332
+ A cylinder with radius ``r``, and axis parallel to ``N.x`` passing through
333
+ ``pO`` can be instantiated with:
334
+
335
+ >>> WrappingCylinder(r, pO, ax)
336
+ WrappingCylinder(radius=r, point=pO, axis=N.x)
337
+
338
+ Parameters
339
+ ==========
340
+
341
+ radius : Symbol
342
+ The radius of the cylinder.
343
+ point : Point
344
+ A point through which the cylinder's axis passes.
345
+ axis : Vector
346
+ The axis along which the cylinder is aligned.
347
+
348
+ See Also
349
+ ========
350
+
351
+ WrappingSphere: Spherical geometry where the wrapping direction is always
352
+ geodetic.
353
+
354
+ """
355
+
356
+ def __init__(self, radius, point, axis):
357
+ """Initializer for ``WrappingCylinder``.
358
+
359
+ Parameters
360
+ ==========
361
+
362
+ radius : Symbol
363
+ The radius of the cylinder. This symbol must represent a value that
364
+ is positive and constant, i.e. it cannot be a dynamic symbol.
365
+ point : Point
366
+ A point through which the cylinder's axis passes.
367
+ axis : Vector
368
+ The axis along which the cylinder is aligned.
369
+
370
+ """
371
+ self.radius = radius
372
+ self.point = point
373
+ self.axis = axis
374
+
375
+ @property
376
+ def radius(self):
377
+ """Radius of the cylinder."""
378
+ return self._radius
379
+
380
+ @radius.setter
381
+ def radius(self, radius):
382
+ self._radius = radius
383
+
384
+ @property
385
+ def point(self):
386
+ """A point through which the cylinder's axis passes."""
387
+ return self._point
388
+
389
+ @point.setter
390
+ def point(self, point):
391
+ self._point = point
392
+
393
+ @property
394
+ def axis(self):
395
+ """Axis along which the cylinder is aligned."""
396
+ return self._axis
397
+
398
+ @axis.setter
399
+ def axis(self, axis):
400
+ self._axis = axis.normalize()
401
+
402
+ def point_on_surface(self, point):
403
+ """Returns ``True`` if a point is on the cylinder's surface.
404
+
405
+ Parameters
406
+ ==========
407
+
408
+ point : Point
409
+ The point for which it's to be ascertained if it's on the
410
+ cylinder's surface or not. This point's position relative to the
411
+ cylinder's axis must be a simple expression involving the radius of
412
+ the sphere, otherwise this check will likely not work.
413
+
414
+ """
415
+ relative_position = point.pos_from(self.point)
416
+ parallel = relative_position.dot(self.axis) * self.axis
417
+ point_vector = relative_position - parallel
418
+ if isinstance(point_vector, Vector):
419
+ point_radius_squared = dot(point_vector, point_vector)
420
+ else:
421
+ point_radius_squared = point_vector**2
422
+ return Eq(trigsimp(point_radius_squared), self.radius**2) == True
423
+
424
+ def geodesic_length(self, point_1, point_2):
425
+ """The shortest distance between two points on a geometry's surface.
426
+
427
+ Explanation
428
+ ===========
429
+
430
+ The geodesic length, i.e. the shortest arc along the surface of a
431
+ cylinder, connecting two points. It can be calculated using Pythagoras'
432
+ theorem. The first short side is the distance between the two points on
433
+ the cylinder's surface parallel to the cylinder's axis. The second
434
+ short side is the arc of a circle between the two points of the
435
+ cylinder's surface perpendicular to the cylinder's axis. The resulting
436
+ hypotenuse is the geodesic length.
437
+
438
+ Examples
439
+ ========
440
+
441
+ A geodesic length can only be calculated between two points on the
442
+ cylinder's surface. Firstly, a ``WrappingCylinder`` instance must be
443
+ created along with two points that will lie on its surface:
444
+
445
+ >>> from sympy import symbols, cos, sin
446
+ >>> from sympy.physics.mechanics import (Point, ReferenceFrame,
447
+ ... WrappingCylinder, dynamicsymbols)
448
+ >>> N = ReferenceFrame('N')
449
+ >>> r = symbols('r')
450
+ >>> pO = Point('pO')
451
+ >>> pO.set_vel(N, 0)
452
+ >>> cylinder = WrappingCylinder(r, pO, N.x)
453
+ >>> p1 = Point('p1')
454
+ >>> p2 = Point('p2')
455
+
456
+ Let's assume that ``p1`` is located at ``N.x + r*N.y`` relative to
457
+ ``pO`` and that ``p2`` is located at ``r*(cos(q)*N.y + sin(q)*N.z)``
458
+ relative to ``pO``, where ``q(t)`` is a generalized coordinate
459
+ specifying the angle rotated around the ``N.x`` axis according to the
460
+ right-hand rule where ``N.y`` is zero. These positions can be set with:
461
+
462
+ >>> q = dynamicsymbols('q')
463
+ >>> p1.set_pos(pO, N.x + r*N.y)
464
+ >>> p1.pos_from(pO)
465
+ N.x + r*N.y
466
+ >>> p2.set_pos(pO, r*(cos(q)*N.y + sin(q)*N.z).normalize())
467
+ >>> p2.pos_from(pO).simplify()
468
+ r*cos(q(t))*N.y + r*sin(q(t))*N.z
469
+
470
+ The geodesic length, which is in this case a is the hypotenuse of a
471
+ right triangle where the other two side lengths are ``1`` (parallel to
472
+ the cylinder's axis) and ``r*q(t)`` (parallel to the cylinder's cross
473
+ section), can be calculated using the ``geodesic_length`` method:
474
+
475
+ >>> cylinder.geodesic_length(p1, p2).simplify()
476
+ sqrt(r**2*q(t)**2 + 1)
477
+
478
+ If the ``geodesic_length`` method is passed an argument ``Point`` that
479
+ doesn't lie on the sphere's surface then a ``ValueError`` is raised
480
+ because it's not possible to calculate a value in this case.
481
+
482
+ Parameters
483
+ ==========
484
+
485
+ point_1 : Point
486
+ Point from which the geodesic length should be calculated.
487
+ point_2 : Point
488
+ Point to which the geodesic length should be calculated.
489
+
490
+ """
491
+ for point in (point_1, point_2):
492
+ if not self.point_on_surface(point):
493
+ msg = (
494
+ f'Geodesic length cannot be calculated as point {point} '
495
+ f'with radius {point.pos_from(self.point).magnitude()} '
496
+ f'from the cylinder\'s center {self.point} does not lie on '
497
+ f'the surface of {self} with radius {self.radius} and axis '
498
+ f'{self.axis}.'
499
+ )
500
+ raise ValueError(msg)
501
+
502
+ relative_position = point_2.pos_from(point_1)
503
+ parallel_length = relative_position.dot(self.axis)
504
+
505
+ point_1_relative_position = point_1.pos_from(self.point)
506
+ point_1_perpendicular_vector = (
507
+ point_1_relative_position
508
+ - point_1_relative_position.dot(self.axis)*self.axis
509
+ ).normalize()
510
+
511
+ point_2_relative_position = point_2.pos_from(self.point)
512
+ point_2_perpendicular_vector = (
513
+ point_2_relative_position
514
+ - point_2_relative_position.dot(self.axis)*self.axis
515
+ ).normalize()
516
+
517
+ central_angle = _directional_atan(
518
+ cancel(point_1_perpendicular_vector
519
+ .cross(point_2_perpendicular_vector)
520
+ .dot(self.axis)),
521
+ cancel(point_1_perpendicular_vector.dot(point_2_perpendicular_vector)),
522
+ )
523
+
524
+ planar_arc_length = self.radius*central_angle
525
+ geodesic_length = sqrt(parallel_length**2 + planar_arc_length**2)
526
+ return geodesic_length
527
+
528
+ def geodesic_end_vectors(self, point_1, point_2):
529
+ """The vectors parallel to the geodesic at the two end points.
530
+
531
+ Parameters
532
+ ==========
533
+
534
+ point_1 : Point
535
+ The point from which the geodesic originates.
536
+ point_2 : Point
537
+ The point at which the geodesic terminates.
538
+
539
+ """
540
+ point_1_from_origin_point = point_1.pos_from(self.point)
541
+ point_2_from_origin_point = point_2.pos_from(self.point)
542
+
543
+ if point_1_from_origin_point == point_2_from_origin_point:
544
+ msg = (
545
+ f'Cannot compute geodesic end vectors for coincident points '
546
+ f'{point_1} and {point_2} as no geodesic exists.'
547
+ )
548
+ raise ValueError(msg)
549
+
550
+ point_1_parallel = point_1_from_origin_point.dot(self.axis) * self.axis
551
+ point_2_parallel = point_2_from_origin_point.dot(self.axis) * self.axis
552
+ point_1_normal = (point_1_from_origin_point - point_1_parallel)
553
+ point_2_normal = (point_2_from_origin_point - point_2_parallel)
554
+
555
+ if point_1_normal == point_2_normal:
556
+ point_1_perpendicular = Vector(0)
557
+ point_2_perpendicular = Vector(0)
558
+ else:
559
+ point_1_perpendicular = self.axis.cross(point_1_normal).normalize()
560
+ point_2_perpendicular = -self.axis.cross(point_2_normal).normalize()
561
+
562
+ geodesic_length = self.geodesic_length(point_1, point_2)
563
+ relative_position = point_2.pos_from(point_1)
564
+ parallel_length = relative_position.dot(self.axis)
565
+ planar_arc_length = sqrt(geodesic_length**2 - parallel_length**2)
566
+
567
+ point_1_vector = (
568
+ planar_arc_length * point_1_perpendicular
569
+ + parallel_length * self.axis
570
+ ).normalize()
571
+ point_2_vector = (
572
+ planar_arc_length * point_2_perpendicular
573
+ - parallel_length * self.axis
574
+ ).normalize()
575
+
576
+ return (point_1_vector, point_2_vector)
577
+
578
+ def __repr__(self):
579
+ """Representation of a ``WrappingCylinder``."""
580
+ return (
581
+ f'{self.__class__.__name__}(radius={self.radius}, '
582
+ f'point={self.point}, axis={self.axis})'
583
+ )
584
+
585
+
586
+ def _directional_atan(numerator, denominator):
587
+ """Compute atan in a directional sense as required for geodesics.
588
+
589
+ Explanation
590
+ ===========
591
+
592
+ To be able to control the direction of the geodesic length along the
593
+ surface of a cylinder a dedicated arctangent function is needed that
594
+ properly handles the directionality of different case. This function
595
+ ensures that the central angle is always positive but shifting the case
596
+ where ``atan2`` would return a negative angle to be centered around
597
+ ``2*pi``.
598
+
599
+ Notes
600
+ =====
601
+
602
+ This function only handles very specific cases, i.e. the ones that are
603
+ expected to be encountered when calculating symbolic geodesics on uniformly
604
+ curved surfaces. As such, ``NotImplemented`` errors can be raised in many
605
+ cases. This function is named with a leader underscore to indicate that it
606
+ only aims to provide very specific functionality within the private scope
607
+ of this module.
608
+
609
+ """
610
+
611
+ if numerator.is_number and denominator.is_number:
612
+ angle = atan2(numerator, denominator)
613
+ if angle < 0:
614
+ angle += 2 * pi
615
+ elif numerator.is_number:
616
+ msg = (
617
+ f'Cannot compute a directional atan when the numerator {numerator} '
618
+ f'is numeric and the denominator {denominator} is symbolic.'
619
+ )
620
+ raise NotImplementedError(msg)
621
+ elif denominator.is_number:
622
+ msg = (
623
+ f'Cannot compute a directional atan when the numerator {numerator} '
624
+ f'is symbolic and the denominator {denominator} is numeric.'
625
+ )
626
+ raise NotImplementedError(msg)
627
+ else:
628
+ ratio = sympify(trigsimp(numerator / denominator))
629
+ if isinstance(ratio, tan):
630
+ angle = ratio.args[0]
631
+ elif (
632
+ ratio.is_Mul
633
+ and ratio.args[0] == Integer(-1)
634
+ and isinstance(ratio.args[1], tan)
635
+ ):
636
+ angle = 2 * pi - ratio.args[1].args[0]
637
+ else:
638
+ msg = f'Cannot compute a directional atan for the value {ratio}.'
639
+ raise NotImplementedError(msg)
640
+
641
+ return angle
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/gaussopt.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/polarization.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
evalkit_internvl/lib/python3.10/site-packages/sympy/physics/optics/__pycache__/utils.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (15.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/configuration_utils.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/dependency_versions_table.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/__pycache__/image_processor.cpython-310.pyc ADDED
Binary file (30.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from abc import ABC, abstractmethod
16
+ from argparse import ArgumentParser
17
+
18
+
19
+ class BaseDiffusersCLICommand(ABC):
20
+ @staticmethod
21
+ @abstractmethod
22
+ def register_subcommand(parser: ArgumentParser):
23
+ raise NotImplementedError()
24
+
25
+ @abstractmethod
26
+ def run(self):
27
+ raise NotImplementedError()
evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/diffusers_cli.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from argparse import ArgumentParser
17
+
18
+ from .env import EnvironmentCommand
19
+ from .fp16_safetensors import FP16SafetensorsCommand
20
+
21
+
22
+ def main():
23
+ parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
24
+ commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
25
+
26
+ # Register commands
27
+ EnvironmentCommand.register_subcommand(commands_parser)
28
+ FP16SafetensorsCommand.register_subcommand(commands_parser)
29
+
30
+ # Let's go
31
+ args = parser.parse_args()
32
+
33
+ if not hasattr(args, "func"):
34
+ parser.print_help()
35
+ exit(1)
36
+
37
+ # Run
38
+ service = args.func(args)
39
+ service.run()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/env.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import platform
16
+ from argparse import ArgumentParser
17
+
18
+ import huggingface_hub
19
+
20
+ from .. import __version__ as version
21
+ from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
22
+ from . import BaseDiffusersCLICommand
23
+
24
+
25
+ def info_command_factory(_):
26
+ return EnvironmentCommand()
27
+
28
+
29
+ class EnvironmentCommand(BaseDiffusersCLICommand):
30
+ @staticmethod
31
+ def register_subcommand(parser: ArgumentParser):
32
+ download_parser = parser.add_parser("env")
33
+ download_parser.set_defaults(func=info_command_factory)
34
+
35
+ def run(self):
36
+ hub_version = huggingface_hub.__version__
37
+
38
+ pt_version = "not installed"
39
+ pt_cuda_available = "NA"
40
+ if is_torch_available():
41
+ import torch
42
+
43
+ pt_version = torch.__version__
44
+ pt_cuda_available = torch.cuda.is_available()
45
+
46
+ transformers_version = "not installed"
47
+ if is_transformers_available():
48
+ import transformers
49
+
50
+ transformers_version = transformers.__version__
51
+
52
+ accelerate_version = "not installed"
53
+ if is_accelerate_available():
54
+ import accelerate
55
+
56
+ accelerate_version = accelerate.__version__
57
+
58
+ xformers_version = "not installed"
59
+ if is_xformers_available():
60
+ import xformers
61
+
62
+ xformers_version = xformers.__version__
63
+
64
+ info = {
65
+ "`diffusers` version": version,
66
+ "Platform": platform.platform(),
67
+ "Python version": platform.python_version(),
68
+ "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
69
+ "Huggingface_hub version": hub_version,
70
+ "Transformers version": transformers_version,
71
+ "Accelerate version": accelerate_version,
72
+ "xFormers version": xformers_version,
73
+ "Using GPU in script?": "<fill in>",
74
+ "Using distributed or parallel set-up in script?": "<fill in>",
75
+ }
76
+
77
+ print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
78
+ print(self.format_dict(info))
79
+
80
+ return info
81
+
82
+ @staticmethod
83
+ def format_dict(d):
84
+ return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
evalkit_tf437/lib/python3.10/site-packages/diffusers/commands/fp16_safetensors.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Usage example:
17
+ diffusers-cli fp16_safetensors --ckpt_id=openai/shap-e --fp16 --use_safetensors
18
+ """
19
+
20
+ import glob
21
+ import json
22
+ import warnings
23
+ from argparse import ArgumentParser, Namespace
24
+ from importlib import import_module
25
+
26
+ import huggingface_hub
27
+ import torch
28
+ from huggingface_hub import hf_hub_download
29
+ from packaging import version
30
+
31
+ from ..utils import logging
32
+ from . import BaseDiffusersCLICommand
33
+
34
+
35
+ def conversion_command_factory(args: Namespace):
36
+ if args.use_auth_token:
37
+ warnings.warn(
38
+ "The `--use_auth_token` flag is deprecated and will be removed in a future version. Authentication is now"
39
+ " handled automatically if user is logged in."
40
+ )
41
+ return FP16SafetensorsCommand(args.ckpt_id, args.fp16, args.use_safetensors)
42
+
43
+
44
+ class FP16SafetensorsCommand(BaseDiffusersCLICommand):
45
+ @staticmethod
46
+ def register_subcommand(parser: ArgumentParser):
47
+ conversion_parser = parser.add_parser("fp16_safetensors")
48
+ conversion_parser.add_argument(
49
+ "--ckpt_id",
50
+ type=str,
51
+ help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
52
+ )
53
+ conversion_parser.add_argument(
54
+ "--fp16", action="store_true", help="If serializing the variables in FP16 precision."
55
+ )
56
+ conversion_parser.add_argument(
57
+ "--use_safetensors", action="store_true", help="If serializing in the safetensors format."
58
+ )
59
+ conversion_parser.add_argument(
60
+ "--use_auth_token",
61
+ action="store_true",
62
+ help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
63
+ )
64
+ conversion_parser.set_defaults(func=conversion_command_factory)
65
+
66
+ def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool):
67
+ self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
68
+ self.ckpt_id = ckpt_id
69
+ self.local_ckpt_dir = f"/tmp/{ckpt_id}"
70
+ self.fp16 = fp16
71
+
72
+ self.use_safetensors = use_safetensors
73
+
74
+ if not self.use_safetensors and not self.fp16:
75
+ raise NotImplementedError(
76
+ "When `use_safetensors` and `fp16` both are False, then this command is of no use."
77
+ )
78
+
79
+ def run(self):
80
+ if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
81
+ raise ImportError(
82
+ "The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
83
+ " installation."
84
+ )
85
+ else:
86
+ from huggingface_hub import create_commit
87
+ from huggingface_hub._commit_api import CommitOperationAdd
88
+
89
+ model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json")
90
+ with open(model_index, "r") as f:
91
+ pipeline_class_name = json.load(f)["_class_name"]
92
+ pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
93
+ self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
94
+
95
+ # Load the appropriate pipeline. We could have use `DiffusionPipeline`
96
+ # here, but just to avoid any rough edge cases.
97
+ pipeline = pipeline_class.from_pretrained(
98
+ self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32
99
+ )
100
+ pipeline.save_pretrained(
101
+ self.local_ckpt_dir,
102
+ safe_serialization=True if self.use_safetensors else False,
103
+ variant="fp16" if self.fp16 else None,
104
+ )
105
+ self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
106
+
107
+ # Fetch all the paths.
108
+ if self.fp16:
109
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
110
+ elif self.use_safetensors:
111
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
112
+
113
+ # Prepare for the PR.
114
+ commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
115
+ operations = []
116
+ for path in modified_paths:
117
+ operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
118
+
119
+ # Open the PR.
120
+ commit_description = (
121
+ "Variables converted by the [`diffusers`' `fp16_safetensors`"
122
+ " CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
123
+ )
124
+ hub_pr_url = create_commit(
125
+ repo_id=self.ckpt_id,
126
+ operations=operations,
127
+ commit_message=commit_message,
128
+ commit_description=commit_description,
129
+ repo_type="model",
130
+ create_pr=True,
131
+ ).pr_url
132
+ self.logger.info(f"PR created here: {hub_pr_url}.")
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_amused.cpython-310.pyc ADDED
Binary file (5.18 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_consistency_decoder.cpython-310.pyc ADDED
Binary file (6.87 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_consistency_models.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddim.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddim_flax.cpython-310.pyc ADDED
Binary file (9.79 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddpm.cpython-310.pyc ADDED
Binary file (17.9 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_ddpm_parallel.cpython-310.pyc ADDED
Binary file (20.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_deis_multistep.cpython-310.pyc ADDED
Binary file (23.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep.cpython-310.pyc ADDED
Binary file (31.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep_flax.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_multistep_inverse.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_dpmsolver_sde.cpython-310.pyc ADDED
Binary file (19.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_edm_dpmsolver_multistep.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_euler_discrete_flax.cpython-310.pyc ADDED
Binary file (9.31 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/diffusers/schedulers/__pycache__/scheduling_k_dpm_2_discrete.cpython-310.pyc ADDED
Binary file (14.8 kB). View file