applied-ai-018 commited on
Commit
73a76f1
·
verified ·
1 Parent(s): 6efc50c

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. llmeval-env/lib/python3.10/site-packages/jinja2-3.1.4.dist-info/entry_points.txt +3 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/__init__.py +535 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/abc.py +111 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/conftest.py +74 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/galgebra.py +1 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/physics/hydrogen.py +265 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py +66 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/body.py +611 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py +779 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py +2163 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py +279 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py +741 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py +477 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py +443 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/method.py +39 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/models.py +230 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py +281 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py +366 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/system.py +445 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py +1144 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py +212 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py +115 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py +46 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py +5 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py +117 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py +245 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/physics/sho.py +95 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__init__.py +0 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py +191 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py +126 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py +57 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py +84 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_pring.py +41 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py +50 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py +1280 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_sho.py +21 -0
llmeval-env/lib/python3.10/site-packages/jinja2-3.1.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [babel.extractors]
2
+ jinja2=jinja2.ext:babel_extract[i18n]
3
+
llmeval-env/lib/python3.10/site-packages/sympy/__init__.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SymPy is a Python library for symbolic mathematics. It aims to become a
3
+ full-featured computer algebra system (CAS) while keeping the code as simple
4
+ as possible in order to be comprehensible and easily extensible. SymPy is
5
+ written entirely in Python. It depends on mpmath, and other external libraries
6
+ may be optionally for things like plotting support.
7
+
8
+ See the webpage for more information and documentation:
9
+
10
+ https://sympy.org
11
+
12
+ """
13
+
14
+
15
+ import sys
16
+ if sys.version_info < (3, 8):
17
+ raise ImportError("Python version 3.8 or above is required for SymPy.")
18
+ del sys
19
+
20
+
21
+ try:
22
+ import mpmath
23
+ except ImportError:
24
+ raise ImportError("SymPy now depends on mpmath as an external library. "
25
+ "See https://docs.sympy.org/latest/install.html#mpmath for more information.")
26
+
27
+ del mpmath
28
+
29
+ from sympy.release import __version__
30
+ from sympy.core.cache import lazy_function
31
+
32
+ if 'dev' in __version__:
33
+ def enable_warnings():
34
+ import warnings
35
+ warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
36
+ del warnings
37
+ enable_warnings()
38
+ del enable_warnings
39
+
40
+
41
+ def __sympy_debug():
42
+ # helper function so we don't import os globally
43
+ import os
44
+ debug_str = os.getenv('SYMPY_DEBUG', 'False')
45
+ if debug_str in ('True', 'False'):
46
+ return eval(debug_str)
47
+ else:
48
+ raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
49
+ debug_str)
50
+ SYMPY_DEBUG = __sympy_debug() # type: bool
51
+
52
+ from .core import (sympify, SympifyError, cacheit, Basic, Atom,
53
+ preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol,
54
+ Wild, Dummy, symbols, var, Number, Float, Rational, Integer,
55
+ NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo,
56
+ AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log,
57
+ Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality,
58
+ GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan,
59
+ vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass,
60
+ Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log,
61
+ expand_func, expand_trig, expand_complex, expand_multinomial, nfloat,
62
+ expand_power_base, expand_power_exp, arity, PrecisionExhausted, N,
63
+ evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate,
64
+ Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use,
65
+ postorder_traversal, default_sort_key, ordered)
66
+
67
+ from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor,
68
+ Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map,
69
+ true, false, satisfiable)
70
+
71
+ from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext,
72
+ assuming, Q, ask, register_handler, remove_handler, refine)
73
+
74
+ from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr,
75
+ degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo,
76
+ pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert,
77
+ subresultants, resultant, discriminant, cofactors, gcd_list, gcd,
78
+ lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose,
79
+ decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf,
80
+ factor_list, factor, intervals, refine_root, count_roots, real_roots,
81
+ nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner,
82
+ is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner,
83
+ interpolate, rational_interpolate, viete, together,
84
+ BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed,
85
+ OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed,
86
+ IsomorphismFailed, ExtraneousFactors, EvaluationFailed,
87
+ RefinementFailed, CoercionFailed, NotInvertible, NotReversible,
88
+ NotAlgebraic, DomainError, PolynomialError, UnificationFailed,
89
+ GeneratorsError, GeneratorsNeeded, ComputationFailed,
90
+ UnivariatePolynomialError, MultivariatePolynomialError,
91
+ PolificationFailed, OptionError, FlagError, minpoly,
92
+ minimal_polynomial, primitive_element, field_isomorphism,
93
+ to_number_field, isolate, round_two, prime_decomp, prime_valuation,
94
+ galois_group, itermonomials, Monomial, lex, grlex,
95
+ grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf,
96
+ ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing,
97
+ RationalField, RealField, ComplexField, PythonFiniteField,
98
+ GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational,
99
+ GMPYRationalField, AlgebraicField, PolynomialRing, FractionField,
100
+ ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python,
101
+ QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW,
102
+ construct_domain, swinnerton_dyer_poly, cyclotomic_poly,
103
+ symmetric_poly, random_poly, interpolating_poly, jacobi_poly,
104
+ chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly,
105
+ legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list,
106
+ Options, ring, xring, vring, sring, field, xfield, vfield, sfield)
107
+
108
+ from .series import (Order, O, limit, Limit, gruntz, series, approximants,
109
+ residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul,
110
+ fourier_series, fps, difference_delta, limit_seq)
111
+
112
+ from .functions import (factorial, factorial2, rf, ff, binomial,
113
+ RisingFactorial, FallingFactorial, subfactorial, carmichael,
114
+ fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler,
115
+ catalan, genocchi, andre, partition, sqrt, root, Min, Max, Id,
116
+ real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift,
117
+ periodic_argument, unbranched_argument, principal_branch, transpose,
118
+ adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc,
119
+ asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log,
120
+ LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh,
121
+ acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold,
122
+ piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv,
123
+ Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma,
124
+ lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma,
125
+ multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk,
126
+ LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside,
127
+ bspline_basis, bspline_basis_set, interpolating_spline, besselj,
128
+ bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1,
129
+ hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper,
130
+ meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob,
131
+ chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre,
132
+ assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c,
133
+ Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus,
134
+ mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized)
135
+
136
+ from .ntheory import (nextprime, prevprime, prime, primepi, primerange,
137
+ randprime, Sieve, sieve, primorial, cycle_length, composite,
138
+ compositepi, isprime, divisors, proper_divisors, factorint,
139
+ multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors,
140
+ totient, trailing, divisor_count, proper_divisor_count, divisor_sigma,
141
+ factorrat, reduced_totient, primenu, primeomega,
142
+ mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant,
143
+ is_deficient, is_amicable, abundance, npartitions, is_primitive_root,
144
+ is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod,
145
+ quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue,
146
+ sqrt_mod_iter, mobius, discrete_log, quadratic_congruence,
147
+ binomial_coefficients, binomial_coefficients_list,
148
+ multinomial_coefficients, continued_fraction_periodic,
149
+ continued_fraction_iterator, continued_fraction_reduce,
150
+ continued_fraction_convergents, continued_fraction, egyptian_fraction)
151
+
152
+ from .concrete import product, Product, summation, Sum
153
+
154
+ from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform,
155
+ inverse_mobius_transform, convolution, covering_product,
156
+ intersecting_product)
157
+
158
+ from .simplify import (simplify, hypersimp, hypersimilar, logcombine,
159
+ separatevars, posify, besselsimp, kroneckersimp, signsimp,
160
+ nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand,
161
+ collect, rcollect, radsimp, collect_const, fraction, numer, denom,
162
+ trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp,
163
+ ratsimp, ratsimpmodprime)
164
+
165
+ from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet,
166
+ Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet,
167
+ Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal,
168
+ OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet,
169
+ Integers, Rationals)
170
+
171
+ from .solvers import (solve, solve_linear_system, solve_linear_system_LU,
172
+ solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick,
173
+ inv_quick, check_assumptions, failing_assumptions, diophantine,
174
+ rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol,
175
+ classify_ode, dsolve, homogeneous_order, solve_poly_system,
176
+ solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul,
177
+ pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities,
178
+ reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality,
179
+ solve_rational_inequalities, solve_univariate_inequality, decompogen,
180
+ solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution)
181
+
182
+ from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt,
183
+ casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy,
184
+ matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
185
+ rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix,
186
+ DeferredVector, MatrixBase, Matrix, MutableMatrix,
187
+ MutableSparseMatrix, banded, ImmutableDenseMatrix,
188
+ ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice,
189
+ BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse,
190
+ MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose,
191
+ ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols,
192
+ Adjoint, hadamard_product, HadamardProduct, HadamardPower,
193
+ Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix,
194
+ DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct,
195
+ PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1,
196
+ rot_ccw_axis2, rot_ccw_axis3, rot_givens)
197
+
198
+ from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D,
199
+ Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle,
200
+ Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid,
201
+ convex_hull, idiff, intersection, closest_points, farthest_points,
202
+ GeometryError, Curve, Parabola)
203
+
204
+ from .utilities import (flatten, group, take, subsets, variations,
205
+ numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes,
206
+ sift, topological_sort, unflatten, has_dups, has_variety, reshape,
207
+ rotations, filldedent, lambdify,
208
+ threaded, xthreaded, public, memoize_property, timed)
209
+
210
+ from .integrals import (integrate, Integral, line_integrate, mellin_transform,
211
+ inverse_mellin_transform, MellinTransform, InverseMellinTransform,
212
+ laplace_transform, inverse_laplace_transform, LaplaceTransform,
213
+ InverseLaplaceTransform, fourier_transform, inverse_fourier_transform,
214
+ FourierTransform, InverseFourierTransform, sine_transform,
215
+ inverse_sine_transform, SineTransform, InverseSineTransform,
216
+ cosine_transform, inverse_cosine_transform, CosineTransform,
217
+ InverseCosineTransform, hankel_transform, inverse_hankel_transform,
218
+ HankelTransform, InverseHankelTransform, singularityintegrate)
219
+
220
+ from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure,
221
+ get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray,
222
+ MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray,
223
+ tensorproduct, tensorcontraction, tensordiagonal, derive_by_array,
224
+ permutedims, Array, DenseNDimArray, SparseNDimArray)
225
+
226
+ from .parsing import parse_expr
227
+
228
+ from .calculus import (euler_equations, singularities, is_increasing,
229
+ is_strictly_increasing, is_decreasing, is_strictly_decreasing,
230
+ is_monotonic, finite_diff_weights, apply_finite_diff,
231
+ differentiate_finite, periodicity, not_empty_in, AccumBounds,
232
+ is_convex, stationary_points, minimum, maximum)
233
+
234
+ from .algebras import Quaternion
235
+
236
+ from .printing import (pager_print, pretty, pretty_print, pprint,
237
+ pprint_use_unicode, pprint_try_use_unicode, latex, print_latex,
238
+ multiline_latex, mathml, print_mathml, python, print_python, pycode,
239
+ ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode,
240
+ print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code,
241
+ mathematica_code, octave_code, rust_code, print_gtk, preview, srepr,
242
+ print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint,
243
+ maple_code, print_maple_code)
244
+
245
+ test = lazy_function('sympy.testing.runtests', 'test')
246
+ doctest = lazy_function('sympy.testing.runtests', 'doctest')
247
+
248
+ # This module causes conflicts with other modules:
249
+ # from .stats import *
250
+ # Adds about .04-.05 seconds of import time
251
+ # from combinatorics import *
252
+ # This module is slow to import:
253
+ #from physics import units
254
+ from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
255
+ from .interactive import init_session, init_printing, interactive_traversal
256
+
257
+ evalf._create_evalf_table()
258
+
259
+ __all__ = [
260
+ '__version__',
261
+
262
+ # sympy.core
263
+ 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom',
264
+ 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr',
265
+ 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float',
266
+ 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm',
267
+ 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp',
268
+ 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod',
269
+ 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality',
270
+ 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan',
271
+ 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative',
272
+ 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError',
273
+ 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig',
274
+ 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base',
275
+ 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple',
276
+ 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan',
277
+ 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use',
278
+ 'postorder_traversal', 'default_sort_key', 'ordered',
279
+
280
+ # sympy.logic
281
+ 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
282
+ 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
283
+ 'bool_map', 'true', 'false', 'satisfiable',
284
+
285
+ # sympy.assumptions
286
+ 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q',
287
+ 'ask', 'register_handler', 'remove_handler', 'refine',
288
+
289
+ # sympy.polys
290
+ 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree',
291
+ 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo',
292
+ 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert',
293
+ 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list',
294
+ 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content',
295
+ 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff',
296
+ 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor',
297
+ 'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots',
298
+ 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner',
299
+ 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner',
300
+ 'interpolate', 'rational_interpolate', 'viete', 'together',
301
+ 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed',
302
+ 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed',
303
+ 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed',
304
+ 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible',
305
+ 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed',
306
+ 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed',
307
+ 'UnivariatePolynomialError', 'MultivariatePolynomialError',
308
+ 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly',
309
+ 'minimal_polynomial', 'primitive_element', 'field_isomorphism',
310
+ 'to_number_field', 'isolate', 'round_two', 'prime_decomp',
311
+ 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex',
312
+ 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf',
313
+ 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField',
314
+ 'IntegerRing', 'RationalField', 'RealField', 'ComplexField',
315
+ 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
316
+ 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
317
+ 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain',
318
+ 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
319
+ 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW',
320
+ 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly',
321
+ 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly',
322
+ 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly',
323
+ 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list',
324
+ 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield',
325
+ 'sfield',
326
+
327
+ # sympy.series
328
+ 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
329
+ 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd',
330
+ 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq',
331
+
332
+ # sympy.functions
333
+ 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
334
+ 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas',
335
+ 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan',
336
+ 'genocchi', 'andre', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root',
337
+ 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
338
+ 'periodic_argument', 'unbranched_argument', 'principal_branch',
339
+ 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan',
340
+ 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc',
341
+ 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh',
342
+ 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
343
+ 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise',
344
+ 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2',
345
+ 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si',
346
+ 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma',
347
+ 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma',
348
+ 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita',
349
+ 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside',
350
+ 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj',
351
+ 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn',
352
+ 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
353
+ 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre',
354
+ 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu',
355
+ 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre',
356
+ 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm',
357
+ 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta',
358
+ 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc',
359
+ 'betainc_regularized',
360
+
361
+ # sympy.ntheory
362
+ 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime',
363
+ 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi',
364
+ 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity',
365
+ 'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient',
366
+ 'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma',
367
+ 'factorrat', 'reduced_totient', 'primenu', 'primeomega',
368
+ 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime',
369
+ 'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions',
370
+ 'is_primitive_root', 'is_quad_residue', 'legendre_symbol',
371
+ 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues',
372
+ 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter',
373
+ 'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients',
374
+ 'binomial_coefficients_list', 'multinomial_coefficients',
375
+ 'continued_fraction_periodic', 'continued_fraction_iterator',
376
+ 'continued_fraction_reduce', 'continued_fraction_convergents',
377
+ 'continued_fraction', 'egyptian_fraction',
378
+
379
+ # sympy.concrete
380
+ 'product', 'Product', 'summation', 'Sum',
381
+
382
+ # sympy.discrete
383
+ 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
384
+ 'inverse_mobius_transform', 'convolution', 'covering_product',
385
+ 'intersecting_product',
386
+
387
+ # sympy.simplify
388
+ 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
389
+ 'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
390
+ 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath',
391
+ 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const',
392
+ 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp',
393
+ 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime',
394
+
395
+ # sympy.sets
396
+ 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet',
397
+ 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference',
398
+ 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet',
399
+ 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals',
400
+ 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes',
401
+
402
+ # sympy.solvers
403
+ 'solve', 'solve_linear_system', 'solve_linear_system_LU',
404
+ 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
405
+ 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
406
+ 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
407
+ 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
408
+ 'solve_poly_system', 'solve_triangulated', 'pde_separate',
409
+ 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde',
410
+ 'checkpdesol', 'ode_order', 'reduce_inequalities',
411
+ 'reduce_abs_inequality', 'reduce_abs_inequalities',
412
+ 'solve_poly_inequality', 'solve_rational_inequalities',
413
+ 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve',
414
+ 'linear_eq_to_matrix', 'nonlinsolve', 'substitution',
415
+
416
+ # sympy.matrices
417
+ 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag',
418
+ 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy',
419
+ 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1',
420
+ 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros',
421
+ 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix',
422
+ 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix',
423
+ 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice',
424
+ 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse',
425
+ 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace',
426
+ 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse',
427
+ 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct',
428
+ 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix',
429
+ 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct',
430
+ 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix',
431
+ 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2',
432
+ 'rot_ccw_axis3', 'rot_givens',
433
+
434
+ # sympy.geometry
435
+ 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D',
436
+ 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse',
437
+ 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg',
438
+ 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection',
439
+ 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola',
440
+
441
+ # sympy.utilities
442
+ 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols',
443
+ 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift',
444
+ 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape',
445
+ 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded',
446
+ 'public', 'memoize_property', 'timed',
447
+
448
+ # sympy.integrals
449
+ 'integrate', 'Integral', 'line_integrate', 'mellin_transform',
450
+ 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform',
451
+ 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform',
452
+ 'InverseLaplaceTransform', 'fourier_transform',
453
+ 'inverse_fourier_transform', 'FourierTransform',
454
+ 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
455
+ 'SineTransform', 'InverseSineTransform', 'cosine_transform',
456
+ 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
457
+ 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
458
+ 'InverseHankelTransform', 'singularityintegrate',
459
+
460
+ # sympy.tensor
461
+ 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure',
462
+ 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
463
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
464
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
465
+ 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray',
466
+
467
+ # sympy.parsing
468
+ 'parse_expr',
469
+
470
+ # sympy.calculus
471
+ 'euler_equations', 'singularities', 'is_increasing',
472
+ 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing',
473
+ 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff',
474
+ 'differentiate_finite', 'periodicity', 'not_empty_in',
475
+ 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum',
476
+
477
+ # sympy.algebras
478
+ 'Quaternion',
479
+
480
+ # sympy.printing
481
+ 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode',
482
+ 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex',
483
+ 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode',
484
+ 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode',
485
+ 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode',
486
+ 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk',
487
+ 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr',
488
+ 'TableForm', 'dotprint', 'maple_code', 'print_maple_code',
489
+
490
+ # sympy.plotting
491
+ 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric',
492
+
493
+ # sympy.interactive
494
+ 'init_session', 'init_printing', 'interactive_traversal',
495
+
496
+ # sympy.testing
497
+ 'test', 'doctest',
498
+ ]
499
+
500
+
501
+ #===========================================================================#
502
+ # #
503
+ # XXX: The names below were importable before SymPy 1.6 using #
504
+ # #
505
+ # from sympy import * #
506
+ # #
507
+ # This happened implicitly because there was no __all__ defined in this #
508
+ # __init__.py file. Not every package is imported. The list matches what #
509
+ # would have been imported before. It is possible that these packages will #
510
+ # not be imported by a star-import from sympy in future. #
511
+ # #
512
+ #===========================================================================#
513
+
514
+
515
+ __all__.extend((
516
+ 'algebras',
517
+ 'assumptions',
518
+ 'calculus',
519
+ 'concrete',
520
+ 'discrete',
521
+ 'external',
522
+ 'functions',
523
+ 'geometry',
524
+ 'interactive',
525
+ 'multipledispatch',
526
+ 'ntheory',
527
+ 'parsing',
528
+ 'plotting',
529
+ 'polys',
530
+ 'printing',
531
+ 'release',
532
+ 'strategies',
533
+ 'tensor',
534
+ 'utilities',
535
+ ))
llmeval-env/lib/python3.10/site-packages/sympy/abc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module exports all latin and greek letters as Symbols, so you can
3
+ conveniently do
4
+
5
+ >>> from sympy.abc import x, y
6
+
7
+ instead of the slightly more clunky-looking
8
+
9
+ >>> from sympy import symbols
10
+ >>> x, y = symbols('x y')
11
+
12
+ Caveats
13
+ =======
14
+
15
+ 1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
16
+ ``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
17
+ from both ``sympy.abc`` and ``sympy``, the second import will "win".
18
+ This is an issue only for * imports, which should only be used for short-lived
19
+ code such as interactive sessions and throwaway scripts that do not survive
20
+ until the next SymPy upgrade, where ``sympy`` may contain a different set of
21
+ names.
22
+
23
+ 2. This module does not define symbol names on demand, i.e.
24
+ ``from sympy.abc import foo`` will be reported as an error because
25
+ ``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
26
+ you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
27
+ You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
28
+ sticking with one and only one way to get the symbols does tend to make the code
29
+ more readable.
30
+
31
+ The module also defines some special names to help detect which names clash
32
+ with the default SymPy namespace.
33
+
34
+ ``_clash1`` defines all the single letter variables that clash with
35
+ SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
36
+ and ``_clash`` is the union of both. These can be passed for ``locals``
37
+ during sympification if one desires Symbols rather than the non-Symbol
38
+ objects for those names.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy import S
44
+ >>> from sympy.abc import _clash1, _clash2, _clash
45
+ >>> S("Q & C", locals=_clash1)
46
+ C & Q
47
+ >>> S('pi(x)', locals=_clash2)
48
+ pi(x)
49
+ >>> S('pi(C, Q)', locals=_clash)
50
+ pi(C, Q)
51
+
52
+ """
53
+
54
+ from typing import Any, Dict as tDict
55
+
56
+ import string
57
+
58
+ from .core import Symbol, symbols
59
+ from .core.alphabets import greeks
60
+ from sympy.parsing.sympy_parser import null
61
+
62
+ ##### Symbol definitions #####
63
+
64
+ # Implementation note: The easiest way to avoid typos in the symbols()
65
+ # parameter is to copy it from the left-hand side of the assignment.
66
+
67
+ a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
68
+ k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
69
+ u, v, w, x, y, z = symbols('u, v, w, x, y, z')
70
+
71
+ A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
72
+ K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
73
+ U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
74
+
75
+ alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
76
+ epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
77
+ iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
78
+ nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
79
+ rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
80
+ phi, chi, psi, omega = symbols('phi, chi, psi, omega')
81
+
82
+
83
+ ##### Clashing-symbols diagnostics #####
84
+
85
+ # We want to know which names in SymPy collide with those in here.
86
+ # This is mostly for diagnosing SymPy's namespace during SymPy development.
87
+
88
+ _latin = list(string.ascii_letters)
89
+ # QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
90
+ _greek = list(greeks) # make a copy, so we can mutate it
91
+ # Note: We import lamda since lambda is a reserved keyword in Python
92
+ _greek.remove("lambda")
93
+ _greek.append("lamda")
94
+
95
+ ns: tDict[str, Any] = {}
96
+ exec('from sympy import *', ns)
97
+ _clash1: tDict[str, Any] = {}
98
+ _clash2: tDict[str, Any] = {}
99
+ while ns:
100
+ _k, _ = ns.popitem()
101
+ if _k in _greek:
102
+ _clash2[_k] = null
103
+ _greek.remove(_k)
104
+ elif _k in _latin:
105
+ _clash1[_k] = null
106
+ _latin.remove(_k)
107
+ _clash = {}
108
+ _clash.update(_clash1)
109
+ _clash.update(_clash2)
110
+
111
+ del _latin, _greek, Symbol, _k, null
llmeval-env/lib/python3.10/site-packages/sympy/conftest.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys._running_pytest = True # type: ignore
3
+ from sympy.external.importtools import version_tuple
4
+
5
+ import pytest
6
+ from sympy.core.cache import clear_cache, USE_CACHE
7
+ from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY
8
+ from sympy.utilities.misc import ARCH
9
+ import re
10
+
11
+ sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
12
+
13
+ def process_split(config, items):
14
+ split = config.getoption("--split")
15
+ if not split:
16
+ return
17
+ m = sp.match(split)
18
+ if not m:
19
+ raise ValueError("split must be a string of the form a/b "
20
+ "where a and b are ints.")
21
+ i, t = map(int, m.groups())
22
+ start, end = (i-1)*len(items)//t, i*len(items)//t
23
+
24
+ if i < t:
25
+ # remove elements from end of list first
26
+ del items[end:]
27
+ del items[:start]
28
+
29
+
30
+ def pytest_report_header(config):
31
+ s = "architecture: %s\n" % ARCH
32
+ s += "cache: %s\n" % USE_CACHE
33
+ version = ''
34
+ if GROUND_TYPES =='gmpy':
35
+ if HAS_GMPY == 1:
36
+ import gmpy
37
+ elif HAS_GMPY == 2:
38
+ import gmpy2 as gmpy
39
+ version = gmpy.version()
40
+ s += "ground types: %s %s\n" % (GROUND_TYPES, version)
41
+ return s
42
+
43
+
44
+ def pytest_terminal_summary(terminalreporter):
45
+ if (terminalreporter.stats.get('error', None) or
46
+ terminalreporter.stats.get('failed', None)):
47
+ terminalreporter.write_sep(
48
+ ' ', 'DO *NOT* COMMIT!', red=True, bold=True)
49
+
50
+
51
+ def pytest_addoption(parser):
52
+ parser.addoption("--split", action="store", default="",
53
+ help="split tests")
54
+
55
+
56
+ def pytest_collection_modifyitems(config, items):
57
+ """ pytest hook. """
58
+ # handle splits
59
+ process_split(config, items)
60
+
61
+
62
+ @pytest.fixture(autouse=True, scope='module')
63
+ def file_clear_cache():
64
+ clear_cache()
65
+
66
+ @pytest.fixture(autouse=True, scope='module')
67
+ def check_disabled(request):
68
+ if getattr(request.module, 'disabled', False):
69
+ pytest.skip("test requirements not met.")
70
+ elif getattr(request.module, 'ipython', False):
71
+ # need to check version and options for ipython tests
72
+ if (version_tuple(pytest.__version__) < version_tuple('2.6.3') and
73
+ pytest.config.getvalue('-s') != 'no'):
74
+ pytest.skip("run py.test with -s or upgrade to newer version.")
llmeval-env/lib/python3.10/site-packages/sympy/galgebra.py ADDED
@@ -0,0 +1 @@
 
 
1
+ raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""")
llmeval-env/lib/python3.10/site-packages/sympy/physics/hydrogen.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Float
2
+ from sympy.core.singleton import S
3
+ from sympy.functions.combinatorial.factorials import factorial
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.special.polynomials import assoc_laguerre
7
+ from sympy.functions.special.spherical_harmonics import Ynm
8
+
9
+
10
+ def R_nl(n, l, r, Z=1):
11
+ """
12
+ Returns the Hydrogen radial wavefunction R_{nl}.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ n : integer
18
+ Principal Quantum Number which is
19
+ an integer with possible values as 1, 2, 3, 4,...
20
+ l : integer
21
+ ``l`` is the Angular Momentum Quantum Number with
22
+ values ranging from 0 to ``n-1``.
23
+ r :
24
+ Radial coordinate.
25
+ Z :
26
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
27
+
28
+ Everything is in Hartree atomic units.
29
+
30
+ Examples
31
+ ========
32
+
33
+ >>> from sympy.physics.hydrogen import R_nl
34
+ >>> from sympy.abc import r, Z
35
+ >>> R_nl(1, 0, r, Z)
36
+ 2*sqrt(Z**3)*exp(-Z*r)
37
+ >>> R_nl(2, 0, r, Z)
38
+ sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4
39
+ >>> R_nl(2, 1, r, Z)
40
+ sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12
41
+
42
+ For Hydrogen atom, you can just use the default value of Z=1:
43
+
44
+ >>> R_nl(1, 0, r)
45
+ 2*exp(-r)
46
+ >>> R_nl(2, 0, r)
47
+ sqrt(2)*(2 - r)*exp(-r/2)/4
48
+ >>> R_nl(3, 0, r)
49
+ 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27
50
+
51
+ For Silver atom, you would use Z=47:
52
+
53
+ >>> R_nl(1, 0, r, Z=47)
54
+ 94*sqrt(47)*exp(-47*r)
55
+ >>> R_nl(2, 0, r, Z=47)
56
+ 47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4
57
+ >>> R_nl(3, 0, r, Z=47)
58
+ 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27
59
+
60
+ The normalization of the radial wavefunction is:
61
+
62
+ >>> from sympy import integrate, oo
63
+ >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo))
64
+ 1
65
+ >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo))
66
+ 1
67
+ >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo))
68
+ 1
69
+
70
+ It holds for any atomic number:
71
+
72
+ >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo))
73
+ 1
74
+ >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo))
75
+ 1
76
+ >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo))
77
+ 1
78
+
79
+ """
80
+ # sympify arguments
81
+ n, l, r, Z = map(S, [n, l, r, Z])
82
+ # radial quantum number
83
+ n_r = n - l - 1
84
+ # rescaled "r"
85
+ a = 1/Z # Bohr radius
86
+ r0 = 2 * r / (n * a)
87
+ # normalization coefficient
88
+ C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l)))
89
+ # This is an equivalent normalization coefficient, that can be found in
90
+ # some books. Both coefficients seem to be the same fast:
91
+ # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l)))
92
+ return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2)
93
+
94
+
95
+ def Psi_nlm(n, l, m, r, phi, theta, Z=1):
96
+ """
97
+ Returns the Hydrogen wave function psi_{nlm}. It's the product of
98
+ the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}.
99
+
100
+ Parameters
101
+ ==========
102
+
103
+ n : integer
104
+ Principal Quantum Number which is
105
+ an integer with possible values as 1, 2, 3, 4,...
106
+ l : integer
107
+ ``l`` is the Angular Momentum Quantum Number with
108
+ values ranging from 0 to ``n-1``.
109
+ m : integer
110
+ ``m`` is the Magnetic Quantum Number with values
111
+ ranging from ``-l`` to ``l``.
112
+ r :
113
+ radial coordinate
114
+ phi :
115
+ azimuthal angle
116
+ theta :
117
+ polar angle
118
+ Z :
119
+ atomic number (1 for Hydrogen, 2 for Helium, ...)
120
+
121
+ Everything is in Hartree atomic units.
122
+
123
+ Examples
124
+ ========
125
+
126
+ >>> from sympy.physics.hydrogen import Psi_nlm
127
+ >>> from sympy import Symbol
128
+ >>> r=Symbol("r", positive=True)
129
+ >>> phi=Symbol("phi", real=True)
130
+ >>> theta=Symbol("theta", real=True)
131
+ >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True)
132
+ >>> Psi_nlm(1,0,0,r,phi,theta,Z)
133
+ Z**(3/2)*exp(-Z*r)/sqrt(pi)
134
+ >>> Psi_nlm(2,1,1,r,phi,theta,Z)
135
+ -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi))
136
+
137
+ Integrating the absolute square of a hydrogen wavefunction psi_{nlm}
138
+ over the whole space leads 1.
139
+
140
+ The normalization of the hydrogen wavefunctions Psi_nlm is:
141
+
142
+ >>> from sympy import integrate, conjugate, pi, oo, sin
143
+ >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z)
144
+ >>> abs_sqrd=wf*conjugate(wf)
145
+ >>> jacobi=r**2*sin(theta)
146
+ >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi))
147
+ 1
148
+ """
149
+
150
+ # sympify arguments
151
+ n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z])
152
+ # check if values for n,l,m make physically sense
153
+ if n.is_integer and n < 1:
154
+ raise ValueError("'n' must be positive integer")
155
+ if l.is_integer and not (n > l):
156
+ raise ValueError("'n' must be greater than 'l'")
157
+ if m.is_integer and not (abs(m) <= l):
158
+ raise ValueError("|'m'| must be less or equal 'l'")
159
+ # return the hydrogen wave function
160
+ return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True)
161
+
162
+
163
+ def E_nl(n, Z=1):
164
+ """
165
+ Returns the energy of the state (n, l) in Hartree atomic units.
166
+
167
+ The energy does not depend on "l".
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ n : integer
173
+ Principal Quantum Number which is
174
+ an integer with possible values as 1, 2, 3, 4,...
175
+ Z :
176
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
177
+
178
+ Examples
179
+ ========
180
+
181
+ >>> from sympy.physics.hydrogen import E_nl
182
+ >>> from sympy.abc import n, Z
183
+ >>> E_nl(n, Z)
184
+ -Z**2/(2*n**2)
185
+ >>> E_nl(1)
186
+ -1/2
187
+ >>> E_nl(2)
188
+ -1/8
189
+ >>> E_nl(3)
190
+ -1/18
191
+ >>> E_nl(3, 47)
192
+ -2209/18
193
+
194
+ """
195
+ n, Z = S(n), S(Z)
196
+ if n.is_integer and (n < 1):
197
+ raise ValueError("'n' must be positive integer")
198
+ return -Z**2/(2*n**2)
199
+
200
+
201
+ def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")):
202
+ """
203
+ Returns the relativistic energy of the state (n, l, spin) in Hartree atomic
204
+ units.
205
+
206
+ The energy is calculated from the Dirac equation. The rest mass energy is
207
+ *not* included.
208
+
209
+ Parameters
210
+ ==========
211
+
212
+ n : integer
213
+ Principal Quantum Number which is
214
+ an integer with possible values as 1, 2, 3, 4,...
215
+ l : integer
216
+ ``l`` is the Angular Momentum Quantum Number with
217
+ values ranging from 0 to ``n-1``.
218
+ spin_up :
219
+ True if the electron spin is up (default), otherwise down
220
+ Z :
221
+ Atomic number (1 for Hydrogen, 2 for Helium, ...)
222
+ c :
223
+ Speed of light in atomic units. Default value is 137.035999037,
224
+ taken from https://arxiv.org/abs/1012.3627
225
+
226
+ Examples
227
+ ========
228
+
229
+ >>> from sympy.physics.hydrogen import E_nl_dirac
230
+ >>> E_nl_dirac(1, 0)
231
+ -0.500006656595360
232
+
233
+ >>> E_nl_dirac(2, 0)
234
+ -0.125002080189006
235
+ >>> E_nl_dirac(2, 1)
236
+ -0.125000416028342
237
+ >>> E_nl_dirac(2, 1, False)
238
+ -0.125002080189006
239
+
240
+ >>> E_nl_dirac(3, 0)
241
+ -0.0555562951740285
242
+ >>> E_nl_dirac(3, 1)
243
+ -0.0555558020932949
244
+ >>> E_nl_dirac(3, 1, False)
245
+ -0.0555562951740285
246
+ >>> E_nl_dirac(3, 2)
247
+ -0.0555556377366884
248
+ >>> E_nl_dirac(3, 2, False)
249
+ -0.0555558020932949
250
+
251
+ """
252
+ n, l, Z, c = map(S, [n, l, Z, c])
253
+ if not (l >= 0):
254
+ raise ValueError("'l' must be positive or zero")
255
+ if not (n > l):
256
+ raise ValueError("'n' must be greater than 'l'")
257
+ if (l == 0 and spin_up is False):
258
+ raise ValueError("Spin must be up for l==0.")
259
+ # skappa is sign*kappa, where sign contains the correct sign
260
+ if spin_up:
261
+ skappa = -l - 1
262
+ else:
263
+ skappa = -l
264
+ beta = sqrt(skappa**2 - Z**2/c**2)
265
+ return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ 'vector',
3
+
4
+ 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross',
5
+ 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations',
6
+ 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint',
7
+ 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl',
8
+ 'divergence', 'gradient', 'is_conservative', 'is_solenoidal',
9
+ 'scalar_potential', 'scalar_potential_difference',
10
+
11
+ 'KanesMethod',
12
+
13
+ 'RigidBody',
14
+
15
+ 'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum',
16
+ 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing',
17
+ 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols',
18
+
19
+ 'Particle',
20
+
21
+ 'LagrangesMethod',
22
+
23
+ 'Linearizer',
24
+
25
+ 'Body',
26
+
27
+ 'SymbolicSystem',
28
+
29
+ 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint',
30
+ 'SphericalJoint', 'WeldJoint',
31
+
32
+ 'JointsMethod'
33
+ ]
34
+
35
+ from sympy.physics import vector
36
+
37
+ from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point,
38
+ cross, dot, express, time_derivative, outer, kinematic_equations,
39
+ get_motion_params, partial_velocity, dynamicsymbols, vprint,
40
+ vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence,
41
+ gradient, is_conservative, is_solenoidal, scalar_potential,
42
+ scalar_potential_difference)
43
+
44
+ from .kane import KanesMethod
45
+
46
+ from .rigidbody import RigidBody
47
+
48
+ from .functions import (inertia, inertia_of_point_mass, linear_momentum,
49
+ angular_momentum, kinetic_energy, potential_energy, Lagrangian,
50
+ mechanics_printing, mprint, msprint, mpprint, mlatex, msubs,
51
+ find_dynamicsymbols)
52
+
53
+ from .particle import Particle
54
+
55
+ from .lagrange import LagrangesMethod
56
+
57
+ from .linearize import Linearizer
58
+
59
+ from .body import Body
60
+
61
+ from .system import SymbolicSystem
62
+
63
+ from .jointsmethod import JointsMethod
64
+
65
+ from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint,
66
+ SphericalJoint, WeldJoint)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/body.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import Symbol
2
+ from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic
3
+ from sympy.physics.mechanics import RigidBody, Particle, inertia
4
+
5
+ __all__ = ['Body']
6
+
7
+
8
+ # XXX: We use type:ignore because the classes RigidBody and Particle have
9
+ # inconsistent parallel axis methods that take different numbers of arguments.
10
+ class Body(RigidBody, Particle): # type: ignore
11
+ """
12
+ Body is a common representation of either a RigidBody or a Particle SymPy
13
+ object depending on what is passed in during initialization. If a mass is
14
+ passed in and central_inertia is left as None, the Particle object is
15
+ created. Otherwise a RigidBody object will be created.
16
+
17
+ Explanation
18
+ ===========
19
+
20
+ The attributes that Body possesses will be the same as a Particle instance
21
+ or a Rigid Body instance depending on which was created. Additional
22
+ attributes are listed below.
23
+
24
+ Attributes
25
+ ==========
26
+
27
+ name : string
28
+ The body's name
29
+ masscenter : Point
30
+ The point which represents the center of mass of the rigid body
31
+ frame : ReferenceFrame
32
+ The reference frame which the body is fixed in
33
+ mass : Sympifyable
34
+ The body's mass
35
+ inertia : (Dyadic, Point)
36
+ The body's inertia around its center of mass. This attribute is specific
37
+ to the rigid body form of Body and is left undefined for the Particle
38
+ form
39
+ loads : iterable
40
+ This list contains information on the different loads acting on the
41
+ Body. Forces are listed as a (point, vector) tuple and torques are
42
+ listed as (reference frame, vector) tuples.
43
+
44
+ Parameters
45
+ ==========
46
+
47
+ name : String
48
+ Defines the name of the body. It is used as the base for defining
49
+ body specific properties.
50
+ masscenter : Point, optional
51
+ A point that represents the center of mass of the body or particle.
52
+ If no point is given, a point is generated.
53
+ mass : Sympifyable, optional
54
+ A Sympifyable object which represents the mass of the body. If no
55
+ mass is passed, one is generated.
56
+ frame : ReferenceFrame, optional
57
+ The ReferenceFrame that represents the reference frame of the body.
58
+ If no frame is given, a frame is generated.
59
+ central_inertia : Dyadic, optional
60
+ Central inertia dyadic of the body. If none is passed while creating
61
+ RigidBody, a default inertia is generated.
62
+
63
+ Examples
64
+ ========
65
+
66
+ Default behaviour. This results in the creation of a RigidBody object for
67
+ which the mass, mass center, frame and inertia attributes are given default
68
+ values. ::
69
+
70
+ >>> from sympy.physics.mechanics import Body
71
+ >>> body = Body('name_of_body')
72
+
73
+ This next example demonstrates the code required to specify all of the
74
+ values of the Body object. Note this will also create a RigidBody version of
75
+ the Body object. ::
76
+
77
+ >>> from sympy import Symbol
78
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia
79
+ >>> from sympy.physics.mechanics import Body
80
+ >>> mass = Symbol('mass')
81
+ >>> masscenter = Point('masscenter')
82
+ >>> frame = ReferenceFrame('frame')
83
+ >>> ixx = Symbol('ixx')
84
+ >>> body_inertia = inertia(frame, ixx, 0, 0)
85
+ >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia)
86
+
87
+ The minimal code required to create a Particle version of the Body object
88
+ involves simply passing in a name and a mass. ::
89
+
90
+ >>> from sympy import Symbol
91
+ >>> from sympy.physics.mechanics import Body
92
+ >>> mass = Symbol('mass')
93
+ >>> body = Body('name_of_body', mass=mass)
94
+
95
+ The Particle version of the Body object can also receive a masscenter point
96
+ and a reference frame, just not an inertia.
97
+ """
98
+
99
+ def __init__(self, name, masscenter=None, mass=None, frame=None,
100
+ central_inertia=None):
101
+
102
+ self.name = name
103
+ self._loads = []
104
+
105
+ if frame is None:
106
+ frame = ReferenceFrame(name + '_frame')
107
+
108
+ if masscenter is None:
109
+ masscenter = Point(name + '_masscenter')
110
+
111
+ if central_inertia is None and mass is None:
112
+ ixx = Symbol(name + '_ixx')
113
+ iyy = Symbol(name + '_iyy')
114
+ izz = Symbol(name + '_izz')
115
+ izx = Symbol(name + '_izx')
116
+ ixy = Symbol(name + '_ixy')
117
+ iyz = Symbol(name + '_iyz')
118
+ _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx),
119
+ masscenter)
120
+ else:
121
+ _inertia = (central_inertia, masscenter)
122
+
123
+ if mass is None:
124
+ _mass = Symbol(name + '_mass')
125
+ else:
126
+ _mass = mass
127
+
128
+ masscenter.set_vel(frame, 0)
129
+
130
+ # If user passes masscenter and mass then a particle is created
131
+ # otherwise a rigidbody. As a result a body may or may not have inertia.
132
+ if central_inertia is None and mass is not None:
133
+ self.frame = frame
134
+ self.masscenter = masscenter
135
+ Particle.__init__(self, name, masscenter, _mass)
136
+ self._central_inertia = Dyadic(0)
137
+ else:
138
+ RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia)
139
+
140
+ @property
141
+ def loads(self):
142
+ return self._loads
143
+
144
+ @property
145
+ def x(self):
146
+ """The basis Vector for the Body, in the x direction."""
147
+ return self.frame.x
148
+
149
+ @property
150
+ def y(self):
151
+ """The basis Vector for the Body, in the y direction."""
152
+ return self.frame.y
153
+
154
+ @property
155
+ def z(self):
156
+ """The basis Vector for the Body, in the z direction."""
157
+ return self.frame.z
158
+
159
+ @property
160
+ def inertia(self):
161
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
162
+ if self.is_rigidbody:
163
+ return RigidBody.inertia.fget(self)
164
+ return (self.central_inertia, self.masscenter)
165
+
166
+ @inertia.setter
167
+ def inertia(self, I):
168
+ RigidBody.inertia.fset(self, I)
169
+
170
+ @property
171
+ def is_rigidbody(self):
172
+ if hasattr(self, '_inertia'):
173
+ return True
174
+ return False
175
+
176
+ def kinetic_energy(self, frame):
177
+ """Kinetic energy of the body.
178
+
179
+ Parameters
180
+ ==========
181
+
182
+ frame : ReferenceFrame or Body
183
+ The Body's angular velocity and the velocity of it's mass
184
+ center are typically defined with respect to an inertial frame but
185
+ any relevant frame in which the velocities are known can be supplied.
186
+
187
+ Examples
188
+ ========
189
+
190
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point
191
+ >>> from sympy import symbols
192
+ >>> m, v, r, omega = symbols('m v r omega')
193
+ >>> N = ReferenceFrame('N')
194
+ >>> O = Point('O')
195
+ >>> P = Body('P', masscenter=O, mass=m)
196
+ >>> P.masscenter.set_vel(N, v * N.y)
197
+ >>> P.kinetic_energy(N)
198
+ m*v**2/2
199
+
200
+ >>> N = ReferenceFrame('N')
201
+ >>> b = ReferenceFrame('b')
202
+ >>> b.set_ang_vel(N, omega * b.x)
203
+ >>> P = Point('P')
204
+ >>> P.set_vel(N, v * N.x)
205
+ >>> B = Body('B', masscenter=P, frame=b)
206
+ >>> B.kinetic_energy(N)
207
+ B_ixx*omega**2/2 + B_mass*v**2/2
208
+
209
+ See Also
210
+ ========
211
+
212
+ sympy.physics.mechanics : Particle, RigidBody
213
+
214
+ """
215
+ if isinstance(frame, Body):
216
+ frame = Body.frame
217
+ if self.is_rigidbody:
218
+ return RigidBody(self.name, self.masscenter, self.frame, self.mass,
219
+ (self.central_inertia, self.masscenter)).kinetic_energy(frame)
220
+ return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame)
221
+
222
+ def apply_force(self, force, point=None, reaction_body=None, reaction_point=None):
223
+ """Add force to the body(s).
224
+
225
+ Explanation
226
+ ===========
227
+
228
+ Applies the force on self or equal and oppposite forces on
229
+ self and other body if both are given on the desried point on the bodies.
230
+ The force applied on other body is taken opposite of self, i.e, -force.
231
+
232
+ Parameters
233
+ ==========
234
+
235
+ force: Vector
236
+ The force to be applied.
237
+ point: Point, optional
238
+ The point on self on which force is applied.
239
+ By default self's masscenter.
240
+ reaction_body: Body, optional
241
+ Second body on which equal and opposite force
242
+ is to be applied.
243
+ reaction_point : Point, optional
244
+ The point on other body on which equal and opposite
245
+ force is applied. By default masscenter of other body.
246
+
247
+ Example
248
+ =======
249
+
250
+ >>> from sympy import symbols
251
+ >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols
252
+ >>> m, g = symbols('m g')
253
+ >>> B = Body('B')
254
+ >>> force1 = m*g*B.z
255
+ >>> B.apply_force(force1) #Applying force on B's masscenter
256
+ >>> B.loads
257
+ [(B_masscenter, g*m*B_frame.z)]
258
+
259
+ We can also remove some part of force from any point on the body by
260
+ adding the opposite force to the body on that point.
261
+
262
+ >>> f1, f2 = dynamicsymbols('f1 f2')
263
+ >>> P = Point('P') #Considering point P on body B
264
+ >>> B.apply_force(f1*B.x + f2*B.y, P)
265
+ >>> B.loads
266
+ [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)]
267
+
268
+ Let's remove f1 from point P on body B.
269
+
270
+ >>> B.apply_force(-f1*B.x, P)
271
+ >>> B.loads
272
+ [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)]
273
+
274
+ To further demonstrate the use of ``apply_force`` attribute,
275
+ consider two bodies connected through a spring.
276
+
277
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
278
+ >>> N = Body('N') #Newtonion Frame
279
+ >>> x = dynamicsymbols('x')
280
+ >>> B1 = Body('B1')
281
+ >>> B2 = Body('B2')
282
+ >>> spring_force = x*N.x
283
+
284
+ Now let's apply equal and opposite spring force to the bodies.
285
+
286
+ >>> P1 = Point('P1')
287
+ >>> P2 = Point('P2')
288
+ >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2)
289
+
290
+ We can check the loads(forces) applied to bodies now.
291
+
292
+ >>> B1.loads
293
+ [(P1, x(t)*N_frame.x)]
294
+ >>> B2.loads
295
+ [(P2, - x(t)*N_frame.x)]
296
+
297
+ Notes
298
+ =====
299
+
300
+ If a new force is applied to a body on a point which already has some
301
+ force applied on it, then the new force is added to the already applied
302
+ force on that point.
303
+
304
+ """
305
+
306
+ if not isinstance(point, Point):
307
+ if point is None:
308
+ point = self.masscenter # masscenter
309
+ else:
310
+ raise TypeError("Force must be applied to a point on the body.")
311
+ if not isinstance(force, Vector):
312
+ raise TypeError("Force must be a vector.")
313
+
314
+ if reaction_body is not None:
315
+ reaction_body.apply_force(-force, point=reaction_point)
316
+
317
+ for load in self._loads:
318
+ if point in load:
319
+ force += load[1]
320
+ self._loads.remove(load)
321
+ break
322
+
323
+ self._loads.append((point, force))
324
+
325
+ def apply_torque(self, torque, reaction_body=None):
326
+ """Add torque to the body(s).
327
+
328
+ Explanation
329
+ ===========
330
+
331
+ Applies the torque on self or equal and oppposite torquess on
332
+ self and other body if both are given.
333
+ The torque applied on other body is taken opposite of self,
334
+ i.e, -torque.
335
+
336
+ Parameters
337
+ ==========
338
+
339
+ torque: Vector
340
+ The torque to be applied.
341
+ reaction_body: Body, optional
342
+ Second body on which equal and opposite torque
343
+ is to be applied.
344
+
345
+ Example
346
+ =======
347
+
348
+ >>> from sympy import symbols
349
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
350
+ >>> t = symbols('t')
351
+ >>> B = Body('B')
352
+ >>> torque1 = t*B.z
353
+ >>> B.apply_torque(torque1)
354
+ >>> B.loads
355
+ [(B_frame, t*B_frame.z)]
356
+
357
+ We can also remove some part of torque from the body by
358
+ adding the opposite torque to the body.
359
+
360
+ >>> t1, t2 = dynamicsymbols('t1 t2')
361
+ >>> B.apply_torque(t1*B.x + t2*B.y)
362
+ >>> B.loads
363
+ [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)]
364
+
365
+ Let's remove t1 from Body B.
366
+
367
+ >>> B.apply_torque(-t1*B.x)
368
+ >>> B.loads
369
+ [(B_frame, t2(t)*B_frame.y + t*B_frame.z)]
370
+
371
+ To further demonstrate the use, let us consider two bodies such that
372
+ a torque `T` is acting on one body, and `-T` on the other.
373
+
374
+ >>> from sympy.physics.mechanics import Body, dynamicsymbols
375
+ >>> N = Body('N') #Newtonion frame
376
+ >>> B1 = Body('B1')
377
+ >>> B2 = Body('B2')
378
+ >>> v = dynamicsymbols('v')
379
+ >>> T = v*N.y #Torque
380
+
381
+ Now let's apply equal and opposite torque to the bodies.
382
+
383
+ >>> B1.apply_torque(T, B2)
384
+
385
+ We can check the loads (torques) applied to bodies now.
386
+
387
+ >>> B1.loads
388
+ [(B1_frame, v(t)*N_frame.y)]
389
+ >>> B2.loads
390
+ [(B2_frame, - v(t)*N_frame.y)]
391
+
392
+ Notes
393
+ =====
394
+
395
+ If a new torque is applied on body which already has some torque applied on it,
396
+ then the new torque is added to the previous torque about the body's frame.
397
+
398
+ """
399
+
400
+ if not isinstance(torque, Vector):
401
+ raise TypeError("A Vector must be supplied to add torque.")
402
+
403
+ if reaction_body is not None:
404
+ reaction_body.apply_torque(-torque)
405
+
406
+ for load in self._loads:
407
+ if self.frame in load:
408
+ torque += load[1]
409
+ self._loads.remove(load)
410
+ break
411
+ self._loads.append((self.frame, torque))
412
+
413
+ def clear_loads(self):
414
+ """
415
+ Clears the Body's loads list.
416
+
417
+ Example
418
+ =======
419
+
420
+ >>> from sympy.physics.mechanics import Body
421
+ >>> B = Body('B')
422
+ >>> force = B.x + B.y
423
+ >>> B.apply_force(force)
424
+ >>> B.loads
425
+ [(B_masscenter, B_frame.x + B_frame.y)]
426
+ >>> B.clear_loads()
427
+ >>> B.loads
428
+ []
429
+
430
+ """
431
+
432
+ self._loads = []
433
+
434
+ def remove_load(self, about=None):
435
+ """
436
+ Remove load about a point or frame.
437
+
438
+ Parameters
439
+ ==========
440
+
441
+ about : Point or ReferenceFrame, optional
442
+ The point about which force is applied,
443
+ and is to be removed.
444
+ If about is None, then the torque about
445
+ self's frame is removed.
446
+
447
+ Example
448
+ =======
449
+
450
+ >>> from sympy.physics.mechanics import Body, Point
451
+ >>> B = Body('B')
452
+ >>> P = Point('P')
453
+ >>> f1 = B.x
454
+ >>> f2 = B.y
455
+ >>> B.apply_force(f1)
456
+ >>> B.apply_force(f2, P)
457
+ >>> B.loads
458
+ [(B_masscenter, B_frame.x), (P, B_frame.y)]
459
+
460
+ >>> B.remove_load(P)
461
+ >>> B.loads
462
+ [(B_masscenter, B_frame.x)]
463
+
464
+ """
465
+
466
+ if about is not None:
467
+ if not isinstance(about, Point):
468
+ raise TypeError('Load is applied about Point or ReferenceFrame.')
469
+ else:
470
+ about = self.frame
471
+
472
+ for load in self._loads:
473
+ if about in load:
474
+ self._loads.remove(load)
475
+ break
476
+
477
+ def masscenter_vel(self, body):
478
+ """
479
+ Returns the velocity of the mass center with respect to the provided
480
+ rigid body or reference frame.
481
+
482
+ Parameters
483
+ ==========
484
+
485
+ body: Body or ReferenceFrame
486
+ The rigid body or reference frame to calculate the velocity in.
487
+
488
+ Example
489
+ =======
490
+
491
+ >>> from sympy.physics.mechanics import Body
492
+ >>> A = Body('A')
493
+ >>> B = Body('B')
494
+ >>> A.masscenter.set_vel(B.frame, 5*B.frame.x)
495
+ >>> A.masscenter_vel(B)
496
+ 5*B_frame.x
497
+ >>> A.masscenter_vel(B.frame)
498
+ 5*B_frame.x
499
+
500
+ """
501
+
502
+ if isinstance(body, ReferenceFrame):
503
+ frame=body
504
+ elif isinstance(body, Body):
505
+ frame = body.frame
506
+ return self.masscenter.vel(frame)
507
+
508
+ def ang_vel_in(self, body):
509
+ """
510
+ Returns this body's angular velocity with respect to the provided
511
+ rigid body or reference frame.
512
+
513
+ Parameters
514
+ ==========
515
+
516
+ body: Body or ReferenceFrame
517
+ The rigid body or reference frame to calculate the angular velocity in.
518
+
519
+ Example
520
+ =======
521
+
522
+ >>> from sympy.physics.mechanics import Body, ReferenceFrame
523
+ >>> A = Body('A')
524
+ >>> N = ReferenceFrame('N')
525
+ >>> B = Body('B', frame=N)
526
+ >>> A.frame.set_ang_vel(N, 5*N.x)
527
+ >>> A.ang_vel_in(B)
528
+ 5*N.x
529
+ >>> A.ang_vel_in(N)
530
+ 5*N.x
531
+
532
+ """
533
+
534
+ if isinstance(body, ReferenceFrame):
535
+ frame=body
536
+ elif isinstance(body, Body):
537
+ frame = body.frame
538
+ return self.frame.ang_vel_in(frame)
539
+
540
+ def dcm(self, body):
541
+ """
542
+ Returns the direction cosine matrix of this body relative to the
543
+ provided rigid body or reference frame.
544
+
545
+ Parameters
546
+ ==========
547
+
548
+ body: Body or ReferenceFrame
549
+ The rigid body or reference frame to calculate the dcm.
550
+
551
+ Example
552
+ =======
553
+
554
+ >>> from sympy.physics.mechanics import Body
555
+ >>> A = Body('A')
556
+ >>> B = Body('B')
557
+ >>> A.frame.orient_axis(B.frame, B.frame.x, 5)
558
+ >>> A.dcm(B)
559
+ Matrix([
560
+ [1, 0, 0],
561
+ [0, cos(5), sin(5)],
562
+ [0, -sin(5), cos(5)]])
563
+ >>> A.dcm(B.frame)
564
+ Matrix([
565
+ [1, 0, 0],
566
+ [0, cos(5), sin(5)],
567
+ [0, -sin(5), cos(5)]])
568
+
569
+ """
570
+
571
+ if isinstance(body, ReferenceFrame):
572
+ frame=body
573
+ elif isinstance(body, Body):
574
+ frame = body.frame
575
+ return self.frame.dcm(frame)
576
+
577
+ def parallel_axis(self, point, frame=None):
578
+ """Returns the inertia dyadic of the body with respect to another
579
+ point.
580
+
581
+ Parameters
582
+ ==========
583
+
584
+ point : sympy.physics.vector.Point
585
+ The point to express the inertia dyadic about.
586
+ frame : sympy.physics.vector.ReferenceFrame
587
+ The reference frame used to construct the dyadic.
588
+
589
+ Returns
590
+ =======
591
+
592
+ inertia : sympy.physics.vector.Dyadic
593
+ The inertia dyadic of the rigid body expressed about the provided
594
+ point.
595
+
596
+ Example
597
+ =======
598
+
599
+ >>> from sympy.physics.mechanics import Body
600
+ >>> A = Body('A')
601
+ >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y)
602
+ >>> A.parallel_axis(P).to_matrix(A.frame)
603
+ Matrix([
604
+ [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx],
605
+ [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz],
606
+ [ A_izx, A_iyz, A_izz + 34*A_mass]])
607
+
608
+ """
609
+ if self.is_rigidbody:
610
+ return RigidBody.parallel_axis(self, point, frame)
611
+ return Particle.parallel_axis(self, point, frame)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py ADDED
@@ -0,0 +1,779 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities import dict_merge
2
+ from sympy.utilities.iterables import iterable
3
+ from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame,
4
+ Point, dynamicsymbols)
5
+ from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex,
6
+ init_vprinting)
7
+ from sympy.physics.mechanics.particle import Particle
8
+ from sympy.physics.mechanics.rigidbody import RigidBody
9
+ from sympy.simplify.simplify import simplify
10
+ from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos,
11
+ tan, AppliedUndef, S)
12
+
13
+ __all__ = ['inertia',
14
+ 'inertia_of_point_mass',
15
+ 'linear_momentum',
16
+ 'angular_momentum',
17
+ 'kinetic_energy',
18
+ 'potential_energy',
19
+ 'Lagrangian',
20
+ 'mechanics_printing',
21
+ 'mprint',
22
+ 'msprint',
23
+ 'mpprint',
24
+ 'mlatex',
25
+ 'msubs',
26
+ 'find_dynamicsymbols']
27
+
28
+ # These are functions that we've moved and renamed during extracting the
29
+ # basic vector calculus code from the mechanics packages.
30
+
31
+ mprint = vprint
32
+ msprint = vsprint
33
+ mpprint = vpprint
34
+ mlatex = vlatex
35
+
36
+
37
+ def mechanics_printing(**kwargs):
38
+ """
39
+ Initializes time derivative printing for all SymPy objects in
40
+ mechanics module.
41
+ """
42
+
43
+ init_vprinting(**kwargs)
44
+
45
+ mechanics_printing.__doc__ = init_vprinting.__doc__
46
+
47
+
48
+ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
49
+ """Simple way to create inertia Dyadic object.
50
+
51
+ Explanation
52
+ ===========
53
+
54
+ If you do not know what a Dyadic is, just treat this like the inertia
55
+ tensor. Then, do the easy thing and define it in a body-fixed frame.
56
+
57
+ Parameters
58
+ ==========
59
+
60
+ frame : ReferenceFrame
61
+ The frame the inertia is defined in
62
+ ixx : Sympifyable
63
+ the xx element in the inertia dyadic
64
+ iyy : Sympifyable
65
+ the yy element in the inertia dyadic
66
+ izz : Sympifyable
67
+ the zz element in the inertia dyadic
68
+ ixy : Sympifyable
69
+ the xy element in the inertia dyadic
70
+ iyz : Sympifyable
71
+ the yz element in the inertia dyadic
72
+ izx : Sympifyable
73
+ the zx element in the inertia dyadic
74
+
75
+ Examples
76
+ ========
77
+
78
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia
79
+ >>> N = ReferenceFrame('N')
80
+ >>> inertia(N, 1, 2, 3)
81
+ (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
82
+
83
+ """
84
+
85
+ if not isinstance(frame, ReferenceFrame):
86
+ raise TypeError('Need to define the inertia in a frame')
87
+ ixx = sympify(ixx)
88
+ ixy = sympify(ixy)
89
+ iyy = sympify(iyy)
90
+ iyz = sympify(iyz)
91
+ izx = sympify(izx)
92
+ izz = sympify(izz)
93
+ ol = ixx * (frame.x | frame.x)
94
+ ol += ixy * (frame.x | frame.y)
95
+ ol += izx * (frame.x | frame.z)
96
+ ol += ixy * (frame.y | frame.x)
97
+ ol += iyy * (frame.y | frame.y)
98
+ ol += iyz * (frame.y | frame.z)
99
+ ol += izx * (frame.z | frame.x)
100
+ ol += iyz * (frame.z | frame.y)
101
+ ol += izz * (frame.z | frame.z)
102
+ return ol
103
+
104
+
105
+ def inertia_of_point_mass(mass, pos_vec, frame):
106
+ """Inertia dyadic of a point mass relative to point O.
107
+
108
+ Parameters
109
+ ==========
110
+
111
+ mass : Sympifyable
112
+ Mass of the point mass
113
+ pos_vec : Vector
114
+ Position from point O to point mass
115
+ frame : ReferenceFrame
116
+ Reference frame to express the dyadic in
117
+
118
+ Examples
119
+ ========
120
+
121
+ >>> from sympy import symbols
122
+ >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
123
+ >>> N = ReferenceFrame('N')
124
+ >>> r, m = symbols('r m')
125
+ >>> px = r * N.x
126
+ >>> inertia_of_point_mass(m, px, N)
127
+ m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
128
+
129
+ """
130
+
131
+ return mass * (((frame.x | frame.x) + (frame.y | frame.y) +
132
+ (frame.z | frame.z)) * (pos_vec & pos_vec) -
133
+ (pos_vec | pos_vec))
134
+
135
+
136
+ def linear_momentum(frame, *body):
137
+ """Linear momentum of the system.
138
+
139
+ Explanation
140
+ ===========
141
+
142
+ This function returns the linear momentum of a system of Particle's and/or
143
+ RigidBody's. The linear momentum of a system is equal to the vector sum of
144
+ the linear momentum of its constituents. Consider a system, S, comprised of
145
+ a rigid body, A, and a particle, P. The linear momentum of the system, L,
146
+ is equal to the vector sum of the linear momentum of the particle, L1, and
147
+ the linear momentum of the rigid body, L2, i.e.
148
+
149
+ L = L1 + L2
150
+
151
+ Parameters
152
+ ==========
153
+
154
+ frame : ReferenceFrame
155
+ The frame in which linear momentum is desired.
156
+ body1, body2, body3... : Particle and/or RigidBody
157
+ The body (or bodies) whose linear momentum is required.
158
+
159
+ Examples
160
+ ========
161
+
162
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
163
+ >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
164
+ >>> N = ReferenceFrame('N')
165
+ >>> P = Point('P')
166
+ >>> P.set_vel(N, 10 * N.x)
167
+ >>> Pa = Particle('Pa', P, 1)
168
+ >>> Ac = Point('Ac')
169
+ >>> Ac.set_vel(N, 25 * N.y)
170
+ >>> I = outer(N.x, N.x)
171
+ >>> A = RigidBody('A', Ac, N, 20, (I, Ac))
172
+ >>> linear_momentum(N, A, Pa)
173
+ 10*N.x + 500*N.y
174
+
175
+ """
176
+
177
+ if not isinstance(frame, ReferenceFrame):
178
+ raise TypeError('Please specify a valid ReferenceFrame')
179
+ else:
180
+ linear_momentum_sys = Vector(0)
181
+ for e in body:
182
+ if isinstance(e, (RigidBody, Particle)):
183
+ linear_momentum_sys += e.linear_momentum(frame)
184
+ else:
185
+ raise TypeError('*body must have only Particle or RigidBody')
186
+ return linear_momentum_sys
187
+
188
+
189
+ def angular_momentum(point, frame, *body):
190
+ """Angular momentum of a system.
191
+
192
+ Explanation
193
+ ===========
194
+
195
+ This function returns the angular momentum of a system of Particle's and/or
196
+ RigidBody's. The angular momentum of such a system is equal to the vector
197
+ sum of the angular momentum of its constituents. Consider a system, S,
198
+ comprised of a rigid body, A, and a particle, P. The angular momentum of
199
+ the system, H, is equal to the vector sum of the angular momentum of the
200
+ particle, H1, and the angular momentum of the rigid body, H2, i.e.
201
+
202
+ H = H1 + H2
203
+
204
+ Parameters
205
+ ==========
206
+
207
+ point : Point
208
+ The point about which angular momentum of the system is desired.
209
+ frame : ReferenceFrame
210
+ The frame in which angular momentum is desired.
211
+ body1, body2, body3... : Particle and/or RigidBody
212
+ The body (or bodies) whose angular momentum is required.
213
+
214
+ Examples
215
+ ========
216
+
217
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
218
+ >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
219
+ >>> N = ReferenceFrame('N')
220
+ >>> O = Point('O')
221
+ >>> O.set_vel(N, 0 * N.x)
222
+ >>> P = O.locatenew('P', 1 * N.x)
223
+ >>> P.set_vel(N, 10 * N.x)
224
+ >>> Pa = Particle('Pa', P, 1)
225
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
226
+ >>> Ac.set_vel(N, 5 * N.y)
227
+ >>> a = ReferenceFrame('a')
228
+ >>> a.set_ang_vel(N, 10 * N.z)
229
+ >>> I = outer(N.z, N.z)
230
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
231
+ >>> angular_momentum(O, N, Pa, A)
232
+ 10*N.z
233
+
234
+ """
235
+
236
+ if not isinstance(frame, ReferenceFrame):
237
+ raise TypeError('Please enter a valid ReferenceFrame')
238
+ if not isinstance(point, Point):
239
+ raise TypeError('Please specify a valid Point')
240
+ else:
241
+ angular_momentum_sys = Vector(0)
242
+ for e in body:
243
+ if isinstance(e, (RigidBody, Particle)):
244
+ angular_momentum_sys += e.angular_momentum(point, frame)
245
+ else:
246
+ raise TypeError('*body must have only Particle or RigidBody')
247
+ return angular_momentum_sys
248
+
249
+
250
+ def kinetic_energy(frame, *body):
251
+ """Kinetic energy of a multibody system.
252
+
253
+ Explanation
254
+ ===========
255
+
256
+ This function returns the kinetic energy of a system of Particle's and/or
257
+ RigidBody's. The kinetic energy of such a system is equal to the sum of
258
+ the kinetic energies of its constituents. Consider a system, S, comprising
259
+ a rigid body, A, and a particle, P. The kinetic energy of the system, T,
260
+ is equal to the vector sum of the kinetic energy of the particle, T1, and
261
+ the kinetic energy of the rigid body, T2, i.e.
262
+
263
+ T = T1 + T2
264
+
265
+ Kinetic energy is a scalar.
266
+
267
+ Parameters
268
+ ==========
269
+
270
+ frame : ReferenceFrame
271
+ The frame in which the velocity or angular velocity of the body is
272
+ defined.
273
+ body1, body2, body3... : Particle and/or RigidBody
274
+ The body (or bodies) whose kinetic energy is required.
275
+
276
+ Examples
277
+ ========
278
+
279
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
280
+ >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
281
+ >>> N = ReferenceFrame('N')
282
+ >>> O = Point('O')
283
+ >>> O.set_vel(N, 0 * N.x)
284
+ >>> P = O.locatenew('P', 1 * N.x)
285
+ >>> P.set_vel(N, 10 * N.x)
286
+ >>> Pa = Particle('Pa', P, 1)
287
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
288
+ >>> Ac.set_vel(N, 5 * N.y)
289
+ >>> a = ReferenceFrame('a')
290
+ >>> a.set_ang_vel(N, 10 * N.z)
291
+ >>> I = outer(N.z, N.z)
292
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
293
+ >>> kinetic_energy(N, Pa, A)
294
+ 350
295
+
296
+ """
297
+
298
+ if not isinstance(frame, ReferenceFrame):
299
+ raise TypeError('Please enter a valid ReferenceFrame')
300
+ ke_sys = S.Zero
301
+ for e in body:
302
+ if isinstance(e, (RigidBody, Particle)):
303
+ ke_sys += e.kinetic_energy(frame)
304
+ else:
305
+ raise TypeError('*body must have only Particle or RigidBody')
306
+ return ke_sys
307
+
308
+
309
+ def potential_energy(*body):
310
+ """Potential energy of a multibody system.
311
+
312
+ Explanation
313
+ ===========
314
+
315
+ This function returns the potential energy of a system of Particle's and/or
316
+ RigidBody's. The potential energy of such a system is equal to the sum of
317
+ the potential energy of its constituents. Consider a system, S, comprising
318
+ a rigid body, A, and a particle, P. The potential energy of the system, V,
319
+ is equal to the vector sum of the potential energy of the particle, V1, and
320
+ the potential energy of the rigid body, V2, i.e.
321
+
322
+ V = V1 + V2
323
+
324
+ Potential energy is a scalar.
325
+
326
+ Parameters
327
+ ==========
328
+
329
+ body1, body2, body3... : Particle and/or RigidBody
330
+ The body (or bodies) whose potential energy is required.
331
+
332
+ Examples
333
+ ========
334
+
335
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
336
+ >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
337
+ >>> from sympy import symbols
338
+ >>> M, m, g, h = symbols('M m g h')
339
+ >>> N = ReferenceFrame('N')
340
+ >>> O = Point('O')
341
+ >>> O.set_vel(N, 0 * N.x)
342
+ >>> P = O.locatenew('P', 1 * N.x)
343
+ >>> Pa = Particle('Pa', P, m)
344
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
345
+ >>> a = ReferenceFrame('a')
346
+ >>> I = outer(N.z, N.z)
347
+ >>> A = RigidBody('A', Ac, a, M, (I, Ac))
348
+ >>> Pa.potential_energy = m * g * h
349
+ >>> A.potential_energy = M * g * h
350
+ >>> potential_energy(Pa, A)
351
+ M*g*h + g*h*m
352
+
353
+ """
354
+
355
+ pe_sys = S.Zero
356
+ for e in body:
357
+ if isinstance(e, (RigidBody, Particle)):
358
+ pe_sys += e.potential_energy
359
+ else:
360
+ raise TypeError('*body must have only Particle or RigidBody')
361
+ return pe_sys
362
+
363
+
364
+ def gravity(acceleration, *bodies):
365
+ """
366
+ Returns a list of gravity forces given the acceleration
367
+ due to gravity and any number of particles or rigidbodies.
368
+
369
+ Example
370
+ =======
371
+
372
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody
373
+ >>> from sympy.physics.mechanics.functions import gravity
374
+ >>> from sympy import symbols
375
+ >>> N = ReferenceFrame('N')
376
+ >>> m, M, g = symbols('m M g')
377
+ >>> F1, F2 = symbols('F1 F2')
378
+ >>> po = Point('po')
379
+ >>> pa = Particle('pa', po, m)
380
+ >>> A = ReferenceFrame('A')
381
+ >>> P = Point('P')
382
+ >>> I = outer(A.x, A.x)
383
+ >>> B = RigidBody('B', P, A, M, (I, P))
384
+ >>> forceList = [(po, F1), (P, F2)]
385
+ >>> forceList.extend(gravity(g*N.y, pa, B))
386
+ >>> forceList
387
+ [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)]
388
+
389
+ """
390
+
391
+ gravity_force = []
392
+ if not bodies:
393
+ raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
394
+
395
+ for e in bodies:
396
+ point = getattr(e, 'masscenter', None)
397
+ if point is None:
398
+ point = e.point
399
+
400
+ gravity_force.append((point, e.mass*acceleration))
401
+
402
+ return gravity_force
403
+
404
+
405
+ def center_of_mass(point, *bodies):
406
+ """
407
+ Returns the position vector from the given point to the center of mass
408
+ of the given bodies(particles or rigidbodies).
409
+
410
+ Example
411
+ =======
412
+
413
+ >>> from sympy import symbols, S
414
+ >>> from sympy.physics.vector import Point
415
+ >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
416
+ >>> from sympy.physics.mechanics.functions import center_of_mass
417
+ >>> a = ReferenceFrame('a')
418
+ >>> m = symbols('m', real=True)
419
+ >>> p1 = Particle('p1', Point('p1_pt'), S(1))
420
+ >>> p2 = Particle('p2', Point('p2_pt'), S(2))
421
+ >>> p3 = Particle('p3', Point('p3_pt'), S(3))
422
+ >>> p4 = Particle('p4', Point('p4_pt'), m)
423
+ >>> b_f = ReferenceFrame('b_f')
424
+ >>> b_cm = Point('b_cm')
425
+ >>> mb = symbols('mb')
426
+ >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
427
+ >>> p2.point.set_pos(p1.point, a.x)
428
+ >>> p3.point.set_pos(p1.point, a.x + a.y)
429
+ >>> p4.point.set_pos(p1.point, a.y)
430
+ >>> b.masscenter.set_pos(p1.point, a.y + a.z)
431
+ >>> point_o=Point('o')
432
+ >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
433
+ >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
434
+ >>> point_o.pos_from(p1.point)
435
+ 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
436
+
437
+ """
438
+ if not bodies:
439
+ raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
440
+
441
+ total_mass = 0
442
+ vec = Vector(0)
443
+ for i in bodies:
444
+ total_mass += i.mass
445
+
446
+ masscenter = getattr(i, 'masscenter', None)
447
+ if masscenter is None:
448
+ masscenter = i.point
449
+ vec += i.mass*masscenter.pos_from(point)
450
+
451
+ return vec/total_mass
452
+
453
+
454
+ def Lagrangian(frame, *body):
455
+ """Lagrangian of a multibody system.
456
+
457
+ Explanation
458
+ ===========
459
+
460
+ This function returns the Lagrangian of a system of Particle's and/or
461
+ RigidBody's. The Lagrangian of such a system is equal to the difference
462
+ between the kinetic energies and potential energies of its constituents. If
463
+ T and V are the kinetic and potential energies of a system then it's
464
+ Lagrangian, L, is defined as
465
+
466
+ L = T - V
467
+
468
+ The Lagrangian is a scalar.
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ frame : ReferenceFrame
474
+ The frame in which the velocity or angular velocity of the body is
475
+ defined to determine the kinetic energy.
476
+
477
+ body1, body2, body3... : Particle and/or RigidBody
478
+ The body (or bodies) whose Lagrangian is required.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
484
+ >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
485
+ >>> from sympy import symbols
486
+ >>> M, m, g, h = symbols('M m g h')
487
+ >>> N = ReferenceFrame('N')
488
+ >>> O = Point('O')
489
+ >>> O.set_vel(N, 0 * N.x)
490
+ >>> P = O.locatenew('P', 1 * N.x)
491
+ >>> P.set_vel(N, 10 * N.x)
492
+ >>> Pa = Particle('Pa', P, 1)
493
+ >>> Ac = O.locatenew('Ac', 2 * N.y)
494
+ >>> Ac.set_vel(N, 5 * N.y)
495
+ >>> a = ReferenceFrame('a')
496
+ >>> a.set_ang_vel(N, 10 * N.z)
497
+ >>> I = outer(N.z, N.z)
498
+ >>> A = RigidBody('A', Ac, a, 20, (I, Ac))
499
+ >>> Pa.potential_energy = m * g * h
500
+ >>> A.potential_energy = M * g * h
501
+ >>> Lagrangian(N, Pa, A)
502
+ -M*g*h - g*h*m + 350
503
+
504
+ """
505
+
506
+ if not isinstance(frame, ReferenceFrame):
507
+ raise TypeError('Please supply a valid ReferenceFrame')
508
+ for e in body:
509
+ if not isinstance(e, (RigidBody, Particle)):
510
+ raise TypeError('*body must have only Particle or RigidBody')
511
+ return kinetic_energy(frame, *body) - potential_energy(*body)
512
+
513
+
514
+ def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
515
+ """Find all dynamicsymbols in expression.
516
+
517
+ Explanation
518
+ ===========
519
+
520
+ If the optional ``exclude`` kwarg is used, only dynamicsymbols
521
+ not in the iterable ``exclude`` are returned.
522
+ If we intend to apply this function on a vector, the optional
523
+ ``reference_frame`` is also used to inform about the corresponding frame
524
+ with respect to which the dynamic symbols of the given vector is to be
525
+ determined.
526
+
527
+ Parameters
528
+ ==========
529
+
530
+ expression : SymPy expression
531
+
532
+ exclude : iterable of dynamicsymbols, optional
533
+
534
+ reference_frame : ReferenceFrame, optional
535
+ The frame with respect to which the dynamic symbols of the
536
+ given vector is to be determined.
537
+
538
+ Examples
539
+ ========
540
+
541
+ >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
542
+ >>> from sympy.physics.mechanics import ReferenceFrame
543
+ >>> x, y = dynamicsymbols('x, y')
544
+ >>> expr = x + x.diff()*y
545
+ >>> find_dynamicsymbols(expr)
546
+ {x(t), y(t), Derivative(x(t), t)}
547
+ >>> find_dynamicsymbols(expr, exclude=[x, y])
548
+ {Derivative(x(t), t)}
549
+ >>> a, b, c = dynamicsymbols('a, b, c')
550
+ >>> A = ReferenceFrame('A')
551
+ >>> v = a * A.x + b * A.y + c * A.z
552
+ >>> find_dynamicsymbols(v, reference_frame=A)
553
+ {a(t), b(t), c(t)}
554
+
555
+ """
556
+ t_set = {dynamicsymbols._t}
557
+ if exclude:
558
+ if iterable(exclude):
559
+ exclude_set = set(exclude)
560
+ else:
561
+ raise TypeError("exclude kwarg must be iterable")
562
+ else:
563
+ exclude_set = set()
564
+ if isinstance(expression, Vector):
565
+ if reference_frame is None:
566
+ raise ValueError("You must provide reference_frame when passing a "
567
+ "vector expression, got %s." % reference_frame)
568
+ else:
569
+ expression = expression.to_matrix(reference_frame)
570
+ return {i for i in expression.atoms(AppliedUndef, Derivative) if
571
+ i.free_symbols == t_set} - exclude_set
572
+
573
+
574
+ def msubs(expr, *sub_dicts, smart=False, **kwargs):
575
+ """A custom subs for use on expressions derived in physics.mechanics.
576
+
577
+ Traverses the expression tree once, performing the subs found in sub_dicts.
578
+ Terms inside ``Derivative`` expressions are ignored:
579
+
580
+ Examples
581
+ ========
582
+
583
+ >>> from sympy.physics.mechanics import dynamicsymbols, msubs
584
+ >>> x = dynamicsymbols('x')
585
+ >>> msubs(x.diff() + x, {x: 1})
586
+ Derivative(x(t), t) + 1
587
+
588
+ Note that sub_dicts can be a single dictionary, or several dictionaries:
589
+
590
+ >>> x, y, z = dynamicsymbols('x, y, z')
591
+ >>> sub1 = {x: 1, y: 2}
592
+ >>> sub2 = {z: 3, x.diff(): 4}
593
+ >>> msubs(x.diff() + x + y + z, sub1, sub2)
594
+ 10
595
+
596
+ If smart=True (default False), also checks for conditions that may result
597
+ in ``nan``, but if simplified would yield a valid expression. For example:
598
+
599
+ >>> from sympy import sin, tan
600
+ >>> (sin(x)/tan(x)).subs(x, 0)
601
+ nan
602
+ >>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
603
+ 1
604
+
605
+ It does this by first replacing all ``tan`` with ``sin/cos``. Then each
606
+ node is traversed. If the node is a fraction, subs is first evaluated on
607
+ the denominator. If this results in 0, simplification of the entire
608
+ fraction is attempted. Using this selective simplification, only
609
+ subexpressions that result in 1/0 are targeted, resulting in faster
610
+ performance.
611
+
612
+ """
613
+
614
+ sub_dict = dict_merge(*sub_dicts)
615
+ if smart:
616
+ func = _smart_subs
617
+ elif hasattr(expr, 'msubs'):
618
+ return expr.msubs(sub_dict)
619
+ else:
620
+ func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
621
+ if isinstance(expr, (Matrix, Vector, Dyadic)):
622
+ return expr.applyfunc(lambda x: func(x, sub_dict))
623
+ else:
624
+ return func(expr, sub_dict)
625
+
626
+
627
+ def _crawl(expr, func, *args, **kwargs):
628
+ """Crawl the expression tree, and apply func to every node."""
629
+ val = func(expr, *args, **kwargs)
630
+ if val is not None:
631
+ return val
632
+ new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
633
+ return expr.func(*new_args)
634
+
635
+
636
+ def _sub_func(expr, sub_dict):
637
+ """Perform direct matching substitution, ignoring derivatives."""
638
+ if expr in sub_dict:
639
+ return sub_dict[expr]
640
+ elif not expr.args or expr.is_Derivative:
641
+ return expr
642
+
643
+
644
+ def _tan_repl_func(expr):
645
+ """Replace tan with sin/cos."""
646
+ if isinstance(expr, tan):
647
+ return sin(*expr.args) / cos(*expr.args)
648
+ elif not expr.args or expr.is_Derivative:
649
+ return expr
650
+
651
+
652
+ def _smart_subs(expr, sub_dict):
653
+ """Performs subs, checking for conditions that may result in `nan` or
654
+ `oo`, and attempts to simplify them out.
655
+
656
+ The expression tree is traversed twice, and the following steps are
657
+ performed on each expression node:
658
+ - First traverse:
659
+ Replace all `tan` with `sin/cos`.
660
+ - Second traverse:
661
+ If node is a fraction, check if the denominator evaluates to 0.
662
+ If so, attempt to simplify it out. Then if node is in sub_dict,
663
+ sub in the corresponding value.
664
+
665
+ """
666
+ expr = _crawl(expr, _tan_repl_func)
667
+
668
+ def _recurser(expr, sub_dict):
669
+ # Decompose the expression into num, den
670
+ num, den = _fraction_decomp(expr)
671
+ if den != 1:
672
+ # If there is a non trivial denominator, we need to handle it
673
+ denom_subbed = _recurser(den, sub_dict)
674
+ if denom_subbed.evalf() == 0:
675
+ # If denom is 0 after this, attempt to simplify the bad expr
676
+ expr = simplify(expr)
677
+ else:
678
+ # Expression won't result in nan, find numerator
679
+ num_subbed = _recurser(num, sub_dict)
680
+ return num_subbed / denom_subbed
681
+ # We have to crawl the tree manually, because `expr` may have been
682
+ # modified in the simplify step. First, perform subs as normal:
683
+ val = _sub_func(expr, sub_dict)
684
+ if val is not None:
685
+ return val
686
+ new_args = (_recurser(arg, sub_dict) for arg in expr.args)
687
+ return expr.func(*new_args)
688
+ return _recurser(expr, sub_dict)
689
+
690
+
691
+ def _fraction_decomp(expr):
692
+ """Return num, den such that expr = num/den."""
693
+ if not isinstance(expr, Mul):
694
+ return expr, 1
695
+ num = []
696
+ den = []
697
+ for a in expr.args:
698
+ if a.is_Pow and a.args[1] < 0:
699
+ den.append(1 / a)
700
+ else:
701
+ num.append(a)
702
+ if not den:
703
+ return expr, 1
704
+ num = Mul(*num)
705
+ den = Mul(*den)
706
+ return num, den
707
+
708
+
709
+ def _f_list_parser(fl, ref_frame):
710
+ """Parses the provided forcelist composed of items
711
+ of the form (obj, force).
712
+ Returns a tuple containing:
713
+ vel_list: The velocity (ang_vel for Frames, vel for Points) in
714
+ the provided reference frame.
715
+ f_list: The forces.
716
+
717
+ Used internally in the KanesMethod and LagrangesMethod classes.
718
+
719
+ """
720
+ def flist_iter():
721
+ for pair in fl:
722
+ obj, force = pair
723
+ if isinstance(obj, ReferenceFrame):
724
+ yield obj.ang_vel_in(ref_frame), force
725
+ elif isinstance(obj, Point):
726
+ yield obj.vel(ref_frame), force
727
+ else:
728
+ raise TypeError('First entry in each forcelist pair must '
729
+ 'be a point or frame.')
730
+
731
+ if not fl:
732
+ vel_list, f_list = (), ()
733
+ else:
734
+ unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
735
+ vel_list, f_list = unzip(list(flist_iter()))
736
+ return vel_list, f_list
737
+
738
+
739
+ def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True,
740
+ is_dynamicsymbols=True):
741
+ t_set = {dynamicsymbols._t}
742
+ # Convert input to iterables
743
+ if coordinates is None:
744
+ coordinates = []
745
+ elif not iterable(coordinates):
746
+ coordinates = [coordinates]
747
+ if speeds is None:
748
+ speeds = []
749
+ elif not iterable(speeds):
750
+ speeds = [speeds]
751
+
752
+ if check_duplicates: # Check for duplicates
753
+ seen = set()
754
+ coord_duplicates = {x for x in coordinates if x in seen or seen.add(x)}
755
+ seen = set()
756
+ speed_duplicates = {x for x in speeds if x in seen or seen.add(x)}
757
+ overlap = set(coordinates).intersection(speeds)
758
+ if coord_duplicates:
759
+ raise ValueError(f'The generalized coordinates {coord_duplicates} '
760
+ f'are duplicated, all generalized coordinates '
761
+ f'should be unique.')
762
+ if speed_duplicates:
763
+ raise ValueError(f'The generalized speeds {speed_duplicates} are '
764
+ f'duplicated, all generalized speeds should be '
765
+ f'unique.')
766
+ if overlap:
767
+ raise ValueError(f'{overlap} are defined as both generalized '
768
+ f'coordinates and generalized speeds.')
769
+ if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols
770
+ for coordinate in coordinates:
771
+ if not (isinstance(coordinate, (AppliedUndef, Derivative)) and
772
+ coordinate.free_symbols == t_set):
773
+ raise ValueError(f'Generalized coordinate "{coordinate}" is not'
774
+ f' a dynamicsymbol.')
775
+ for speed in speeds:
776
+ if not (isinstance(speed, (AppliedUndef, Derivative)) and
777
+ speed.free_symbols == t_set):
778
+ raise ValueError(f'Generalized speed "{speed}" is not a '
779
+ f'dynamicsymbol.')
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py ADDED
@@ -0,0 +1,2163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ from sympy.core.backend import pi, AppliedUndef, Derivative, Matrix
6
+ from sympy.physics.mechanics.body import Body
7
+ from sympy.physics.mechanics.functions import _validate_coordinates
8
+ from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point,
9
+ ReferenceFrame)
10
+ from sympy.utilities.iterables import iterable
11
+ from sympy.utilities.exceptions import sympy_deprecation_warning
12
+
13
+ __all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint',
14
+ 'PlanarJoint', 'SphericalJoint', 'WeldJoint']
15
+
16
+
17
+ class Joint(ABC):
18
+ """Abstract base class for all specific joints.
19
+
20
+ Explanation
21
+ ===========
22
+
23
+ A joint subtracts degrees of freedom from a body. This is the base class
24
+ for all specific joints and holds all common methods acting as an interface
25
+ for all joints. Custom joint can be created by inheriting Joint class and
26
+ defining all abstract functions.
27
+
28
+ The abstract methods are:
29
+
30
+ - ``_generate_coordinates``
31
+ - ``_generate_speeds``
32
+ - ``_orient_frames``
33
+ - ``_set_angular_velocity``
34
+ - ``_set_linear_velocity``
35
+
36
+ Parameters
37
+ ==========
38
+
39
+ name : string
40
+ A unique name for the joint.
41
+ parent : Body
42
+ The parent body of joint.
43
+ child : Body
44
+ The child body of joint.
45
+ coordinates : iterable of dynamicsymbols, optional
46
+ Generalized coordinates of the joint.
47
+ speeds : iterable of dynamicsymbols, optional
48
+ Generalized speeds of joint.
49
+ parent_point : Point or Vector, optional
50
+ Attachment point where the joint is fixed to the parent body. If a
51
+ vector is provided, then the attachment point is computed by adding the
52
+ vector to the body's mass center. The default value is the parent's mass
53
+ center.
54
+ child_point : Point or Vector, optional
55
+ Attachment point where the joint is fixed to the child body. If a
56
+ vector is provided, then the attachment point is computed by adding the
57
+ vector to the body's mass center. The default value is the child's mass
58
+ center.
59
+ parent_axis : Vector, optional
60
+ .. deprecated:: 1.12
61
+ Axis fixed in the parent body which aligns with an axis fixed in the
62
+ child body. The default is the x axis of parent's reference frame.
63
+ For more information on this deprecation, see
64
+ :ref:`deprecated-mechanics-joint-axis`.
65
+ child_axis : Vector, optional
66
+ .. deprecated:: 1.12
67
+ Axis fixed in the child body which aligns with an axis fixed in the
68
+ parent body. The default is the x axis of child's reference frame.
69
+ For more information on this deprecation, see
70
+ :ref:`deprecated-mechanics-joint-axis`.
71
+ parent_interframe : ReferenceFrame, optional
72
+ Intermediate frame of the parent body with respect to which the joint
73
+ transformation is formulated. If a Vector is provided then an interframe
74
+ is created which aligns its X axis with the given vector. The default
75
+ value is the parent's own frame.
76
+ child_interframe : ReferenceFrame, optional
77
+ Intermediate frame of the child body with respect to which the joint
78
+ transformation is formulated. If a Vector is provided then an interframe
79
+ is created which aligns its X axis with the given vector. The default
80
+ value is the child's own frame.
81
+ parent_joint_pos : Point or Vector, optional
82
+ .. deprecated:: 1.12
83
+ This argument is replaced by parent_point and will be removed in a
84
+ future version.
85
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
86
+ child_joint_pos : Point or Vector, optional
87
+ .. deprecated:: 1.12
88
+ This argument is replaced by child_point and will be removed in a
89
+ future version.
90
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
91
+
92
+ Attributes
93
+ ==========
94
+
95
+ name : string
96
+ The joint's name.
97
+ parent : Body
98
+ The joint's parent body.
99
+ child : Body
100
+ The joint's child body.
101
+ coordinates : Matrix
102
+ Matrix of the joint's generalized coordinates.
103
+ speeds : Matrix
104
+ Matrix of the joint's generalized speeds.
105
+ parent_point : Point
106
+ Attachment point where the joint is fixed to the parent body.
107
+ child_point : Point
108
+ Attachment point where the joint is fixed to the child body.
109
+ parent_axis : Vector
110
+ The axis fixed in the parent frame that represents the joint.
111
+ child_axis : Vector
112
+ The axis fixed in the child frame that represents the joint.
113
+ parent_interframe : ReferenceFrame
114
+ Intermediate frame of the parent body with respect to which the joint
115
+ transformation is formulated.
116
+ child_interframe : ReferenceFrame
117
+ Intermediate frame of the child body with respect to which the joint
118
+ transformation is formulated.
119
+ kdes : Matrix
120
+ Kinematical differential equations of the joint.
121
+
122
+ Notes
123
+ =====
124
+
125
+ When providing a vector as the intermediate frame, a new intermediate frame
126
+ is created which aligns its X axis with the provided vector. This is done
127
+ with a single fixed rotation about a rotation axis. This rotation axis is
128
+ determined by taking the cross product of the ``body.x`` axis with the
129
+ provided vector. In the case where the provided vector is in the ``-body.x``
130
+ direction, the rotation is done about the ``body.y`` axis.
131
+
132
+ """
133
+
134
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
135
+ parent_point=None, child_point=None, parent_axis=None,
136
+ child_axis=None, parent_interframe=None, child_interframe=None,
137
+ parent_joint_pos=None, child_joint_pos=None):
138
+
139
+ if not isinstance(name, str):
140
+ raise TypeError('Supply a valid name.')
141
+ self._name = name
142
+
143
+ if not isinstance(parent, Body):
144
+ raise TypeError('Parent must be an instance of Body.')
145
+ self._parent = parent
146
+
147
+ if not isinstance(child, Body):
148
+ raise TypeError('Parent must be an instance of Body.')
149
+ self._child = child
150
+
151
+ self._coordinates = self._generate_coordinates(coordinates)
152
+ self._speeds = self._generate_speeds(speeds)
153
+ _validate_coordinates(self.coordinates, self.speeds)
154
+ self._kdes = self._generate_kdes()
155
+
156
+ self._parent_axis = self._axis(parent_axis, parent.frame)
157
+ self._child_axis = self._axis(child_axis, child.frame)
158
+
159
+ if parent_joint_pos is not None or child_joint_pos is not None:
160
+ sympy_deprecation_warning(
161
+ """
162
+ The parent_joint_pos and child_joint_pos arguments for the Joint
163
+ classes are deprecated. Instead use parent_point and child_point.
164
+ """,
165
+ deprecated_since_version="1.12",
166
+ active_deprecations_target="deprecated-mechanics-joint-pos",
167
+ stacklevel=4
168
+ )
169
+ if parent_point is None:
170
+ parent_point = parent_joint_pos
171
+ if child_point is None:
172
+ child_point = child_joint_pos
173
+ self._parent_point = self._locate_joint_pos(parent, parent_point)
174
+ self._child_point = self._locate_joint_pos(child, child_point)
175
+ if parent_axis is not None or child_axis is not None:
176
+ sympy_deprecation_warning(
177
+ """
178
+ The parent_axis and child_axis arguments for the Joint classes
179
+ are deprecated. Instead use parent_interframe, child_interframe.
180
+ """,
181
+ deprecated_since_version="1.12",
182
+ active_deprecations_target="deprecated-mechanics-joint-axis",
183
+ stacklevel=4
184
+ )
185
+ if parent_interframe is None:
186
+ parent_interframe = parent_axis
187
+ if child_interframe is None:
188
+ child_interframe = child_axis
189
+ self._parent_interframe = self._locate_joint_frame(parent,
190
+ parent_interframe)
191
+ self._child_interframe = self._locate_joint_frame(child,
192
+ child_interframe)
193
+
194
+ self._orient_frames()
195
+ self._set_angular_velocity()
196
+ self._set_linear_velocity()
197
+
198
+ def __str__(self):
199
+ return self.name
200
+
201
+ def __repr__(self):
202
+ return self.__str__()
203
+
204
+ @property
205
+ def name(self):
206
+ """Name of the joint."""
207
+ return self._name
208
+
209
+ @property
210
+ def parent(self):
211
+ """Parent body of Joint."""
212
+ return self._parent
213
+
214
+ @property
215
+ def child(self):
216
+ """Child body of Joint."""
217
+ return self._child
218
+
219
+ @property
220
+ def coordinates(self):
221
+ """Matrix of the joint's generalized coordinates."""
222
+ return self._coordinates
223
+
224
+ @property
225
+ def speeds(self):
226
+ """Matrix of the joint's generalized speeds."""
227
+ return self._speeds
228
+
229
+ @property
230
+ def kdes(self):
231
+ """Kinematical differential equations of the joint."""
232
+ return self._kdes
233
+
234
+ @property
235
+ def parent_axis(self):
236
+ """The axis of parent frame."""
237
+ # Will be removed with `deprecated-mechanics-joint-axis`
238
+ return self._parent_axis
239
+
240
+ @property
241
+ def child_axis(self):
242
+ """The axis of child frame."""
243
+ # Will be removed with `deprecated-mechanics-joint-axis`
244
+ return self._child_axis
245
+
246
+ @property
247
+ def parent_point(self):
248
+ """Attachment point where the joint is fixed to the parent body."""
249
+ return self._parent_point
250
+
251
+ @property
252
+ def child_point(self):
253
+ """Attachment point where the joint is fixed to the child body."""
254
+ return self._child_point
255
+
256
+ @property
257
+ def parent_interframe(self):
258
+ return self._parent_interframe
259
+
260
+ @property
261
+ def child_interframe(self):
262
+ return self._child_interframe
263
+
264
+ @abstractmethod
265
+ def _generate_coordinates(self, coordinates):
266
+ """Generate Matrix of the joint's generalized coordinates."""
267
+ pass
268
+
269
+ @abstractmethod
270
+ def _generate_speeds(self, speeds):
271
+ """Generate Matrix of the joint's generalized speeds."""
272
+ pass
273
+
274
+ @abstractmethod
275
+ def _orient_frames(self):
276
+ """Orient frames as per the joint."""
277
+ pass
278
+
279
+ @abstractmethod
280
+ def _set_angular_velocity(self):
281
+ """Set angular velocity of the joint related frames."""
282
+ pass
283
+
284
+ @abstractmethod
285
+ def _set_linear_velocity(self):
286
+ """Set velocity of related points to the joint."""
287
+ pass
288
+
289
+ @staticmethod
290
+ def _to_vector(matrix, frame):
291
+ """Converts a matrix to a vector in the given frame."""
292
+ return Vector([(matrix, frame)])
293
+
294
+ @staticmethod
295
+ def _axis(ax, *frames):
296
+ """Check whether an axis is fixed in one of the frames."""
297
+ if ax is None:
298
+ ax = frames[0].x
299
+ return ax
300
+ if not isinstance(ax, Vector):
301
+ raise TypeError("Axis must be a Vector.")
302
+ ref_frame = None # Find a body in which the axis can be expressed
303
+ for frame in frames:
304
+ try:
305
+ ax.to_matrix(frame)
306
+ except ValueError:
307
+ pass
308
+ else:
309
+ ref_frame = frame
310
+ break
311
+ if ref_frame is None:
312
+ raise ValueError("Axis cannot be expressed in one of the body's "
313
+ "frames.")
314
+ if not ax.dt(ref_frame) == 0:
315
+ raise ValueError('Axis cannot be time-varying when viewed from the '
316
+ 'associated body.')
317
+ return ax
318
+
319
+ @staticmethod
320
+ def _choose_rotation_axis(frame, axis):
321
+ components = axis.to_matrix(frame)
322
+ x, y, z = components[0], components[1], components[2]
323
+
324
+ if x != 0:
325
+ if y != 0:
326
+ if z != 0:
327
+ return cross(axis, frame.x)
328
+ if z != 0:
329
+ return frame.y
330
+ return frame.z
331
+ else:
332
+ if y != 0:
333
+ return frame.x
334
+ return frame.y
335
+
336
+ @staticmethod
337
+ def _create_aligned_interframe(frame, align_axis, frame_axis=None,
338
+ frame_name=None):
339
+ """
340
+ Returns an intermediate frame, where the ``frame_axis`` defined in
341
+ ``frame`` is aligned with ``axis``. By default this means that the X
342
+ axis will be aligned with ``axis``.
343
+
344
+ Parameters
345
+ ==========
346
+
347
+ frame : Body or ReferenceFrame
348
+ The body or reference frame with respect to which the intermediate
349
+ frame is oriented.
350
+ align_axis : Vector
351
+ The vector with respect to which the intermediate frame will be
352
+ aligned.
353
+ frame_axis : Vector
354
+ The vector of the frame which should get aligned with ``axis``. The
355
+ default is the X axis of the frame.
356
+ frame_name : string
357
+ Name of the to be created intermediate frame. The default adds
358
+ "_int_frame" to the name of ``frame``.
359
+
360
+ Example
361
+ =======
362
+
363
+ An intermediate frame, where the X axis of the parent becomes aligned
364
+ with ``parent.y + parent.z`` can be created as follows:
365
+
366
+ >>> from sympy.physics.mechanics.joint import Joint
367
+ >>> from sympy.physics.mechanics import Body
368
+ >>> parent = Body('parent')
369
+ >>> parent_interframe = Joint._create_aligned_interframe(
370
+ ... parent, parent.y + parent.z)
371
+ >>> parent_interframe
372
+ parent_int_frame
373
+ >>> parent.dcm(parent_interframe)
374
+ Matrix([
375
+ [ 0, -sqrt(2)/2, -sqrt(2)/2],
376
+ [sqrt(2)/2, 1/2, -1/2],
377
+ [sqrt(2)/2, -1/2, 1/2]])
378
+ >>> (parent.y + parent.z).express(parent_interframe)
379
+ sqrt(2)*parent_int_frame.x
380
+
381
+ Notes
382
+ =====
383
+
384
+ The direction cosine matrix between the given frame and intermediate
385
+ frame is formed using a simple rotation about an axis that is normal to
386
+ both ``align_axis`` and ``frame_axis``. In general, the normal axis is
387
+ formed by crossing the ``frame_axis`` with the ``align_axis``. The
388
+ exception is if the axes are parallel with opposite directions, in which
389
+ case the rotation vector is chosen using the rules in the following
390
+ table with the vectors expressed in the given frame:
391
+
392
+ .. list-table::
393
+ :header-rows: 1
394
+
395
+ * - ``align_axis``
396
+ - ``frame_axis``
397
+ - ``rotation_axis``
398
+ * - ``-x``
399
+ - ``x``
400
+ - ``z``
401
+ * - ``-y``
402
+ - ``y``
403
+ - ``x``
404
+ * - ``-z``
405
+ - ``z``
406
+ - ``y``
407
+ * - ``-x-y``
408
+ - ``x+y``
409
+ - ``z``
410
+ * - ``-y-z``
411
+ - ``y+z``
412
+ - ``x``
413
+ * - ``-x-z``
414
+ - ``x+z``
415
+ - ``y``
416
+ * - ``-x-y-z``
417
+ - ``x+y+z``
418
+ - ``(x+y+z) × x``
419
+
420
+ """
421
+ if isinstance(frame, Body):
422
+ frame = frame.frame
423
+ if frame_axis is None:
424
+ frame_axis = frame.x
425
+ if frame_name is None:
426
+ if frame.name[-6:] == '_frame':
427
+ frame_name = f'{frame.name[:-6]}_int_frame'
428
+ else:
429
+ frame_name = f'{frame.name}_int_frame'
430
+ angle = frame_axis.angle_between(align_axis)
431
+ rotation_axis = cross(frame_axis, align_axis)
432
+ if rotation_axis == Vector(0) and angle == 0:
433
+ return frame
434
+ if angle == pi:
435
+ rotation_axis = Joint._choose_rotation_axis(frame, align_axis)
436
+
437
+ int_frame = ReferenceFrame(frame_name)
438
+ int_frame.orient_axis(frame, rotation_axis, angle)
439
+ int_frame.set_ang_vel(frame, 0 * rotation_axis)
440
+ return int_frame
441
+
442
+ def _generate_kdes(self):
443
+ """Generate kinematical differential equations."""
444
+ kdes = []
445
+ t = dynamicsymbols._t
446
+ for i in range(len(self.coordinates)):
447
+ kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
448
+ return Matrix(kdes)
449
+
450
+ def _locate_joint_pos(self, body, joint_pos):
451
+ """Returns the attachment point of a body."""
452
+ if joint_pos is None:
453
+ return body.masscenter
454
+ if not isinstance(joint_pos, (Point, Vector)):
455
+ raise TypeError('Attachment point must be a Point or Vector.')
456
+ if isinstance(joint_pos, Vector):
457
+ point_name = f'{self.name}_{body.name}_joint'
458
+ joint_pos = body.masscenter.locatenew(point_name, joint_pos)
459
+ if not joint_pos.pos_from(body.masscenter).dt(body.frame) == 0:
460
+ raise ValueError('Attachment point must be fixed to the associated '
461
+ 'body.')
462
+ return joint_pos
463
+
464
+ def _locate_joint_frame(self, body, interframe):
465
+ """Returns the attachment frame of a body."""
466
+ if interframe is None:
467
+ return body.frame
468
+ if isinstance(interframe, Vector):
469
+ interframe = Joint._create_aligned_interframe(
470
+ body, interframe,
471
+ frame_name=f'{self.name}_{body.name}_int_frame')
472
+ elif not isinstance(interframe, ReferenceFrame):
473
+ raise TypeError('Interframe must be a ReferenceFrame.')
474
+ if not interframe.ang_vel_in(body.frame) == 0:
475
+ raise ValueError(f'Interframe {interframe} is not fixed to body '
476
+ f'{body}.')
477
+ body.masscenter.set_vel(interframe, 0) # Fixate interframe to body
478
+ return interframe
479
+
480
+ def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0,
481
+ number_single=False):
482
+ """Helper method for _generate_coordinates and _generate_speeds.
483
+
484
+ Parameters
485
+ ==========
486
+
487
+ coordinates : iterable
488
+ Iterable of coordinates or speeds that have been provided.
489
+ n_coords : Integer
490
+ Number of coordinates that should be returned.
491
+ label : String, optional
492
+ Coordinate type either 'q' (coordinates) or 'u' (speeds). The
493
+ Default is 'q'.
494
+ offset : Integer
495
+ Count offset when creating new dynamicsymbols. The default is 0.
496
+ number_single : Boolean
497
+ Boolean whether if n_coords == 1, number should still be used. The
498
+ default is False.
499
+
500
+ """
501
+
502
+ def create_symbol(number):
503
+ if n_coords == 1 and not number_single:
504
+ return dynamicsymbols(f'{label}_{self.name}')
505
+ return dynamicsymbols(f'{label}{number}_{self.name}')
506
+
507
+ name = 'generalized coordinate' if label == 'q' else 'generalized speed'
508
+ generated_coordinates = []
509
+ if coordinates is None:
510
+ coordinates = []
511
+ elif not iterable(coordinates):
512
+ coordinates = [coordinates]
513
+ if not (len(coordinates) == 0 or len(coordinates) == n_coords):
514
+ raise ValueError(f'Expected {n_coords} {name}s, instead got '
515
+ f'{len(coordinates)} {name}s.')
516
+ # Supports more iterables, also Matrix
517
+ for i, coord in enumerate(coordinates):
518
+ if coord is None:
519
+ generated_coordinates.append(create_symbol(i + offset))
520
+ elif isinstance(coord, (AppliedUndef, Derivative)):
521
+ generated_coordinates.append(coord)
522
+ else:
523
+ raise TypeError(f'The {name} {coord} should have been a '
524
+ f'dynamicsymbol.')
525
+ for i in range(len(coordinates) + offset, n_coords + offset):
526
+ generated_coordinates.append(create_symbol(i))
527
+ return Matrix(generated_coordinates)
528
+
529
+
530
+ class PinJoint(Joint):
531
+ """Pin (Revolute) Joint.
532
+
533
+ .. image:: PinJoint.svg
534
+
535
+ Explanation
536
+ ===========
537
+
538
+ A pin joint is defined such that the joint rotation axis is fixed in both
539
+ the child and parent and the location of the joint is relative to the mass
540
+ center of each body. The child rotates an angle, θ, from the parent about
541
+ the rotation axis and has a simple angular speed, ω, relative to the
542
+ parent. The direction cosine matrix between the child interframe and
543
+ parent interframe is formed using a simple rotation about the joint axis.
544
+ The page on the joints framework gives a more detailed explanation of the
545
+ intermediate frames.
546
+
547
+ Parameters
548
+ ==========
549
+
550
+ name : string
551
+ A unique name for the joint.
552
+ parent : Body
553
+ The parent body of joint.
554
+ child : Body
555
+ The child body of joint.
556
+ coordinates : dynamicsymbol, optional
557
+ Generalized coordinates of the joint.
558
+ speeds : dynamicsymbol, optional
559
+ Generalized speeds of joint.
560
+ parent_point : Point or Vector, optional
561
+ Attachment point where the joint is fixed to the parent body. If a
562
+ vector is provided, then the attachment point is computed by adding the
563
+ vector to the body's mass center. The default value is the parent's mass
564
+ center.
565
+ child_point : Point or Vector, optional
566
+ Attachment point where the joint is fixed to the child body. If a
567
+ vector is provided, then the attachment point is computed by adding the
568
+ vector to the body's mass center. The default value is the child's mass
569
+ center.
570
+ parent_axis : Vector, optional
571
+ .. deprecated:: 1.12
572
+ Axis fixed in the parent body which aligns with an axis fixed in the
573
+ child body. The default is the x axis of parent's reference frame.
574
+ For more information on this deprecation, see
575
+ :ref:`deprecated-mechanics-joint-axis`.
576
+ child_axis : Vector, optional
577
+ .. deprecated:: 1.12
578
+ Axis fixed in the child body which aligns with an axis fixed in the
579
+ parent body. The default is the x axis of child's reference frame.
580
+ For more information on this deprecation, see
581
+ :ref:`deprecated-mechanics-joint-axis`.
582
+ parent_interframe : ReferenceFrame, optional
583
+ Intermediate frame of the parent body with respect to which the joint
584
+ transformation is formulated. If a Vector is provided then an interframe
585
+ is created which aligns its X axis with the given vector. The default
586
+ value is the parent's own frame.
587
+ child_interframe : ReferenceFrame, optional
588
+ Intermediate frame of the child body with respect to which the joint
589
+ transformation is formulated. If a Vector is provided then an interframe
590
+ is created which aligns its X axis with the given vector. The default
591
+ value is the child's own frame.
592
+ joint_axis : Vector
593
+ The axis about which the rotation occurs. Note that the components
594
+ of this axis are the same in the parent_interframe and child_interframe.
595
+ parent_joint_pos : Point or Vector, optional
596
+ .. deprecated:: 1.12
597
+ This argument is replaced by parent_point and will be removed in a
598
+ future version.
599
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
600
+ child_joint_pos : Point or Vector, optional
601
+ .. deprecated:: 1.12
602
+ This argument is replaced by child_point and will be removed in a
603
+ future version.
604
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
605
+
606
+ Attributes
607
+ ==========
608
+
609
+ name : string
610
+ The joint's name.
611
+ parent : Body
612
+ The joint's parent body.
613
+ child : Body
614
+ The joint's child body.
615
+ coordinates : Matrix
616
+ Matrix of the joint's generalized coordinates. The default value is
617
+ ``dynamicsymbols(f'q_{joint.name}')``.
618
+ speeds : Matrix
619
+ Matrix of the joint's generalized speeds. The default value is
620
+ ``dynamicsymbols(f'u_{joint.name}')``.
621
+ parent_point : Point
622
+ Attachment point where the joint is fixed to the parent body.
623
+ child_point : Point
624
+ Attachment point where the joint is fixed to the child body.
625
+ parent_axis : Vector
626
+ The axis fixed in the parent frame that represents the joint.
627
+ child_axis : Vector
628
+ The axis fixed in the child frame that represents the joint.
629
+ parent_interframe : ReferenceFrame
630
+ Intermediate frame of the parent body with respect to which the joint
631
+ transformation is formulated.
632
+ child_interframe : ReferenceFrame
633
+ Intermediate frame of the child body with respect to which the joint
634
+ transformation is formulated.
635
+ joint_axis : Vector
636
+ The axis about which the rotation occurs. Note that the components of
637
+ this axis are the same in the parent_interframe and child_interframe.
638
+ kdes : Matrix
639
+ Kinematical differential equations of the joint.
640
+
641
+ Examples
642
+ =========
643
+
644
+ A single pin joint is created from two bodies and has the following basic
645
+ attributes:
646
+
647
+ >>> from sympy.physics.mechanics import Body, PinJoint
648
+ >>> parent = Body('P')
649
+ >>> parent
650
+ P
651
+ >>> child = Body('C')
652
+ >>> child
653
+ C
654
+ >>> joint = PinJoint('PC', parent, child)
655
+ >>> joint
656
+ PinJoint: PC parent: P child: C
657
+ >>> joint.name
658
+ 'PC'
659
+ >>> joint.parent
660
+ P
661
+ >>> joint.child
662
+ C
663
+ >>> joint.parent_point
664
+ P_masscenter
665
+ >>> joint.child_point
666
+ C_masscenter
667
+ >>> joint.parent_axis
668
+ P_frame.x
669
+ >>> joint.child_axis
670
+ C_frame.x
671
+ >>> joint.coordinates
672
+ Matrix([[q_PC(t)]])
673
+ >>> joint.speeds
674
+ Matrix([[u_PC(t)]])
675
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
676
+ u_PC(t)*P_frame.x
677
+ >>> joint.child.frame.dcm(joint.parent.frame)
678
+ Matrix([
679
+ [1, 0, 0],
680
+ [0, cos(q_PC(t)), sin(q_PC(t))],
681
+ [0, -sin(q_PC(t)), cos(q_PC(t))]])
682
+ >>> joint.child_point.pos_from(joint.parent_point)
683
+ 0
684
+
685
+ To further demonstrate the use of the pin joint, the kinematics of simple
686
+ double pendulum that rotates about the Z axis of each connected body can be
687
+ created as follows.
688
+
689
+ >>> from sympy import symbols, trigsimp
690
+ >>> from sympy.physics.mechanics import Body, PinJoint
691
+ >>> l1, l2 = symbols('l1 l2')
692
+
693
+ First create bodies to represent the fixed ceiling and one to represent
694
+ each pendulum bob.
695
+
696
+ >>> ceiling = Body('C')
697
+ >>> upper_bob = Body('U')
698
+ >>> lower_bob = Body('L')
699
+
700
+ The first joint will connect the upper bob to the ceiling by a distance of
701
+ ``l1`` and the joint axis will be about the Z axis for each body.
702
+
703
+ >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
704
+ ... child_point=-l1*upper_bob.frame.x,
705
+ ... joint_axis=ceiling.frame.z)
706
+
707
+ The second joint will connect the lower bob to the upper bob by a distance
708
+ of ``l2`` and the joint axis will also be about the Z axis for each body.
709
+
710
+ >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
711
+ ... child_point=-l2*lower_bob.frame.x,
712
+ ... joint_axis=upper_bob.frame.z)
713
+
714
+ Once the joints are established the kinematics of the connected bodies can
715
+ be accessed. First the direction cosine matrices of pendulum link relative
716
+ to the ceiling are found:
717
+
718
+ >>> upper_bob.frame.dcm(ceiling.frame)
719
+ Matrix([
720
+ [ cos(q_P1(t)), sin(q_P1(t)), 0],
721
+ [-sin(q_P1(t)), cos(q_P1(t)), 0],
722
+ [ 0, 0, 1]])
723
+ >>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
724
+ Matrix([
725
+ [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0],
726
+ [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0],
727
+ [ 0, 0, 1]])
728
+
729
+ The position of the lower bob's masscenter is found with:
730
+
731
+ >>> lower_bob.masscenter.pos_from(ceiling.masscenter)
732
+ l1*U_frame.x + l2*L_frame.x
733
+
734
+ The angular velocities of the two pendulum links can be computed with
735
+ respect to the ceiling.
736
+
737
+ >>> upper_bob.frame.ang_vel_in(ceiling.frame)
738
+ u_P1(t)*C_frame.z
739
+ >>> lower_bob.frame.ang_vel_in(ceiling.frame)
740
+ u_P1(t)*C_frame.z + u_P2(t)*U_frame.z
741
+
742
+ And finally, the linear velocities of the two pendulum bobs can be computed
743
+ with respect to the ceiling.
744
+
745
+ >>> upper_bob.masscenter.vel(ceiling.frame)
746
+ l1*u_P1(t)*U_frame.y
747
+ >>> lower_bob.masscenter.vel(ceiling.frame)
748
+ l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y
749
+
750
+ """
751
+
752
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
753
+ parent_point=None, child_point=None, parent_axis=None,
754
+ child_axis=None, parent_interframe=None, child_interframe=None,
755
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
756
+
757
+ self._joint_axis = joint_axis
758
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
759
+ child_point, parent_axis, child_axis,
760
+ parent_interframe, child_interframe, parent_joint_pos,
761
+ child_joint_pos)
762
+
763
+ def __str__(self):
764
+ return (f'PinJoint: {self.name} parent: {self.parent} '
765
+ f'child: {self.child}')
766
+
767
+ @property
768
+ def joint_axis(self):
769
+ """Axis about which the child rotates with respect to the parent."""
770
+ return self._joint_axis
771
+
772
+ def _generate_coordinates(self, coordinate):
773
+ return self._fill_coordinate_list(coordinate, 1, 'q')
774
+
775
+ def _generate_speeds(self, speed):
776
+ return self._fill_coordinate_list(speed, 1, 'u')
777
+
778
+ def _orient_frames(self):
779
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
780
+ self.child_interframe.orient_axis(
781
+ self.parent_interframe, self.joint_axis, self.coordinates[0])
782
+
783
+ def _set_angular_velocity(self):
784
+ self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[
785
+ 0] * self.joint_axis.normalize())
786
+
787
+ def _set_linear_velocity(self):
788
+ self.child_point.set_pos(self.parent_point, 0)
789
+ self.parent_point.set_vel(self.parent.frame, 0)
790
+ self.child_point.set_vel(self.child.frame, 0)
791
+ self.child.masscenter.v2pt_theory(self.parent_point,
792
+ self.parent.frame, self.child.frame)
793
+
794
+
795
+ class PrismaticJoint(Joint):
796
+ """Prismatic (Sliding) Joint.
797
+
798
+ .. image:: PrismaticJoint.svg
799
+
800
+ Explanation
801
+ ===========
802
+
803
+ It is defined such that the child body translates with respect to the parent
804
+ body along the body-fixed joint axis. The location of the joint is defined
805
+ by two points, one in each body, which coincide when the generalized
806
+ coordinate is zero. The direction cosine matrix between the
807
+ parent_interframe and child_interframe is the identity matrix. Therefore,
808
+ the direction cosine matrix between the parent and child frames is fully
809
+ defined by the definition of the intermediate frames. The page on the joints
810
+ framework gives a more detailed explanation of the intermediate frames.
811
+
812
+ Parameters
813
+ ==========
814
+
815
+ name : string
816
+ A unique name for the joint.
817
+ parent : Body
818
+ The parent body of joint.
819
+ child : Body
820
+ The child body of joint.
821
+ coordinates : dynamicsymbol, optional
822
+ Generalized coordinates of the joint. The default value is
823
+ ``dynamicsymbols(f'q_{joint.name}')``.
824
+ speeds : dynamicsymbol, optional
825
+ Generalized speeds of joint. The default value is
826
+ ``dynamicsymbols(f'u_{joint.name}')``.
827
+ parent_point : Point or Vector, optional
828
+ Attachment point where the joint is fixed to the parent body. If a
829
+ vector is provided, then the attachment point is computed by adding the
830
+ vector to the body's mass center. The default value is the parent's mass
831
+ center.
832
+ child_point : Point or Vector, optional
833
+ Attachment point where the joint is fixed to the child body. If a
834
+ vector is provided, then the attachment point is computed by adding the
835
+ vector to the body's mass center. The default value is the child's mass
836
+ center.
837
+ parent_axis : Vector, optional
838
+ .. deprecated:: 1.12
839
+ Axis fixed in the parent body which aligns with an axis fixed in the
840
+ child body. The default is the x axis of parent's reference frame.
841
+ For more information on this deprecation, see
842
+ :ref:`deprecated-mechanics-joint-axis`.
843
+ child_axis : Vector, optional
844
+ .. deprecated:: 1.12
845
+ Axis fixed in the child body which aligns with an axis fixed in the
846
+ parent body. The default is the x axis of child's reference frame.
847
+ For more information on this deprecation, see
848
+ :ref:`deprecated-mechanics-joint-axis`.
849
+ parent_interframe : ReferenceFrame, optional
850
+ Intermediate frame of the parent body with respect to which the joint
851
+ transformation is formulated. If a Vector is provided then an interframe
852
+ is created which aligns its X axis with the given vector. The default
853
+ value is the parent's own frame.
854
+ child_interframe : ReferenceFrame, optional
855
+ Intermediate frame of the child body with respect to which the joint
856
+ transformation is formulated. If a Vector is provided then an interframe
857
+ is created which aligns its X axis with the given vector. The default
858
+ value is the child's own frame.
859
+ joint_axis : Vector
860
+ The axis along which the translation occurs. Note that the components
861
+ of this axis are the same in the parent_interframe and child_interframe.
862
+ parent_joint_pos : Point or Vector, optional
863
+ .. deprecated:: 1.12
864
+ This argument is replaced by parent_point and will be removed in a
865
+ future version.
866
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
867
+ child_joint_pos : Point or Vector, optional
868
+ .. deprecated:: 1.12
869
+ This argument is replaced by child_point and will be removed in a
870
+ future version.
871
+ See :ref:`deprecated-mechanics-joint-pos` for more information.
872
+
873
+ Attributes
874
+ ==========
875
+
876
+ name : string
877
+ The joint's name.
878
+ parent : Body
879
+ The joint's parent body.
880
+ child : Body
881
+ The joint's child body.
882
+ coordinates : Matrix
883
+ Matrix of the joint's generalized coordinates.
884
+ speeds : Matrix
885
+ Matrix of the joint's generalized speeds.
886
+ parent_point : Point
887
+ Attachment point where the joint is fixed to the parent body.
888
+ child_point : Point
889
+ Attachment point where the joint is fixed to the child body.
890
+ parent_axis : Vector
891
+ The axis fixed in the parent frame that represents the joint.
892
+ child_axis : Vector
893
+ The axis fixed in the child frame that represents the joint.
894
+ parent_interframe : ReferenceFrame
895
+ Intermediate frame of the parent body with respect to which the joint
896
+ transformation is formulated.
897
+ child_interframe : ReferenceFrame
898
+ Intermediate frame of the child body with respect to which the joint
899
+ transformation is formulated.
900
+ kdes : Matrix
901
+ Kinematical differential equations of the joint.
902
+
903
+ Examples
904
+ =========
905
+
906
+ A single prismatic joint is created from two bodies and has the following
907
+ basic attributes:
908
+
909
+ >>> from sympy.physics.mechanics import Body, PrismaticJoint
910
+ >>> parent = Body('P')
911
+ >>> parent
912
+ P
913
+ >>> child = Body('C')
914
+ >>> child
915
+ C
916
+ >>> joint = PrismaticJoint('PC', parent, child)
917
+ >>> joint
918
+ PrismaticJoint: PC parent: P child: C
919
+ >>> joint.name
920
+ 'PC'
921
+ >>> joint.parent
922
+ P
923
+ >>> joint.child
924
+ C
925
+ >>> joint.parent_point
926
+ P_masscenter
927
+ >>> joint.child_point
928
+ C_masscenter
929
+ >>> joint.parent_axis
930
+ P_frame.x
931
+ >>> joint.child_axis
932
+ C_frame.x
933
+ >>> joint.coordinates
934
+ Matrix([[q_PC(t)]])
935
+ >>> joint.speeds
936
+ Matrix([[u_PC(t)]])
937
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
938
+ 0
939
+ >>> joint.child.frame.dcm(joint.parent.frame)
940
+ Matrix([
941
+ [1, 0, 0],
942
+ [0, 1, 0],
943
+ [0, 0, 1]])
944
+ >>> joint.child_point.pos_from(joint.parent_point)
945
+ q_PC(t)*P_frame.x
946
+
947
+ To further demonstrate the use of the prismatic joint, the kinematics of two
948
+ masses sliding, one moving relative to a fixed body and the other relative
949
+ to the moving body. about the X axis of each connected body can be created
950
+ as follows.
951
+
952
+ >>> from sympy.physics.mechanics import PrismaticJoint, Body
953
+
954
+ First create bodies to represent the fixed ceiling and one to represent
955
+ a particle.
956
+
957
+ >>> wall = Body('W')
958
+ >>> Part1 = Body('P1')
959
+ >>> Part2 = Body('P2')
960
+
961
+ The first joint will connect the particle to the ceiling and the
962
+ joint axis will be about the X axis for each body.
963
+
964
+ >>> J1 = PrismaticJoint('J1', wall, Part1)
965
+
966
+ The second joint will connect the second particle to the first particle
967
+ and the joint axis will also be about the X axis for each body.
968
+
969
+ >>> J2 = PrismaticJoint('J2', Part1, Part2)
970
+
971
+ Once the joint is established the kinematics of the connected bodies can
972
+ be accessed. First the direction cosine matrices of Part relative
973
+ to the ceiling are found:
974
+
975
+ >>> Part1.dcm(wall)
976
+ Matrix([
977
+ [1, 0, 0],
978
+ [0, 1, 0],
979
+ [0, 0, 1]])
980
+
981
+ >>> Part2.dcm(wall)
982
+ Matrix([
983
+ [1, 0, 0],
984
+ [0, 1, 0],
985
+ [0, 0, 1]])
986
+
987
+ The position of the particles' masscenter is found with:
988
+
989
+ >>> Part1.masscenter.pos_from(wall.masscenter)
990
+ q_J1(t)*W_frame.x
991
+
992
+ >>> Part2.masscenter.pos_from(wall.masscenter)
993
+ q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x
994
+
995
+ The angular velocities of the two particle links can be computed with
996
+ respect to the ceiling.
997
+
998
+ >>> Part1.ang_vel_in(wall)
999
+ 0
1000
+
1001
+ >>> Part2.ang_vel_in(wall)
1002
+ 0
1003
+
1004
+ And finally, the linear velocities of the two particles can be computed
1005
+ with respect to the ceiling.
1006
+
1007
+ >>> Part1.masscenter_vel(wall)
1008
+ u_J1(t)*W_frame.x
1009
+
1010
+ >>> Part2.masscenter.vel(wall.frame)
1011
+ u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x
1012
+
1013
+ """
1014
+
1015
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1016
+ parent_point=None, child_point=None, parent_axis=None,
1017
+ child_axis=None, parent_interframe=None, child_interframe=None,
1018
+ joint_axis=None, parent_joint_pos=None, child_joint_pos=None):
1019
+
1020
+ self._joint_axis = joint_axis
1021
+ super().__init__(name, parent, child, coordinates, speeds, parent_point,
1022
+ child_point, parent_axis, child_axis,
1023
+ parent_interframe, child_interframe, parent_joint_pos,
1024
+ child_joint_pos)
1025
+
1026
+ def __str__(self):
1027
+ return (f'PrismaticJoint: {self.name} parent: {self.parent} '
1028
+ f'child: {self.child}')
1029
+
1030
+ @property
1031
+ def joint_axis(self):
1032
+ """Axis along which the child translates with respect to the parent."""
1033
+ return self._joint_axis
1034
+
1035
+ def _generate_coordinates(self, coordinate):
1036
+ return self._fill_coordinate_list(coordinate, 1, 'q')
1037
+
1038
+ def _generate_speeds(self, speed):
1039
+ return self._fill_coordinate_list(speed, 1, 'u')
1040
+
1041
+ def _orient_frames(self):
1042
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1043
+ self.child_interframe.orient_axis(
1044
+ self.parent_interframe, self.joint_axis, 0)
1045
+
1046
+ def _set_angular_velocity(self):
1047
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
1048
+
1049
+ def _set_linear_velocity(self):
1050
+ axis = self.joint_axis.normalize()
1051
+ self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis)
1052
+ self.parent_point.set_vel(self.parent.frame, 0)
1053
+ self.child_point.set_vel(self.child.frame, 0)
1054
+ self.child_point.set_vel(self.parent.frame, self.speeds[0] * axis)
1055
+ self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * axis)
1056
+
1057
+
1058
+ class CylindricalJoint(Joint):
1059
+ """Cylindrical Joint.
1060
+
1061
+ .. image:: CylindricalJoint.svg
1062
+ :align: center
1063
+ :width: 600
1064
+
1065
+ Explanation
1066
+ ===========
1067
+
1068
+ A cylindrical joint is defined such that the child body both rotates about
1069
+ and translates along the body-fixed joint axis with respect to the parent
1070
+ body. The joint axis is both the rotation axis and translation axis. The
1071
+ location of the joint is defined by two points, one in each body, which
1072
+ coincide when the generalized coordinate corresponding to the translation is
1073
+ zero. The direction cosine matrix between the child interframe and parent
1074
+ interframe is formed using a simple rotation about the joint axis. The page
1075
+ on the joints framework gives a more detailed explanation of the
1076
+ intermediate frames.
1077
+
1078
+ Parameters
1079
+ ==========
1080
+
1081
+ name : string
1082
+ A unique name for the joint.
1083
+ parent : Body
1084
+ The parent body of joint.
1085
+ child : Body
1086
+ The child body of joint.
1087
+ rotation_coordinate : dynamicsymbol, optional
1088
+ Generalized coordinate corresponding to the rotation angle. The default
1089
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1090
+ translation_coordinate : dynamicsymbol, optional
1091
+ Generalized coordinate corresponding to the translation distance. The
1092
+ default value is ``dynamicsymbols(f'q1_{joint.name}')``.
1093
+ rotation_speed : dynamicsymbol, optional
1094
+ Generalized speed corresponding to the angular velocity. The default
1095
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1096
+ translation_speed : dynamicsymbol, optional
1097
+ Generalized speed corresponding to the translation velocity. The default
1098
+ value is ``dynamicsymbols(f'u1_{joint.name}')``.
1099
+ parent_point : Point or Vector, optional
1100
+ Attachment point where the joint is fixed to the parent body. If a
1101
+ vector is provided, then the attachment point is computed by adding the
1102
+ vector to the body's mass center. The default value is the parent's mass
1103
+ center.
1104
+ child_point : Point or Vector, optional
1105
+ Attachment point where the joint is fixed to the child body. If a
1106
+ vector is provided, then the attachment point is computed by adding the
1107
+ vector to the body's mass center. The default value is the child's mass
1108
+ center.
1109
+ parent_interframe : ReferenceFrame, optional
1110
+ Intermediate frame of the parent body with respect to which the joint
1111
+ transformation is formulated. If a Vector is provided then an interframe
1112
+ is created which aligns its X axis with the given vector. The default
1113
+ value is the parent's own frame.
1114
+ child_interframe : ReferenceFrame, optional
1115
+ Intermediate frame of the child body with respect to which the joint
1116
+ transformation is formulated. If a Vector is provided then an interframe
1117
+ is created which aligns its X axis with the given vector. The default
1118
+ value is the child's own frame.
1119
+ joint_axis : Vector, optional
1120
+ The rotation as well as translation axis. Note that the components of
1121
+ this axis are the same in the parent_interframe and child_interframe.
1122
+
1123
+ Attributes
1124
+ ==========
1125
+
1126
+ name : string
1127
+ The joint's name.
1128
+ parent : Body
1129
+ The joint's parent body.
1130
+ child : Body
1131
+ The joint's child body.
1132
+ rotation_coordinate : dynamicsymbol
1133
+ Generalized coordinate corresponding to the rotation angle.
1134
+ translation_coordinate : dynamicsymbol
1135
+ Generalized coordinate corresponding to the translation distance.
1136
+ rotation_speed : dynamicsymbol
1137
+ Generalized speed corresponding to the angular velocity.
1138
+ translation_speed : dynamicsymbol
1139
+ Generalized speed corresponding to the translation velocity.
1140
+ coordinates : Matrix
1141
+ Matrix of the joint's generalized coordinates.
1142
+ speeds : Matrix
1143
+ Matrix of the joint's generalized speeds.
1144
+ parent_point : Point
1145
+ Attachment point where the joint is fixed to the parent body.
1146
+ child_point : Point
1147
+ Attachment point where the joint is fixed to the child body.
1148
+ parent_interframe : ReferenceFrame
1149
+ Intermediate frame of the parent body with respect to which the joint
1150
+ transformation is formulated.
1151
+ child_interframe : ReferenceFrame
1152
+ Intermediate frame of the child body with respect to which the joint
1153
+ transformation is formulated.
1154
+ kdes : Matrix
1155
+ Kinematical differential equations of the joint.
1156
+ joint_axis : Vector
1157
+ The axis of rotation and translation.
1158
+
1159
+ Examples
1160
+ =========
1161
+
1162
+ A single cylindrical joint is created between two bodies and has the
1163
+ following basic attributes:
1164
+
1165
+ >>> from sympy.physics.mechanics import Body, CylindricalJoint
1166
+ >>> parent = Body('P')
1167
+ >>> parent
1168
+ P
1169
+ >>> child = Body('C')
1170
+ >>> child
1171
+ C
1172
+ >>> joint = CylindricalJoint('PC', parent, child)
1173
+ >>> joint
1174
+ CylindricalJoint: PC parent: P child: C
1175
+ >>> joint.name
1176
+ 'PC'
1177
+ >>> joint.parent
1178
+ P
1179
+ >>> joint.child
1180
+ C
1181
+ >>> joint.parent_point
1182
+ P_masscenter
1183
+ >>> joint.child_point
1184
+ C_masscenter
1185
+ >>> joint.parent_axis
1186
+ P_frame.x
1187
+ >>> joint.child_axis
1188
+ C_frame.x
1189
+ >>> joint.coordinates
1190
+ Matrix([
1191
+ [q0_PC(t)],
1192
+ [q1_PC(t)]])
1193
+ >>> joint.speeds
1194
+ Matrix([
1195
+ [u0_PC(t)],
1196
+ [u1_PC(t)]])
1197
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
1198
+ u0_PC(t)*P_frame.x
1199
+ >>> joint.child.frame.dcm(joint.parent.frame)
1200
+ Matrix([
1201
+ [1, 0, 0],
1202
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1203
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1204
+ >>> joint.child_point.pos_from(joint.parent_point)
1205
+ q1_PC(t)*P_frame.x
1206
+ >>> child.masscenter.vel(parent.frame)
1207
+ u1_PC(t)*P_frame.x
1208
+
1209
+ To further demonstrate the use of the cylindrical joint, the kinematics of
1210
+ two cylindrical joints perpendicular to each other can be created as follows.
1211
+
1212
+ >>> from sympy import symbols
1213
+ >>> from sympy.physics.mechanics import Body, CylindricalJoint
1214
+ >>> r, l, w = symbols('r l w')
1215
+
1216
+ First create bodies to represent the fixed floor with a fixed pole on it.
1217
+ The second body represents a freely moving tube around that pole. The third
1218
+ body represents a solid flag freely translating along and rotating around
1219
+ the Y axis of the tube.
1220
+
1221
+ >>> floor = Body('floor')
1222
+ >>> tube = Body('tube')
1223
+ >>> flag = Body('flag')
1224
+
1225
+ The first joint will connect the first tube to the floor with it translating
1226
+ along and rotating around the Z axis of both bodies.
1227
+
1228
+ >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z)
1229
+
1230
+ The second joint will connect the tube perpendicular to the flag along the Y
1231
+ axis of both the tube and the flag, with the joint located at a distance
1232
+ ``r`` from the tube's center of mass and a combination of the distances
1233
+ ``l`` and ``w`` from the flag's center of mass.
1234
+
1235
+ >>> flag_joint = CylindricalJoint('C2', tube, flag,
1236
+ ... parent_point=r * tube.y,
1237
+ ... child_point=-w * flag.y + l * flag.z,
1238
+ ... joint_axis=tube.y)
1239
+
1240
+ Once the joints are established the kinematics of the connected bodies can
1241
+ be accessed. First the direction cosine matrices of both the body and the
1242
+ flag relative to the floor are found:
1243
+
1244
+ >>> tube.dcm(floor)
1245
+ Matrix([
1246
+ [ cos(q0_C1(t)), sin(q0_C1(t)), 0],
1247
+ [-sin(q0_C1(t)), cos(q0_C1(t)), 0],
1248
+ [ 0, 0, 1]])
1249
+ >>> flag.dcm(floor)
1250
+ Matrix([
1251
+ [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))],
1252
+ [ -sin(q0_C1(t)), cos(q0_C1(t)), 0],
1253
+ [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]])
1254
+
1255
+ The position of the flag's center of mass is found with:
1256
+
1257
+ >>> flag.masscenter.pos_from(floor.masscenter)
1258
+ q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z
1259
+
1260
+ The angular velocities of the two tubes can be computed with respect to the
1261
+ floor.
1262
+
1263
+ >>> tube.ang_vel_in(floor)
1264
+ u0_C1(t)*floor_frame.z
1265
+ >>> flag.ang_vel_in(floor)
1266
+ u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y
1267
+
1268
+ Finally, the linear velocities of the two tube centers of mass can be
1269
+ computed with respect to the floor, while expressed in the tube's frame.
1270
+
1271
+ >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame)
1272
+ Matrix([
1273
+ [ 0],
1274
+ [ 0],
1275
+ [u1_C1(t)]])
1276
+ >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify()
1277
+ Matrix([
1278
+ [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)],
1279
+ [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)],
1280
+ [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]])
1281
+
1282
+ """
1283
+
1284
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1285
+ translation_coordinate=None, rotation_speed=None,
1286
+ translation_speed=None, parent_point=None, child_point=None,
1287
+ parent_interframe=None, child_interframe=None,
1288
+ joint_axis=None):
1289
+ self._joint_axis = joint_axis
1290
+ coordinates = (rotation_coordinate, translation_coordinate)
1291
+ speeds = (rotation_speed, translation_speed)
1292
+ super().__init__(name, parent, child, coordinates, speeds,
1293
+ parent_point, child_point,
1294
+ parent_interframe=parent_interframe,
1295
+ child_interframe=child_interframe)
1296
+
1297
+ def __str__(self):
1298
+ return (f'CylindricalJoint: {self.name} parent: {self.parent} '
1299
+ f'child: {self.child}')
1300
+
1301
+ @property
1302
+ def joint_axis(self):
1303
+ """Axis about and along which the rotation and translation occurs."""
1304
+ return self._joint_axis
1305
+
1306
+ @property
1307
+ def rotation_coordinate(self):
1308
+ """Generalized coordinate corresponding to the rotation angle."""
1309
+ return self.coordinates[0]
1310
+
1311
+ @property
1312
+ def translation_coordinate(self):
1313
+ """Generalized coordinate corresponding to the translation distance."""
1314
+ return self.coordinates[1]
1315
+
1316
+ @property
1317
+ def rotation_speed(self):
1318
+ """Generalized speed corresponding to the angular velocity."""
1319
+ return self.speeds[0]
1320
+
1321
+ @property
1322
+ def translation_speed(self):
1323
+ """Generalized speed corresponding to the translation velocity."""
1324
+ return self.speeds[1]
1325
+
1326
+ def _generate_coordinates(self, coordinates):
1327
+ return self._fill_coordinate_list(coordinates, 2, 'q')
1328
+
1329
+ def _generate_speeds(self, speeds):
1330
+ return self._fill_coordinate_list(speeds, 2, 'u')
1331
+
1332
+ def _orient_frames(self):
1333
+ self._joint_axis = self._axis(self.joint_axis, self.parent_interframe)
1334
+ self.child_interframe.orient_axis(
1335
+ self.parent_interframe, self.joint_axis, self.rotation_coordinate)
1336
+
1337
+ def _set_angular_velocity(self):
1338
+ self.child_interframe.set_ang_vel(
1339
+ self.parent_interframe,
1340
+ self.rotation_speed * self.joint_axis.normalize())
1341
+
1342
+ def _set_linear_velocity(self):
1343
+ self.child_point.set_pos(
1344
+ self.parent_point,
1345
+ self.translation_coordinate * self.joint_axis.normalize())
1346
+ self.parent_point.set_vel(self.parent.frame, 0)
1347
+ self.child_point.set_vel(self.child.frame, 0)
1348
+ self.child_point.set_vel(
1349
+ self.parent.frame,
1350
+ self.translation_speed * self.joint_axis.normalize())
1351
+ self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame,
1352
+ self.child_interframe)
1353
+
1354
+
1355
+ class PlanarJoint(Joint):
1356
+ """Planar Joint.
1357
+
1358
+ .. image:: PlanarJoint.svg
1359
+ :align: center
1360
+ :width: 800
1361
+
1362
+ Explanation
1363
+ ===========
1364
+
1365
+ A planar joint is defined such that the child body translates over a fixed
1366
+ plane of the parent body as well as rotate about the rotation axis, which
1367
+ is perpendicular to that plane. The origin of this plane is the
1368
+ ``parent_point`` and the plane is spanned by two nonparallel planar vectors.
1369
+ The location of the ``child_point`` is based on the planar vectors
1370
+ ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$),
1371
+ i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine
1372
+ matrix between the ``child_interframe`` and ``parent_interframe`` is formed
1373
+ using a simple rotation ($q_0$) about the rotation axis.
1374
+
1375
+ In order to simplify the definition of the ``PlanarJoint``, the
1376
+ ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of
1377
+ the ``parent_interframe`` according to the table below. This ensures that
1378
+ you can only define these vectors by creating a separate frame and supplying
1379
+ that as the interframe. If you however would only like to supply the normals
1380
+ of the plane with respect to the parent and child bodies, then you can also
1381
+ supply those to the ``parent_interframe`` and ``child_interframe``
1382
+ arguments. An example of both of these cases is in the examples section
1383
+ below and the page on the joints framework provides a more detailed
1384
+ explanation of the intermediate frames.
1385
+
1386
+ .. list-table::
1387
+
1388
+ * - ``rotation_axis``
1389
+ - ``parent_interframe.x``
1390
+ * - ``planar_vectors[0]``
1391
+ - ``parent_interframe.y``
1392
+ * - ``planar_vectors[1]``
1393
+ - ``parent_interframe.z``
1394
+
1395
+ Parameters
1396
+ ==========
1397
+
1398
+ name : string
1399
+ A unique name for the joint.
1400
+ parent : Body
1401
+ The parent body of joint.
1402
+ child : Body
1403
+ The child body of joint.
1404
+ rotation_coordinate : dynamicsymbol, optional
1405
+ Generalized coordinate corresponding to the rotation angle. The default
1406
+ value is ``dynamicsymbols(f'q0_{joint.name}')``.
1407
+ planar_coordinates : iterable of dynamicsymbols, optional
1408
+ Two generalized coordinates used for the planar translation. The default
1409
+ value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``.
1410
+ rotation_speed : dynamicsymbol, optional
1411
+ Generalized speed corresponding to the angular velocity. The default
1412
+ value is ``dynamicsymbols(f'u0_{joint.name}')``.
1413
+ planar_speeds : dynamicsymbols, optional
1414
+ Two generalized speeds used for the planar translation velocity. The
1415
+ default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``.
1416
+ parent_point : Point or Vector, optional
1417
+ Attachment point where the joint is fixed to the parent body. If a
1418
+ vector is provided, then the attachment point is computed by adding the
1419
+ vector to the body's mass center. The default value is the parent's mass
1420
+ center.
1421
+ child_point : Point or Vector, optional
1422
+ Attachment point where the joint is fixed to the child body. If a
1423
+ vector is provided, then the attachment point is computed by adding the
1424
+ vector to the body's mass center. The default value is the child's mass
1425
+ center.
1426
+ parent_interframe : ReferenceFrame, optional
1427
+ Intermediate frame of the parent body with respect to which the joint
1428
+ transformation is formulated. If a Vector is provided then an interframe
1429
+ is created which aligns its X axis with the given vector. The default
1430
+ value is the parent's own frame.
1431
+ child_interframe : ReferenceFrame, optional
1432
+ Intermediate frame of the child body with respect to which the joint
1433
+ transformation is formulated. If a Vector is provided then an interframe
1434
+ is created which aligns its X axis with the given vector. The default
1435
+ value is the child's own frame.
1436
+
1437
+ Attributes
1438
+ ==========
1439
+
1440
+ name : string
1441
+ The joint's name.
1442
+ parent : Body
1443
+ The joint's parent body.
1444
+ child : Body
1445
+ The joint's child body.
1446
+ rotation_coordinate : dynamicsymbol
1447
+ Generalized coordinate corresponding to the rotation angle.
1448
+ planar_coordinates : Matrix
1449
+ Two generalized coordinates used for the planar translation.
1450
+ rotation_speed : dynamicsymbol
1451
+ Generalized speed corresponding to the angular velocity.
1452
+ planar_speeds : Matrix
1453
+ Two generalized speeds used for the planar translation velocity.
1454
+ coordinates : Matrix
1455
+ Matrix of the joint's generalized coordinates.
1456
+ speeds : Matrix
1457
+ Matrix of the joint's generalized speeds.
1458
+ parent_point : Point
1459
+ Attachment point where the joint is fixed to the parent body.
1460
+ child_point : Point
1461
+ Attachment point where the joint is fixed to the child body.
1462
+ parent_interframe : ReferenceFrame
1463
+ Intermediate frame of the parent body with respect to which the joint
1464
+ transformation is formulated.
1465
+ child_interframe : ReferenceFrame
1466
+ Intermediate frame of the child body with respect to which the joint
1467
+ transformation is formulated.
1468
+ kdes : Matrix
1469
+ Kinematical differential equations of the joint.
1470
+ rotation_axis : Vector
1471
+ The axis about which the rotation occurs.
1472
+ planar_vectors : list
1473
+ The vectors that describe the planar translation directions.
1474
+
1475
+ Examples
1476
+ =========
1477
+
1478
+ A single planar joint is created between two bodies and has the following
1479
+ basic attributes:
1480
+
1481
+ >>> from sympy.physics.mechanics import Body, PlanarJoint
1482
+ >>> parent = Body('P')
1483
+ >>> parent
1484
+ P
1485
+ >>> child = Body('C')
1486
+ >>> child
1487
+ C
1488
+ >>> joint = PlanarJoint('PC', parent, child)
1489
+ >>> joint
1490
+ PlanarJoint: PC parent: P child: C
1491
+ >>> joint.name
1492
+ 'PC'
1493
+ >>> joint.parent
1494
+ P
1495
+ >>> joint.child
1496
+ C
1497
+ >>> joint.parent_point
1498
+ P_masscenter
1499
+ >>> joint.child_point
1500
+ C_masscenter
1501
+ >>> joint.rotation_axis
1502
+ P_frame.x
1503
+ >>> joint.planar_vectors
1504
+ [P_frame.y, P_frame.z]
1505
+ >>> joint.rotation_coordinate
1506
+ q0_PC(t)
1507
+ >>> joint.planar_coordinates
1508
+ Matrix([
1509
+ [q1_PC(t)],
1510
+ [q2_PC(t)]])
1511
+ >>> joint.coordinates
1512
+ Matrix([
1513
+ [q0_PC(t)],
1514
+ [q1_PC(t)],
1515
+ [q2_PC(t)]])
1516
+ >>> joint.rotation_speed
1517
+ u0_PC(t)
1518
+ >>> joint.planar_speeds
1519
+ Matrix([
1520
+ [u1_PC(t)],
1521
+ [u2_PC(t)]])
1522
+ >>> joint.speeds
1523
+ Matrix([
1524
+ [u0_PC(t)],
1525
+ [u1_PC(t)],
1526
+ [u2_PC(t)]])
1527
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
1528
+ u0_PC(t)*P_frame.x
1529
+ >>> joint.child.frame.dcm(joint.parent.frame)
1530
+ Matrix([
1531
+ [1, 0, 0],
1532
+ [0, cos(q0_PC(t)), sin(q0_PC(t))],
1533
+ [0, -sin(q0_PC(t)), cos(q0_PC(t))]])
1534
+ >>> joint.child_point.pos_from(joint.parent_point)
1535
+ q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z
1536
+ >>> child.masscenter.vel(parent.frame)
1537
+ u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z
1538
+
1539
+ To further demonstrate the use of the planar joint, the kinematics of a
1540
+ block sliding on a slope, can be created as follows.
1541
+
1542
+ >>> from sympy import symbols
1543
+ >>> from sympy.physics.mechanics import PlanarJoint, Body, ReferenceFrame
1544
+ >>> a, d, h = symbols('a d h')
1545
+
1546
+ First create bodies to represent the slope and the block.
1547
+
1548
+ >>> ground = Body('G')
1549
+ >>> block = Body('B')
1550
+
1551
+ To define the slope you can either define the plane by specifying the
1552
+ ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to
1553
+ create a rotated intermediate frame, so that the ``parent_vectors`` and
1554
+ ``rotation_axis`` will be the unit vectors of this intermediate frame.
1555
+
1556
+ >>> slope = ReferenceFrame('A')
1557
+ >>> slope.orient_axis(ground.frame, ground.y, a)
1558
+
1559
+ The planar joint can be created using these bodies and intermediate frame.
1560
+ We can specify the origin of the slope to be ``d`` above the slope's center
1561
+ of mass and the block's center of mass to be a distance ``h`` above the
1562
+ slope's surface. Note that we can specify the normal of the plane using the
1563
+ rotation axis argument.
1564
+
1565
+ >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x,
1566
+ ... child_point=-h * block.x, parent_interframe=slope)
1567
+
1568
+ Once the joint is established the kinematics of the bodies can be accessed.
1569
+ First the ``rotation_axis``, which is normal to the plane and the
1570
+ ``plane_vectors``, can be found.
1571
+
1572
+ >>> joint.rotation_axis
1573
+ A.x
1574
+ >>> joint.planar_vectors
1575
+ [A.y, A.z]
1576
+
1577
+ The direction cosine matrix of the block with respect to the ground can be
1578
+ found with:
1579
+
1580
+ >>> block.dcm(ground)
1581
+ Matrix([
1582
+ [ cos(a), 0, -sin(a)],
1583
+ [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1584
+ [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1585
+
1586
+ The angular velocity of the block can be computed with respect to the
1587
+ ground.
1588
+
1589
+ >>> block.ang_vel_in(ground)
1590
+ u0_PC(t)*A.x
1591
+
1592
+ The position of the block's center of mass can be found with:
1593
+
1594
+ >>> block.masscenter.pos_from(ground.masscenter)
1595
+ d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z
1596
+
1597
+ Finally, the linear velocity of the block's center of mass can be
1598
+ computed with respect to the ground.
1599
+
1600
+ >>> block.masscenter.vel(ground.frame)
1601
+ u1_PC(t)*A.y + u2_PC(t)*A.z
1602
+
1603
+ In some cases it could be your preference to only define the normals of the
1604
+ plane with respect to both bodies. This can most easily be done by supplying
1605
+ vectors to the ``interframe`` arguments. What will happen in this case is
1606
+ that an interframe will be created with its ``x`` axis aligned with the
1607
+ provided vector. For a further explanation of how this is done see the notes
1608
+ of the ``Joint`` class. In the code below, the above example (with the block
1609
+ on the slope) is recreated by supplying vectors to the interframe arguments.
1610
+ Note that the previously described option is however more computationally
1611
+ efficient, because the algorithm now has to compute the rotation angle
1612
+ between the provided vector and the 'x' axis.
1613
+
1614
+ >>> from sympy import symbols, cos, sin
1615
+ >>> from sympy.physics.mechanics import PlanarJoint, Body
1616
+ >>> a, d, h = symbols('a d h')
1617
+ >>> ground = Body('G')
1618
+ >>> block = Body('B')
1619
+ >>> joint = PlanarJoint(
1620
+ ... 'PC', ground, block, parent_point=d * ground.x,
1621
+ ... child_point=-h * block.x, child_interframe=block.x,
1622
+ ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z)
1623
+ >>> block.dcm(ground).simplify()
1624
+ Matrix([
1625
+ [ cos(a), 0, sin(a)],
1626
+ [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)],
1627
+ [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]])
1628
+
1629
+ """
1630
+
1631
+ def __init__(self, name, parent, child, rotation_coordinate=None,
1632
+ planar_coordinates=None, rotation_speed=None,
1633
+ planar_speeds=None, parent_point=None, child_point=None,
1634
+ parent_interframe=None, child_interframe=None):
1635
+ # A ready to merge implementation of setting the planar_vectors and
1636
+ # rotation_axis was added and removed in PR #24046
1637
+ coordinates = (rotation_coordinate, planar_coordinates)
1638
+ speeds = (rotation_speed, planar_speeds)
1639
+ super().__init__(name, parent, child, coordinates, speeds,
1640
+ parent_point, child_point,
1641
+ parent_interframe=parent_interframe,
1642
+ child_interframe=child_interframe)
1643
+
1644
+ def __str__(self):
1645
+ return (f'PlanarJoint: {self.name} parent: {self.parent} '
1646
+ f'child: {self.child}')
1647
+
1648
+ @property
1649
+ def rotation_coordinate(self):
1650
+ """Generalized coordinate corresponding to the rotation angle."""
1651
+ return self.coordinates[0]
1652
+
1653
+ @property
1654
+ def planar_coordinates(self):
1655
+ """Two generalized coordinates used for the planar translation."""
1656
+ return self.coordinates[1:, 0]
1657
+
1658
+ @property
1659
+ def rotation_speed(self):
1660
+ """Generalized speed corresponding to the angular velocity."""
1661
+ return self.speeds[0]
1662
+
1663
+ @property
1664
+ def planar_speeds(self):
1665
+ """Two generalized speeds used for the planar translation velocity."""
1666
+ return self.speeds[1:, 0]
1667
+
1668
+ @property
1669
+ def rotation_axis(self):
1670
+ """The axis about which the rotation occurs."""
1671
+ return self.parent_interframe.x
1672
+
1673
+ @property
1674
+ def planar_vectors(self):
1675
+ """The vectors that describe the planar translation directions."""
1676
+ return [self.parent_interframe.y, self.parent_interframe.z]
1677
+
1678
+ def _generate_coordinates(self, coordinates):
1679
+ rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q',
1680
+ number_single=True)
1681
+ planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1)
1682
+ return rotation_speed.col_join(planar_speeds)
1683
+
1684
+ def _generate_speeds(self, speeds):
1685
+ rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u',
1686
+ number_single=True)
1687
+ planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1)
1688
+ return rotation_speed.col_join(planar_speeds)
1689
+
1690
+ def _orient_frames(self):
1691
+ self.child_interframe.orient_axis(
1692
+ self.parent_interframe, self.rotation_axis,
1693
+ self.rotation_coordinate)
1694
+
1695
+ def _set_angular_velocity(self):
1696
+ self.child_interframe.set_ang_vel(
1697
+ self.parent_interframe,
1698
+ self.rotation_speed * self.rotation_axis)
1699
+
1700
+ def _set_linear_velocity(self):
1701
+ self.child_point.set_pos(
1702
+ self.parent_point,
1703
+ self.planar_coordinates[0] * self.planar_vectors[0] +
1704
+ self.planar_coordinates[1] * self.planar_vectors[1])
1705
+ self.parent_point.set_vel(self.parent_interframe, 0)
1706
+ self.child_point.set_vel(self.child_interframe, 0)
1707
+ self.child_point.set_vel(
1708
+ self.parent.frame, self.planar_speeds[0] * self.planar_vectors[0] +
1709
+ self.planar_speeds[1] * self.planar_vectors[1])
1710
+ self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame,
1711
+ self.child.frame)
1712
+
1713
+
1714
+ class SphericalJoint(Joint):
1715
+ """Spherical (Ball-and-Socket) Joint.
1716
+
1717
+ .. image:: SphericalJoint.svg
1718
+ :align: center
1719
+ :width: 600
1720
+
1721
+ Explanation
1722
+ ===========
1723
+
1724
+ A spherical joint is defined such that the child body is free to rotate in
1725
+ any direction, without allowing a translation of the ``child_point``. As can
1726
+ also be seen in the image, the ``parent_point`` and ``child_point`` are
1727
+ fixed on top of each other, i.e. the ``joint_point``. This rotation is
1728
+ defined using the :func:`parent_interframe.orient(child_interframe,
1729
+ rot_type, amounts, rot_order)
1730
+ <sympy.physics.vector.frame.ReferenceFrame.orient>` method. The default
1731
+ rotation consists of three relative rotations, i.e. body-fixed rotations.
1732
+ Based on the direction cosine matrix following from these rotations, the
1733
+ angular velocity is computed based on the generalized coordinates and
1734
+ generalized speeds.
1735
+
1736
+ Parameters
1737
+ ==========
1738
+
1739
+ name : string
1740
+ A unique name for the joint.
1741
+ parent : Body
1742
+ The parent body of joint.
1743
+ child : Body
1744
+ The child body of joint.
1745
+ coordinates: iterable of dynamicsymbols, optional
1746
+ Generalized coordinates of the joint.
1747
+ speeds : iterable of dynamicsymbols, optional
1748
+ Generalized speeds of joint.
1749
+ parent_point : Point or Vector, optional
1750
+ Attachment point where the joint is fixed to the parent body. If a
1751
+ vector is provided, then the attachment point is computed by adding the
1752
+ vector to the body's mass center. The default value is the parent's mass
1753
+ center.
1754
+ child_point : Point or Vector, optional
1755
+ Attachment point where the joint is fixed to the child body. If a
1756
+ vector is provided, then the attachment point is computed by adding the
1757
+ vector to the body's mass center. The default value is the child's mass
1758
+ center.
1759
+ parent_interframe : ReferenceFrame, optional
1760
+ Intermediate frame of the parent body with respect to which the joint
1761
+ transformation is formulated. If a Vector is provided then an interframe
1762
+ is created which aligns its X axis with the given vector. The default
1763
+ value is the parent's own frame.
1764
+ child_interframe : ReferenceFrame, optional
1765
+ Intermediate frame of the child body with respect to which the joint
1766
+ transformation is formulated. If a Vector is provided then an interframe
1767
+ is created which aligns its X axis with the given vector. The default
1768
+ value is the child's own frame.
1769
+ rot_type : str, optional
1770
+ The method used to generate the direction cosine matrix. Supported
1771
+ methods are:
1772
+
1773
+ - ``'Body'``: three successive rotations about new intermediate axes,
1774
+ also called "Euler and Tait-Bryan angles"
1775
+ - ``'Space'``: three successive rotations about the parent frames' unit
1776
+ vectors
1777
+
1778
+ The default method is ``'Body'``.
1779
+ amounts :
1780
+ Expressions defining the rotation angles or direction cosine matrix.
1781
+ These must match the ``rot_type``. See examples below for details. The
1782
+ input types are:
1783
+
1784
+ - ``'Body'``: 3-tuple of expressions, symbols, or functions
1785
+ - ``'Space'``: 3-tuple of expressions, symbols, or functions
1786
+
1787
+ The default amounts are the given ``coordinates``.
1788
+ rot_order : str or int, optional
1789
+ If applicable, the order of the successive of rotations. The string
1790
+ ``'123'`` and integer ``123`` are equivalent, for example. Required for
1791
+ ``'Body'`` and ``'Space'``. The default value is ``123``.
1792
+
1793
+ Attributes
1794
+ ==========
1795
+
1796
+ name : string
1797
+ The joint's name.
1798
+ parent : Body
1799
+ The joint's parent body.
1800
+ child : Body
1801
+ The joint's child body.
1802
+ coordinates : Matrix
1803
+ Matrix of the joint's generalized coordinates.
1804
+ speeds : Matrix
1805
+ Matrix of the joint's generalized speeds.
1806
+ parent_point : Point
1807
+ Attachment point where the joint is fixed to the parent body.
1808
+ child_point : Point
1809
+ Attachment point where the joint is fixed to the child body.
1810
+ parent_interframe : ReferenceFrame
1811
+ Intermediate frame of the parent body with respect to which the joint
1812
+ transformation is formulated.
1813
+ child_interframe : ReferenceFrame
1814
+ Intermediate frame of the child body with respect to which the joint
1815
+ transformation is formulated.
1816
+ kdes : Matrix
1817
+ Kinematical differential equations of the joint.
1818
+
1819
+ Examples
1820
+ =========
1821
+
1822
+ A single spherical joint is created from two bodies and has the following
1823
+ basic attributes:
1824
+
1825
+ >>> from sympy.physics.mechanics import Body, SphericalJoint
1826
+ >>> parent = Body('P')
1827
+ >>> parent
1828
+ P
1829
+ >>> child = Body('C')
1830
+ >>> child
1831
+ C
1832
+ >>> joint = SphericalJoint('PC', parent, child)
1833
+ >>> joint
1834
+ SphericalJoint: PC parent: P child: C
1835
+ >>> joint.name
1836
+ 'PC'
1837
+ >>> joint.parent
1838
+ P
1839
+ >>> joint.child
1840
+ C
1841
+ >>> joint.parent_point
1842
+ P_masscenter
1843
+ >>> joint.child_point
1844
+ C_masscenter
1845
+ >>> joint.parent_interframe
1846
+ P_frame
1847
+ >>> joint.child_interframe
1848
+ C_frame
1849
+ >>> joint.coordinates
1850
+ Matrix([
1851
+ [q0_PC(t)],
1852
+ [q1_PC(t)],
1853
+ [q2_PC(t)]])
1854
+ >>> joint.speeds
1855
+ Matrix([
1856
+ [u0_PC(t)],
1857
+ [u1_PC(t)],
1858
+ [u2_PC(t)]])
1859
+ >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame)
1860
+ Matrix([
1861
+ [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))],
1862
+ [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))],
1863
+ [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]])
1864
+ >>> child.frame.x.to_matrix(parent.frame)
1865
+ Matrix([
1866
+ [ cos(q1_PC(t))*cos(q2_PC(t))],
1867
+ [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))],
1868
+ [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]])
1869
+ >>> joint.child_point.pos_from(joint.parent_point)
1870
+ 0
1871
+
1872
+ To further demonstrate the use of the spherical joint, the kinematics of a
1873
+ spherical joint with a ZXZ rotation can be created as follows.
1874
+
1875
+ >>> from sympy import symbols
1876
+ >>> from sympy.physics.mechanics import Body, SphericalJoint
1877
+ >>> l1 = symbols('l1')
1878
+
1879
+ First create bodies to represent the fixed floor and a pendulum bob.
1880
+
1881
+ >>> floor = Body('F')
1882
+ >>> bob = Body('B')
1883
+
1884
+ The joint will connect the bob to the floor, with the joint located at a
1885
+ distance of ``l1`` from the child's center of mass and the rotation set to a
1886
+ body-fixed ZXZ rotation.
1887
+
1888
+ >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y,
1889
+ ... rot_type='body', rot_order='ZXZ')
1890
+
1891
+ Now that the joint is established, the kinematics of the connected body can
1892
+ be accessed.
1893
+
1894
+ The position of the bob's masscenter is found with:
1895
+
1896
+ >>> bob.masscenter.pos_from(floor.masscenter)
1897
+ - l1*B_frame.y
1898
+
1899
+ The angular velocities of the pendulum link can be computed with respect to
1900
+ the floor.
1901
+
1902
+ >>> bob.frame.ang_vel_in(floor.frame).to_matrix(
1903
+ ... floor.frame).simplify()
1904
+ Matrix([
1905
+ [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))],
1906
+ [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))],
1907
+ [ u0_S(t) + u2_S(t)*cos(q1_S(t))]])
1908
+
1909
+ Finally, the linear velocity of the bob's center of mass can be computed.
1910
+
1911
+ >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame)
1912
+ Matrix([
1913
+ [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))],
1914
+ [ 0],
1915
+ [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]])
1916
+
1917
+ """
1918
+ def __init__(self, name, parent, child, coordinates=None, speeds=None,
1919
+ parent_point=None, child_point=None, parent_interframe=None,
1920
+ child_interframe=None, rot_type='BODY', amounts=None,
1921
+ rot_order=123):
1922
+ self._rot_type = rot_type
1923
+ self._amounts = amounts
1924
+ self._rot_order = rot_order
1925
+ super().__init__(name, parent, child, coordinates, speeds,
1926
+ parent_point, child_point,
1927
+ parent_interframe=parent_interframe,
1928
+ child_interframe=child_interframe)
1929
+
1930
+ def __str__(self):
1931
+ return (f'SphericalJoint: {self.name} parent: {self.parent} '
1932
+ f'child: {self.child}')
1933
+
1934
+ def _generate_coordinates(self, coordinates):
1935
+ return self._fill_coordinate_list(coordinates, 3, 'q')
1936
+
1937
+ def _generate_speeds(self, speeds):
1938
+ return self._fill_coordinate_list(speeds, len(self.coordinates), 'u')
1939
+
1940
+ def _orient_frames(self):
1941
+ supported_rot_types = ('BODY', 'SPACE')
1942
+ if self._rot_type.upper() not in supported_rot_types:
1943
+ raise NotImplementedError(
1944
+ f'Rotation type "{self._rot_type}" is not implemented. '
1945
+ f'Implemented rotation types are: {supported_rot_types}')
1946
+ amounts = self.coordinates if self._amounts is None else self._amounts
1947
+ self.child_interframe.orient(self.parent_interframe, self._rot_type,
1948
+ amounts, self._rot_order)
1949
+
1950
+ def _set_angular_velocity(self):
1951
+ t = dynamicsymbols._t
1952
+ vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace(
1953
+ {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)}
1954
+ )
1955
+ self.child_interframe.set_ang_vel(self.parent_interframe, vel)
1956
+
1957
+ def _set_linear_velocity(self):
1958
+ self.child_point.set_pos(self.parent_point, 0)
1959
+ self.parent_point.set_vel(self.parent.frame, 0)
1960
+ self.child_point.set_vel(self.child.frame, 0)
1961
+ self.child.masscenter.v2pt_theory(self.parent_point, self.parent.frame,
1962
+ self.child.frame)
1963
+
1964
+
1965
+ class WeldJoint(Joint):
1966
+ """Weld Joint.
1967
+
1968
+ .. image:: WeldJoint.svg
1969
+ :align: center
1970
+ :width: 500
1971
+
1972
+ Explanation
1973
+ ===========
1974
+
1975
+ A weld joint is defined such that there is no relative motion between the
1976
+ child and parent bodies. The direction cosine matrix between the attachment
1977
+ frame (``parent_interframe`` and ``child_interframe``) is the identity
1978
+ matrix and the attachment points (``parent_point`` and ``child_point``) are
1979
+ coincident. The page on the joints framework gives a more detailed
1980
+ explanation of the intermediate frames.
1981
+
1982
+ Parameters
1983
+ ==========
1984
+
1985
+ name : string
1986
+ A unique name for the joint.
1987
+ parent : Body
1988
+ The parent body of joint.
1989
+ child : Body
1990
+ The child body of joint.
1991
+ parent_point : Point or Vector, optional
1992
+ Attachment point where the joint is fixed to the parent body. If a
1993
+ vector is provided, then the attachment point is computed by adding the
1994
+ vector to the body's mass center. The default value is the parent's mass
1995
+ center.
1996
+ child_point : Point or Vector, optional
1997
+ Attachment point where the joint is fixed to the child body. If a
1998
+ vector is provided, then the attachment point is computed by adding the
1999
+ vector to the body's mass center. The default value is the child's mass
2000
+ center.
2001
+ parent_interframe : ReferenceFrame, optional
2002
+ Intermediate frame of the parent body with respect to which the joint
2003
+ transformation is formulated. If a Vector is provided then an interframe
2004
+ is created which aligns its X axis with the given vector. The default
2005
+ value is the parent's own frame.
2006
+ child_interframe : ReferenceFrame, optional
2007
+ Intermediate frame of the child body with respect to which the joint
2008
+ transformation is formulated. If a Vector is provided then an interframe
2009
+ is created which aligns its X axis with the given vector. The default
2010
+ value is the child's own frame.
2011
+
2012
+ Attributes
2013
+ ==========
2014
+
2015
+ name : string
2016
+ The joint's name.
2017
+ parent : Body
2018
+ The joint's parent body.
2019
+ child : Body
2020
+ The joint's child body.
2021
+ coordinates : Matrix
2022
+ Matrix of the joint's generalized coordinates. The default value is
2023
+ ``dynamicsymbols(f'q_{joint.name}')``.
2024
+ speeds : Matrix
2025
+ Matrix of the joint's generalized speeds. The default value is
2026
+ ``dynamicsymbols(f'u_{joint.name}')``.
2027
+ parent_point : Point
2028
+ Attachment point where the joint is fixed to the parent body.
2029
+ child_point : Point
2030
+ Attachment point where the joint is fixed to the child body.
2031
+ parent_interframe : ReferenceFrame
2032
+ Intermediate frame of the parent body with respect to which the joint
2033
+ transformation is formulated.
2034
+ child_interframe : ReferenceFrame
2035
+ Intermediate frame of the child body with respect to which the joint
2036
+ transformation is formulated.
2037
+ kdes : Matrix
2038
+ Kinematical differential equations of the joint.
2039
+
2040
+ Examples
2041
+ =========
2042
+
2043
+ A single weld joint is created from two bodies and has the following basic
2044
+ attributes:
2045
+
2046
+ >>> from sympy.physics.mechanics import Body, WeldJoint
2047
+ >>> parent = Body('P')
2048
+ >>> parent
2049
+ P
2050
+ >>> child = Body('C')
2051
+ >>> child
2052
+ C
2053
+ >>> joint = WeldJoint('PC', parent, child)
2054
+ >>> joint
2055
+ WeldJoint: PC parent: P child: C
2056
+ >>> joint.name
2057
+ 'PC'
2058
+ >>> joint.parent
2059
+ P
2060
+ >>> joint.child
2061
+ C
2062
+ >>> joint.parent_point
2063
+ P_masscenter
2064
+ >>> joint.child_point
2065
+ C_masscenter
2066
+ >>> joint.coordinates
2067
+ Matrix(0, 0, [])
2068
+ >>> joint.speeds
2069
+ Matrix(0, 0, [])
2070
+ >>> joint.child.frame.ang_vel_in(joint.parent.frame)
2071
+ 0
2072
+ >>> joint.child.frame.dcm(joint.parent.frame)
2073
+ Matrix([
2074
+ [1, 0, 0],
2075
+ [0, 1, 0],
2076
+ [0, 0, 1]])
2077
+ >>> joint.child_point.pos_from(joint.parent_point)
2078
+ 0
2079
+
2080
+ To further demonstrate the use of the weld joint, two relatively-fixed
2081
+ bodies rotated by a quarter turn about the Y axis can be created as follows:
2082
+
2083
+ >>> from sympy import symbols, pi
2084
+ >>> from sympy.physics.mechanics import ReferenceFrame, Body, WeldJoint
2085
+ >>> l1, l2 = symbols('l1 l2')
2086
+
2087
+ First create the bodies to represent the parent and rotated child body.
2088
+
2089
+ >>> parent = Body('P')
2090
+ >>> child = Body('C')
2091
+
2092
+ Next the intermediate frame specifying the fixed rotation with respect to
2093
+ the parent can be created.
2094
+
2095
+ >>> rotated_frame = ReferenceFrame('Pr')
2096
+ >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2)
2097
+
2098
+ The weld between the parent body and child body is located at a distance
2099
+ ``l1`` from the parent's center of mass in the X direction and ``l2`` from
2100
+ the child's center of mass in the child's negative X direction.
2101
+
2102
+ >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x,
2103
+ ... child_point=-l2 * child.x,
2104
+ ... parent_interframe=rotated_frame)
2105
+
2106
+ Now that the joint has been established, the kinematics of the bodies can be
2107
+ accessed. The direction cosine matrix of the child body with respect to the
2108
+ parent can be found:
2109
+
2110
+ >>> child.dcm(parent)
2111
+ Matrix([
2112
+ [0, 0, -1],
2113
+ [0, 1, 0],
2114
+ [1, 0, 0]])
2115
+
2116
+ As can also been seen from the direction cosine matrix, the parent X axis is
2117
+ aligned with the child's Z axis:
2118
+ >>> parent.x == child.z
2119
+ True
2120
+
2121
+ The position of the child's center of mass with respect to the parent's
2122
+ center of mass can be found with:
2123
+
2124
+ >>> child.masscenter.pos_from(parent.masscenter)
2125
+ l1*P_frame.x + l2*C_frame.x
2126
+
2127
+ The angular velocity of the child with respect to the parent is 0 as one
2128
+ would expect.
2129
+
2130
+ >>> child.ang_vel_in(parent)
2131
+ 0
2132
+
2133
+ """
2134
+
2135
+ def __init__(self, name, parent, child, parent_point=None, child_point=None,
2136
+ parent_interframe=None, child_interframe=None):
2137
+ super().__init__(name, parent, child, [], [], parent_point,
2138
+ child_point, parent_interframe=parent_interframe,
2139
+ child_interframe=child_interframe)
2140
+ self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770
2141
+
2142
+ def __str__(self):
2143
+ return (f'WeldJoint: {self.name} parent: {self.parent} '
2144
+ f'child: {self.child}')
2145
+
2146
+ def _generate_coordinates(self, coordinate):
2147
+ return Matrix()
2148
+
2149
+ def _generate_speeds(self, speed):
2150
+ return Matrix()
2151
+
2152
+ def _orient_frames(self):
2153
+ self.child_interframe.orient_axis(self.parent_interframe,
2154
+ self.parent_interframe.x, 0)
2155
+
2156
+ def _set_angular_velocity(self):
2157
+ self.child_interframe.set_ang_vel(self.parent_interframe, 0)
2158
+
2159
+ def _set_linear_velocity(self):
2160
+ self.child_point.set_pos(self.parent_point, 0)
2161
+ self.parent_point.set_vel(self.parent.frame, 0)
2162
+ self.child_point.set_vel(self.child.frame, 0)
2163
+ self.child.masscenter.set_vel(self.parent.frame, 0)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
2
+ RigidBody, Particle)
3
+ from sympy.physics.mechanics.method import _Methods
4
+ from sympy.core.backend import Matrix
5
+
6
+ __all__ = ['JointsMethod']
7
+
8
+
9
+ class JointsMethod(_Methods):
10
+ """Method for formulating the equations of motion using a set of interconnected bodies with joints.
11
+
12
+ Parameters
13
+ ==========
14
+
15
+ newtonion : Body or ReferenceFrame
16
+ The newtonion(inertial) frame.
17
+ *joints : Joint
18
+ The joints in the system
19
+
20
+ Attributes
21
+ ==========
22
+
23
+ q, u : iterable
24
+ Iterable of the generalized coordinates and speeds
25
+ bodies : iterable
26
+ Iterable of Body objects in the system.
27
+ loads : iterable
28
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
29
+ describing the forces on the system.
30
+ mass_matrix : Matrix, shape(n, n)
31
+ The system's mass matrix
32
+ forcing : Matrix, shape(n, 1)
33
+ The system's forcing vector
34
+ mass_matrix_full : Matrix, shape(2*n, 2*n)
35
+ The "mass matrix" for the u's and q's
36
+ forcing_full : Matrix, shape(2*n, 1)
37
+ The "forcing vector" for the u's and q's
38
+ method : KanesMethod or Lagrange's method
39
+ Method's object.
40
+ kdes : iterable
41
+ Iterable of kde in they system.
42
+
43
+ Examples
44
+ ========
45
+
46
+ This is a simple example for a one degree of freedom translational
47
+ spring-mass-damper.
48
+
49
+ >>> from sympy import symbols
50
+ >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
51
+ >>> from sympy.physics.vector import dynamicsymbols
52
+ >>> c, k = symbols('c k')
53
+ >>> x, v = dynamicsymbols('x v')
54
+ >>> wall = Body('W')
55
+ >>> body = Body('B')
56
+ >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
57
+ >>> wall.apply_force(c*v*wall.x, reaction_body=body)
58
+ >>> wall.apply_force(k*x*wall.x, reaction_body=body)
59
+ >>> method = JointsMethod(wall, J)
60
+ >>> method.form_eoms()
61
+ Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
62
+ >>> M = method.mass_matrix_full
63
+ >>> F = method.forcing_full
64
+ >>> rhs = M.LUsolve(F)
65
+ >>> rhs
66
+ Matrix([
67
+ [ v(t)],
68
+ [(-c*v(t) - k*x(t))/B_mass]])
69
+
70
+ Notes
71
+ =====
72
+
73
+ ``JointsMethod`` currently only works with systems that do not have any
74
+ configuration or motion constraints.
75
+
76
+ """
77
+
78
+ def __init__(self, newtonion, *joints):
79
+ if isinstance(newtonion, Body):
80
+ self.frame = newtonion.frame
81
+ else:
82
+ self.frame = newtonion
83
+
84
+ self._joints = joints
85
+ self._bodies = self._generate_bodylist()
86
+ self._loads = self._generate_loadlist()
87
+ self._q = self._generate_q()
88
+ self._u = self._generate_u()
89
+ self._kdes = self._generate_kdes()
90
+
91
+ self._method = None
92
+
93
+ @property
94
+ def bodies(self):
95
+ """List of bodies in they system."""
96
+ return self._bodies
97
+
98
+ @property
99
+ def loads(self):
100
+ """List of loads on the system."""
101
+ return self._loads
102
+
103
+ @property
104
+ def q(self):
105
+ """List of the generalized coordinates."""
106
+ return self._q
107
+
108
+ @property
109
+ def u(self):
110
+ """List of the generalized speeds."""
111
+ return self._u
112
+
113
+ @property
114
+ def kdes(self):
115
+ """List of the generalized coordinates."""
116
+ return self._kdes
117
+
118
+ @property
119
+ def forcing_full(self):
120
+ """The "forcing vector" for the u's and q's."""
121
+ return self.method.forcing_full
122
+
123
+ @property
124
+ def mass_matrix_full(self):
125
+ """The "mass matrix" for the u's and q's."""
126
+ return self.method.mass_matrix_full
127
+
128
+ @property
129
+ def mass_matrix(self):
130
+ """The system's mass matrix."""
131
+ return self.method.mass_matrix
132
+
133
+ @property
134
+ def forcing(self):
135
+ """The system's forcing vector."""
136
+ return self.method.forcing
137
+
138
+ @property
139
+ def method(self):
140
+ """Object of method used to form equations of systems."""
141
+ return self._method
142
+
143
+ def _generate_bodylist(self):
144
+ bodies = []
145
+ for joint in self._joints:
146
+ if joint.child not in bodies:
147
+ bodies.append(joint.child)
148
+ if joint.parent not in bodies:
149
+ bodies.append(joint.parent)
150
+ return bodies
151
+
152
+ def _generate_loadlist(self):
153
+ load_list = []
154
+ for body in self.bodies:
155
+ load_list.extend(body.loads)
156
+ return load_list
157
+
158
+ def _generate_q(self):
159
+ q_ind = []
160
+ for joint in self._joints:
161
+ for coordinate in joint.coordinates:
162
+ if coordinate in q_ind:
163
+ raise ValueError('Coordinates of joints should be unique.')
164
+ q_ind.append(coordinate)
165
+ return Matrix(q_ind)
166
+
167
+ def _generate_u(self):
168
+ u_ind = []
169
+ for joint in self._joints:
170
+ for speed in joint.speeds:
171
+ if speed in u_ind:
172
+ raise ValueError('Speeds of joints should be unique.')
173
+ u_ind.append(speed)
174
+ return Matrix(u_ind)
175
+
176
+ def _generate_kdes(self):
177
+ kd_ind = Matrix(1, 0, []).T
178
+ for joint in self._joints:
179
+ kd_ind = kd_ind.col_join(joint.kdes)
180
+ return kd_ind
181
+
182
+ def _convert_bodies(self):
183
+ # Convert `Body` to `Particle` and `RigidBody`
184
+ bodylist = []
185
+ for body in self.bodies:
186
+ if body.is_rigidbody:
187
+ rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
188
+ (body.central_inertia, body.masscenter))
189
+ rb.potential_energy = body.potential_energy
190
+ bodylist.append(rb)
191
+ else:
192
+ part = Particle(body.name, body.masscenter, body.mass)
193
+ part.potential_energy = body.potential_energy
194
+ bodylist.append(part)
195
+ return bodylist
196
+
197
+ def form_eoms(self, method=KanesMethod):
198
+ """Method to form system's equation of motions.
199
+
200
+ Parameters
201
+ ==========
202
+
203
+ method : Class
204
+ Class name of method.
205
+
206
+ Returns
207
+ ========
208
+
209
+ Matrix
210
+ Vector of equations of motions.
211
+
212
+ Examples
213
+ ========
214
+
215
+ This is a simple example for a one degree of freedom translational
216
+ spring-mass-damper.
217
+
218
+ >>> from sympy import S, symbols
219
+ >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
220
+ >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
221
+ >>> q = dynamicsymbols('q')
222
+ >>> qd = dynamicsymbols('q', 1)
223
+ >>> m, k, b = symbols('m k b')
224
+ >>> wall = Body('W')
225
+ >>> part = Body('P', mass=m)
226
+ >>> part.potential_energy = k * q**2 / S(2)
227
+ >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
228
+ >>> wall.apply_force(b * qd * wall.x, reaction_body=part)
229
+ >>> method = JointsMethod(wall, J)
230
+ >>> method.form_eoms(LagrangesMethod)
231
+ Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
232
+
233
+ We can also solve for the states using the 'rhs' method.
234
+
235
+ >>> method.rhs()
236
+ Matrix([
237
+ [ Derivative(q(t), t)],
238
+ [(-b*Derivative(q(t), t) - k*q(t))/m]])
239
+
240
+ """
241
+
242
+ bodylist = self._convert_bodies()
243
+ if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
244
+ L = Lagrangian(self.frame, *bodylist)
245
+ self._method = method(L, self.q, self.loads, bodylist, self.frame)
246
+ else: #KanesMethod or similar
247
+ self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
248
+ forcelist=self.loads, bodies=bodylist)
249
+ soln = self.method._form_eoms()
250
+ return soln
251
+
252
+ def rhs(self, inv_method=None):
253
+ """Returns equations that can be solved numerically.
254
+
255
+ Parameters
256
+ ==========
257
+
258
+ inv_method : str
259
+ The specific sympy inverse matrix calculation method to use. For a
260
+ list of valid methods, see
261
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
262
+
263
+ Returns
264
+ ========
265
+
266
+ Matrix
267
+ Numerically solvable equations.
268
+
269
+ See Also
270
+ ========
271
+
272
+ sympy.physics.mechanics.kane.KanesMethod.rhs:
273
+ KanesMethod's rhs function.
274
+ sympy.physics.mechanics.lagrange.LagrangesMethod.rhs:
275
+ LagrangesMethod's rhs function.
276
+
277
+ """
278
+
279
+ return self.method.rhs(inv_method=inv_method)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py ADDED
@@ -0,0 +1,741 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import zeros, Matrix, diff, eye
2
+ from sympy.core.sorting import default_sort_key
3
+ from sympy.physics.vector import (ReferenceFrame, dynamicsymbols,
4
+ partial_velocity)
5
+ from sympy.physics.mechanics.method import _Methods
6
+ from sympy.physics.mechanics.particle import Particle
7
+ from sympy.physics.mechanics.rigidbody import RigidBody
8
+ from sympy.physics.mechanics.functions import (
9
+ msubs, find_dynamicsymbols, _f_list_parser, _validate_coordinates)
10
+ from sympy.physics.mechanics.linearize import Linearizer
11
+ from sympy.utilities.iterables import iterable
12
+
13
+ __all__ = ['KanesMethod']
14
+
15
+
16
+ class KanesMethod(_Methods):
17
+ r"""Kane's method object.
18
+
19
+ Explanation
20
+ ===========
21
+
22
+ This object is used to do the "book-keeping" as you go through and form
23
+ equations of motion in the way Kane presents in:
24
+ Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
25
+
26
+ The attributes are for equations in the form [M] udot = forcing.
27
+
28
+ Attributes
29
+ ==========
30
+
31
+ q, u : Matrix
32
+ Matrices of the generalized coordinates and speeds
33
+ bodies : iterable
34
+ Iterable of Point and RigidBody objects in the system.
35
+ loads : iterable
36
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
37
+ describing the forces on the system.
38
+ auxiliary_eqs : Matrix
39
+ If applicable, the set of auxiliary Kane's
40
+ equations used to solve for non-contributing
41
+ forces.
42
+ mass_matrix : Matrix
43
+ The system's dynamics mass matrix: [k_d; k_dnh]
44
+ forcing : Matrix
45
+ The system's dynamics forcing vector: -[f_d; f_dnh]
46
+ mass_matrix_kin : Matrix
47
+ The "mass matrix" for kinematic differential equations: k_kqdot
48
+ forcing_kin : Matrix
49
+ The forcing vector for kinematic differential equations: -(k_ku*u + f_k)
50
+ mass_matrix_full : Matrix
51
+ The "mass matrix" for the u's and q's with dynamics and kinematics
52
+ forcing_full : Matrix
53
+ The "forcing vector" for the u's and q's with dynamics and kinematics
54
+ explicit_kinematics : bool
55
+ Boolean whether the mass matrices and forcing vectors should use the
56
+ explicit form (default) or implicit form for kinematics.
57
+ See the notes for more details.
58
+
59
+ Notes
60
+ =====
61
+
62
+ The mass matrices and forcing vectors related to kinematic equations
63
+ are given in the explicit form by default. In other words, the kinematic
64
+ mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$.
65
+ In order to get the implicit form of those matrices/vectors, you can set the
66
+ ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$ is not
67
+ necessarily an identity matrix. This can provide more compact equations for
68
+ non-simple kinematics (see #22626).
69
+
70
+ Examples
71
+ ========
72
+
73
+ This is a simple example for a one degree of freedom translational
74
+ spring-mass-damper.
75
+
76
+ In this example, we first need to do the kinematics.
77
+ This involves creating generalized speeds and coordinates and their
78
+ derivatives.
79
+ Then we create a point and set its velocity in a frame.
80
+
81
+ >>> from sympy import symbols
82
+ >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame
83
+ >>> from sympy.physics.mechanics import Point, Particle, KanesMethod
84
+ >>> q, u = dynamicsymbols('q u')
85
+ >>> qd, ud = dynamicsymbols('q u', 1)
86
+ >>> m, c, k = symbols('m c k')
87
+ >>> N = ReferenceFrame('N')
88
+ >>> P = Point('P')
89
+ >>> P.set_vel(N, u * N.x)
90
+
91
+ Next we need to arrange/store information in the way that KanesMethod
92
+ requires. The kinematic differential equations need to be stored in a
93
+ dict. A list of forces/torques must be constructed, where each entry in
94
+ the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the
95
+ Vectors represent the Force or Torque.
96
+ Next a particle needs to be created, and it needs to have a point and mass
97
+ assigned to it.
98
+ Finally, a list of all bodies and particles needs to be created.
99
+
100
+ >>> kd = [qd - u]
101
+ >>> FL = [(P, (-k * q - c * u) * N.x)]
102
+ >>> pa = Particle('pa', P, m)
103
+ >>> BL = [pa]
104
+
105
+ Finally we can generate the equations of motion.
106
+ First we create the KanesMethod object and supply an inertial frame,
107
+ coordinates, generalized speeds, and the kinematic differential equations.
108
+ Additional quantities such as configuration and motion constraints,
109
+ dependent coordinates and speeds, and auxiliary speeds are also supplied
110
+ here (see the online documentation).
111
+ Next we form FR* and FR to complete: Fr + Fr* = 0.
112
+ We have the equations of motion at this point.
113
+ It makes sense to rearrange them though, so we calculate the mass matrix and
114
+ the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is
115
+ the mass matrix, udot is a vector of the time derivatives of the
116
+ generalized speeds, and forcing is a vector representing "forcing" terms.
117
+
118
+ >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd)
119
+ >>> (fr, frstar) = KM.kanes_equations(BL, FL)
120
+ >>> MM = KM.mass_matrix
121
+ >>> forcing = KM.forcing
122
+ >>> rhs = MM.inv() * forcing
123
+ >>> rhs
124
+ Matrix([[(-c*u(t) - k*q(t))/m]])
125
+ >>> KM.linearize(A_and_B=True)[0]
126
+ Matrix([
127
+ [ 0, 1],
128
+ [-k/m, -c/m]])
129
+
130
+ Please look at the documentation pages for more information on how to
131
+ perform linearization and how to deal with dependent coordinates & speeds,
132
+ and how do deal with bringing non-contributing forces into evidence.
133
+
134
+ """
135
+
136
+ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None,
137
+ configuration_constraints=None, u_dependent=None,
138
+ velocity_constraints=None, acceleration_constraints=None,
139
+ u_auxiliary=None, bodies=None, forcelist=None, explicit_kinematics=True):
140
+
141
+ """Please read the online documentation. """
142
+ if not q_ind:
143
+ q_ind = [dynamicsymbols('dummy_q')]
144
+ kd_eqs = [dynamicsymbols('dummy_kd')]
145
+
146
+ if not isinstance(frame, ReferenceFrame):
147
+ raise TypeError('An inertial ReferenceFrame must be supplied')
148
+ self._inertial = frame
149
+
150
+ self._fr = None
151
+ self._frstar = None
152
+
153
+ self._forcelist = forcelist
154
+ self._bodylist = bodies
155
+
156
+ self.explicit_kinematics = explicit_kinematics
157
+
158
+ self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent,
159
+ u_auxiliary)
160
+ _validate_coordinates(self.q, self.u)
161
+ self._initialize_kindiffeq_matrices(kd_eqs)
162
+ self._initialize_constraint_matrices(configuration_constraints,
163
+ velocity_constraints, acceleration_constraints)
164
+
165
+ def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
166
+ """Initialize the coordinate and speed vectors."""
167
+
168
+ none_handler = lambda x: Matrix(x) if x else Matrix()
169
+
170
+ # Initialize generalized coordinates
171
+ q_dep = none_handler(q_dep)
172
+ if not iterable(q_ind):
173
+ raise TypeError('Generalized coordinates must be an iterable.')
174
+ if not iterable(q_dep):
175
+ raise TypeError('Dependent coordinates must be an iterable.')
176
+ q_ind = Matrix(q_ind)
177
+ self._qdep = q_dep
178
+ self._q = Matrix([q_ind, q_dep])
179
+ self._qdot = self.q.diff(dynamicsymbols._t)
180
+
181
+ # Initialize generalized speeds
182
+ u_dep = none_handler(u_dep)
183
+ if not iterable(u_ind):
184
+ raise TypeError('Generalized speeds must be an iterable.')
185
+ if not iterable(u_dep):
186
+ raise TypeError('Dependent speeds must be an iterable.')
187
+ u_ind = Matrix(u_ind)
188
+ self._udep = u_dep
189
+ self._u = Matrix([u_ind, u_dep])
190
+ self._udot = self.u.diff(dynamicsymbols._t)
191
+ self._uaux = none_handler(u_aux)
192
+
193
+ def _initialize_constraint_matrices(self, config, vel, acc):
194
+ """Initializes constraint matrices."""
195
+
196
+ # Define vector dimensions
197
+ o = len(self.u)
198
+ m = len(self._udep)
199
+ p = o - m
200
+ none_handler = lambda x: Matrix(x) if x else Matrix()
201
+
202
+ # Initialize configuration constraints
203
+ config = none_handler(config)
204
+ if len(self._qdep) != len(config):
205
+ raise ValueError('There must be an equal number of dependent '
206
+ 'coordinates and configuration constraints.')
207
+ self._f_h = none_handler(config)
208
+
209
+ # Initialize velocity and acceleration constraints
210
+ vel = none_handler(vel)
211
+ acc = none_handler(acc)
212
+ if len(vel) != m:
213
+ raise ValueError('There must be an equal number of dependent '
214
+ 'speeds and velocity constraints.')
215
+ if acc and (len(acc) != m):
216
+ raise ValueError('There must be an equal number of dependent '
217
+ 'speeds and acceleration constraints.')
218
+ if vel:
219
+ u_zero = {i: 0 for i in self.u}
220
+ udot_zero = {i: 0 for i in self._udot}
221
+
222
+ # When calling kanes_equations, another class instance will be
223
+ # created if auxiliary u's are present. In this case, the
224
+ # computation of kinetic differential equation matrices will be
225
+ # skipped as this was computed during the original KanesMethod
226
+ # object, and the qd_u_map will not be available.
227
+ if self._qdot_u_map is not None:
228
+ vel = msubs(vel, self._qdot_u_map)
229
+
230
+ self._f_nh = msubs(vel, u_zero)
231
+ self._k_nh = (vel - self._f_nh).jacobian(self.u)
232
+ # If no acceleration constraints given, calculate them.
233
+ if not acc:
234
+ _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u +
235
+ self._f_nh.diff(dynamicsymbols._t))
236
+ if self._qdot_u_map is not None:
237
+ _f_dnh = msubs(_f_dnh, self._qdot_u_map)
238
+ self._f_dnh = _f_dnh
239
+ self._k_dnh = self._k_nh
240
+ else:
241
+ if self._qdot_u_map is not None:
242
+ acc = msubs(acc, self._qdot_u_map)
243
+ self._f_dnh = msubs(acc, udot_zero)
244
+ self._k_dnh = (acc - self._f_dnh).jacobian(self._udot)
245
+
246
+ # Form of non-holonomic constraints is B*u + C = 0.
247
+ # We partition B into independent and dependent columns:
248
+ # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds
249
+ # to independent speeds as: udep = Ars*uind, neglecting the C term.
250
+ B_ind = self._k_nh[:, :p]
251
+ B_dep = self._k_nh[:, p:o]
252
+ self._Ars = -B_dep.LUsolve(B_ind)
253
+ else:
254
+ self._f_nh = Matrix()
255
+ self._k_nh = Matrix()
256
+ self._f_dnh = Matrix()
257
+ self._k_dnh = Matrix()
258
+ self._Ars = Matrix()
259
+
260
+ def _initialize_kindiffeq_matrices(self, kdeqs):
261
+ """Initialize the kinematic differential equation matrices.
262
+
263
+ Parameters
264
+ ==========
265
+ kdeqs : sequence of sympy expressions
266
+ Kinematic differential equations in the form of f(u,q',q,t) where
267
+ f() = 0. The equations have to be linear in the generalized
268
+ coordinates and generalized speeds.
269
+
270
+ """
271
+
272
+ if kdeqs:
273
+ if len(self.q) != len(kdeqs):
274
+ raise ValueError('There must be an equal number of kinematic '
275
+ 'differential equations and coordinates.')
276
+
277
+ u = self.u
278
+ qdot = self._qdot
279
+
280
+ kdeqs = Matrix(kdeqs)
281
+
282
+ u_zero = {ui: 0 for ui in u}
283
+ uaux_zero = {uai: 0 for uai in self._uaux}
284
+ qdot_zero = {qdi: 0 for qdi in qdot}
285
+
286
+ # Extract the linear coefficient matrices as per the following
287
+ # equation:
288
+ #
289
+ # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0
290
+ #
291
+ k_ku = kdeqs.jacobian(u)
292
+ k_kqdot = kdeqs.jacobian(qdot)
293
+ f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero)
294
+
295
+ # The kinematic differential equations should be linear in both q'
296
+ # and u, so check for u and q' in the components.
297
+ dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k))
298
+ nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms]
299
+ if nonlin_vars:
300
+ msg = ('The provided kinematic differential equations are '
301
+ 'nonlinear in {}. They must be linear in the '
302
+ 'generalized speeds and derivatives of the generalized '
303
+ 'coordinates.')
304
+ raise ValueError(msg.format(nonlin_vars))
305
+
306
+ self._f_k_implicit = f_k.xreplace(uaux_zero)
307
+ self._k_ku_implicit = k_ku.xreplace(uaux_zero)
308
+ self._k_kqdot_implicit = k_kqdot
309
+
310
+ # Solve for q'(t) such that the coefficient matrices are now in
311
+ # this form:
312
+ #
313
+ # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0
314
+ #
315
+ # NOTE : Solving the kinematic differential equations here is not
316
+ # necessary and prevents the equations from being provided in fully
317
+ # implicit form.
318
+ f_k_explicit = k_kqdot.LUsolve(f_k)
319
+ k_ku_explicit = k_kqdot.LUsolve(k_ku)
320
+ self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit)))
321
+
322
+ self._f_k = f_k_explicit.xreplace(uaux_zero)
323
+ self._k_ku = k_ku_explicit.xreplace(uaux_zero)
324
+ self._k_kqdot = eye(len(qdot))
325
+
326
+ else:
327
+ self._qdot_u_map = None
328
+ self._f_k_implicit = self._f_k = Matrix()
329
+ self._k_ku_implicit = self._k_ku = Matrix()
330
+ self._k_kqdot_implicit = self._k_kqdot = Matrix()
331
+
332
+ def _form_fr(self, fl):
333
+ """Form the generalized active force."""
334
+ if fl is not None and (len(fl) == 0 or not iterable(fl)):
335
+ raise ValueError('Force pairs must be supplied in an '
336
+ 'non-empty iterable or None.')
337
+
338
+ N = self._inertial
339
+ # pull out relevant velocities for constructing partial velocities
340
+ vel_list, f_list = _f_list_parser(fl, N)
341
+ vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
342
+ f_list = [msubs(i, self._qdot_u_map) for i in f_list]
343
+
344
+ # Fill Fr with dot product of partial velocities and forces
345
+ o = len(self.u)
346
+ b = len(f_list)
347
+ FR = zeros(o, 1)
348
+ partials = partial_velocity(vel_list, self.u, N)
349
+ for i in range(o):
350
+ FR[i] = sum(partials[j][i] & f_list[j] for j in range(b))
351
+
352
+ # In case there are dependent speeds
353
+ if self._udep:
354
+ p = o - len(self._udep)
355
+ FRtilde = FR[:p, 0]
356
+ FRold = FR[p:o, 0]
357
+ FRtilde += self._Ars.T * FRold
358
+ FR = FRtilde
359
+
360
+ self._forcelist = fl
361
+ self._fr = FR
362
+ return FR
363
+
364
+ def _form_frstar(self, bl):
365
+ """Form the generalized inertia force."""
366
+
367
+ if not iterable(bl):
368
+ raise TypeError('Bodies must be supplied in an iterable.')
369
+
370
+ t = dynamicsymbols._t
371
+ N = self._inertial
372
+ # Dicts setting things to zero
373
+ udot_zero = {i: 0 for i in self._udot}
374
+ uaux_zero = {i: 0 for i in self._uaux}
375
+ uauxdot = [diff(i, t) for i in self._uaux]
376
+ uauxdot_zero = {i: 0 for i in uauxdot}
377
+ # Dictionary of q' and q'' to u and u'
378
+ q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in
379
+ self._qdot_u_map.items()}
380
+ q_ddot_u_map.update(self._qdot_u_map)
381
+
382
+ # Fill up the list of partials: format is a list with num elements
383
+ # equal to number of entries in body list. Each of these elements is a
384
+ # list - either of length 1 for the translational components of
385
+ # particles or of length 2 for the translational and rotational
386
+ # components of rigid bodies. The inner most list is the list of
387
+ # partial velocities.
388
+ def get_partial_velocity(body):
389
+ if isinstance(body, RigidBody):
390
+ vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)]
391
+ elif isinstance(body, Particle):
392
+ vlist = [body.point.vel(N),]
393
+ else:
394
+ raise TypeError('The body list may only contain either '
395
+ 'RigidBody or Particle as list elements.')
396
+ v = [msubs(vel, self._qdot_u_map) for vel in vlist]
397
+ return partial_velocity(v, self.u, N)
398
+ partials = [get_partial_velocity(body) for body in bl]
399
+
400
+ # Compute fr_star in two components:
401
+ # fr_star = -(MM*u' + nonMM)
402
+ o = len(self.u)
403
+ MM = zeros(o, o)
404
+ nonMM = zeros(o, 1)
405
+ zero_uaux = lambda expr: msubs(expr, uaux_zero)
406
+ zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero)
407
+ for i, body in enumerate(bl):
408
+ if isinstance(body, RigidBody):
409
+ M = zero_uaux(body.mass)
410
+ I = zero_uaux(body.central_inertia)
411
+ vel = zero_uaux(body.masscenter.vel(N))
412
+ omega = zero_uaux(body.frame.ang_vel_in(N))
413
+ acc = zero_udot_uaux(body.masscenter.acc(N))
414
+ inertial_force = (M.diff(t) * vel + M * acc)
415
+ inertial_torque = zero_uaux((I.dt(body.frame) & omega) +
416
+ msubs(I & body.frame.ang_acc_in(N), udot_zero) +
417
+ (omega ^ (I & omega)))
418
+ for j in range(o):
419
+ tmp_vel = zero_uaux(partials[i][0][j])
420
+ tmp_ang = zero_uaux(I & partials[i][1][j])
421
+ for k in range(o):
422
+ # translational
423
+ MM[j, k] += M * (tmp_vel & partials[i][0][k])
424
+ # rotational
425
+ MM[j, k] += (tmp_ang & partials[i][1][k])
426
+ nonMM[j] += inertial_force & partials[i][0][j]
427
+ nonMM[j] += inertial_torque & partials[i][1][j]
428
+ else:
429
+ M = zero_uaux(body.mass)
430
+ vel = zero_uaux(body.point.vel(N))
431
+ acc = zero_udot_uaux(body.point.acc(N))
432
+ inertial_force = (M.diff(t) * vel + M * acc)
433
+ for j in range(o):
434
+ temp = zero_uaux(partials[i][0][j])
435
+ for k in range(o):
436
+ MM[j, k] += M * (temp & partials[i][0][k])
437
+ nonMM[j] += inertial_force & partials[i][0][j]
438
+ # Compose fr_star out of MM and nonMM
439
+ MM = zero_uaux(msubs(MM, q_ddot_u_map))
440
+ nonMM = msubs(msubs(nonMM, q_ddot_u_map),
441
+ udot_zero, uauxdot_zero, uaux_zero)
442
+ fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM)
443
+
444
+ # If there are dependent speeds, we need to find fr_star_tilde
445
+ if self._udep:
446
+ p = o - len(self._udep)
447
+ fr_star_ind = fr_star[:p, 0]
448
+ fr_star_dep = fr_star[p:o, 0]
449
+ fr_star = fr_star_ind + (self._Ars.T * fr_star_dep)
450
+ # Apply the same to MM
451
+ MMi = MM[:p, :]
452
+ MMd = MM[p:o, :]
453
+ MM = MMi + (self._Ars.T * MMd)
454
+
455
+ self._bodylist = bl
456
+ self._frstar = fr_star
457
+ self._k_d = MM
458
+ self._f_d = -msubs(self._fr + self._frstar, udot_zero)
459
+ return fr_star
460
+
461
+ def to_linearizer(self):
462
+ """Returns an instance of the Linearizer class, initiated from the
463
+ data in the KanesMethod class. This may be more desirable than using
464
+ the linearize class method, as the Linearizer object will allow more
465
+ efficient recalculation (i.e. about varying operating points)."""
466
+
467
+ if (self._fr is None) or (self._frstar is None):
468
+ raise ValueError('Need to compute Fr, Fr* first.')
469
+
470
+ # Get required equation components. The Kane's method class breaks
471
+ # these into pieces. Need to reassemble
472
+ f_c = self._f_h
473
+ if self._f_nh and self._k_nh:
474
+ f_v = self._f_nh + self._k_nh*Matrix(self.u)
475
+ else:
476
+ f_v = Matrix()
477
+ if self._f_dnh and self._k_dnh:
478
+ f_a = self._f_dnh + self._k_dnh*Matrix(self._udot)
479
+ else:
480
+ f_a = Matrix()
481
+ # Dicts to sub to zero, for splitting up expressions
482
+ u_zero = {i: 0 for i in self.u}
483
+ ud_zero = {i: 0 for i in self._udot}
484
+ qd_zero = {i: 0 for i in self._qdot}
485
+ qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])}
486
+ # Break the kinematic differential eqs apart into f_0 and f_1
487
+ f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot)
488
+ f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u)
489
+ # Break the dynamic differential eqs into f_2 and f_3
490
+ f_2 = msubs(self._frstar, qd_u_zero)
491
+ f_3 = msubs(self._frstar, ud_zero) + self._fr
492
+ f_4 = zeros(len(f_2), 1)
493
+
494
+ # Get the required vector components
495
+ q = self.q
496
+ u = self.u
497
+ if self._qdep:
498
+ q_i = q[:-len(self._qdep)]
499
+ else:
500
+ q_i = q
501
+ q_d = self._qdep
502
+ if self._udep:
503
+ u_i = u[:-len(self._udep)]
504
+ else:
505
+ u_i = u
506
+ u_d = self._udep
507
+
508
+ # Form dictionary to set auxiliary speeds & their derivatives to 0.
509
+ uaux = self._uaux
510
+ uauxdot = uaux.diff(dynamicsymbols._t)
511
+ uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])}
512
+
513
+ # Checking for dynamic symbols outside the dynamic differential
514
+ # equations; throws error if there is.
515
+ sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot]))
516
+ if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot,
517
+ self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]):
518
+ raise ValueError('Cannot have dynamicsymbols outside dynamic \
519
+ forcing vector.')
520
+
521
+ # Find all other dynamic symbols, forming the forcing vector r.
522
+ # Sort r to make it canonical.
523
+ r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list))
524
+ r.sort(key=default_sort_key)
525
+
526
+ # Check for any derivatives of variables in r that are also found in r.
527
+ for i in r:
528
+ if diff(i, dynamicsymbols._t) in r:
529
+ raise ValueError('Cannot have derivatives of specified \
530
+ quantities when linearizing forcing terms.')
531
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
532
+ q_d, u_i, u_d, r)
533
+
534
+ # TODO : Remove `new_method` after 1.1 has been released.
535
+ def linearize(self, *, new_method=None, **kwargs):
536
+ """ Linearize the equations of motion about a symbolic operating point.
537
+
538
+ Explanation
539
+ ===========
540
+
541
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
542
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
543
+
544
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
545
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
546
+ computationally intensive if there are many symbolic parameters. For
547
+ this reason, it may be more desirable to use the default A_and_B=False,
548
+ returning M, A, and B. Values may then be substituted in to these
549
+ matrices, and the state space form found as
550
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
551
+
552
+ In both cases, r is found as all dynamicsymbols in the equations of
553
+ motion that are not part of q, u, q', or u'. They are sorted in
554
+ canonical form.
555
+
556
+ The operating points may be also entered using the ``op_point`` kwarg.
557
+ This takes a dictionary of {symbol: value}, or a an iterable of such
558
+ dictionaries. The values may be numeric or symbolic. The more values
559
+ you can specify beforehand, the faster this computation will run.
560
+
561
+ For more documentation, please see the ``Linearizer`` class."""
562
+ linearizer = self.to_linearizer()
563
+ result = linearizer.linearize(**kwargs)
564
+ return result + (linearizer.r,)
565
+
566
+ def kanes_equations(self, bodies=None, loads=None):
567
+ """ Method to form Kane's equations, Fr + Fr* = 0.
568
+
569
+ Explanation
570
+ ===========
571
+
572
+ Returns (Fr, Fr*). In the case where auxiliary generalized speeds are
573
+ present (say, s auxiliary speeds, o generalized speeds, and m motion
574
+ constraints) the length of the returned vectors will be o - m + s in
575
+ length. The first o - m equations will be the constrained Kane's
576
+ equations, then the s auxiliary Kane's equations. These auxiliary
577
+ equations can be accessed with the auxiliary_eqs property.
578
+
579
+ Parameters
580
+ ==========
581
+
582
+ bodies : iterable
583
+ An iterable of all RigidBody's and Particle's in the system.
584
+ A system must have at least one body.
585
+ loads : iterable
586
+ Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector)
587
+ tuples which represent the force at a point or torque on a frame.
588
+ Must be either a non-empty iterable of tuples or None which corresponds
589
+ to a system with no constraints.
590
+ """
591
+ if bodies is None:
592
+ bodies = self.bodies
593
+ if loads is None and self._forcelist is not None:
594
+ loads = self._forcelist
595
+ if loads == []:
596
+ loads = None
597
+ if not self._k_kqdot:
598
+ raise AttributeError('Create an instance of KanesMethod with '
599
+ 'kinematic differential equations to use this method.')
600
+ fr = self._form_fr(loads)
601
+ frstar = self._form_frstar(bodies)
602
+ if self._uaux:
603
+ if not self._udep:
604
+ km = KanesMethod(self._inertial, self.q, self._uaux,
605
+ u_auxiliary=self._uaux)
606
+ else:
607
+ km = KanesMethod(self._inertial, self.q, self._uaux,
608
+ u_auxiliary=self._uaux, u_dependent=self._udep,
609
+ velocity_constraints=(self._k_nh * self.u +
610
+ self._f_nh),
611
+ acceleration_constraints=(self._k_dnh * self._udot +
612
+ self._f_dnh)
613
+ )
614
+ km._qdot_u_map = self._qdot_u_map
615
+ self._km = km
616
+ fraux = km._form_fr(loads)
617
+ frstaraux = km._form_frstar(bodies)
618
+ self._aux_eq = fraux + frstaraux
619
+ self._fr = fr.col_join(fraux)
620
+ self._frstar = frstar.col_join(frstaraux)
621
+ return (self._fr, self._frstar)
622
+
623
+ def _form_eoms(self):
624
+ fr, frstar = self.kanes_equations(self.bodylist, self.forcelist)
625
+ return fr + frstar
626
+
627
+ def rhs(self, inv_method=None):
628
+ """Returns the system's equations of motion in first order form. The
629
+ output is the right hand side of::
630
+
631
+ x' = |q'| =: f(q, u, r, p, t)
632
+ |u'|
633
+
634
+ The right hand side is what is needed by most numerical ODE
635
+ integrators.
636
+
637
+ Parameters
638
+ ==========
639
+
640
+ inv_method : str
641
+ The specific sympy inverse matrix calculation method to use. For a
642
+ list of valid methods, see
643
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
644
+
645
+ """
646
+ rhs = zeros(len(self.q) + len(self.u), 1)
647
+ kdes = self.kindiffdict()
648
+ for i, q_i in enumerate(self.q):
649
+ rhs[i] = kdes[q_i.diff()]
650
+
651
+ if inv_method is None:
652
+ rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing)
653
+ else:
654
+ rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method,
655
+ try_block_diag=True) *
656
+ self.forcing)
657
+
658
+ return rhs
659
+
660
+ def kindiffdict(self):
661
+ """Returns a dictionary mapping q' to u."""
662
+ if not self._qdot_u_map:
663
+ raise AttributeError('Create an instance of KanesMethod with '
664
+ 'kinematic differential equations to use this method.')
665
+ return self._qdot_u_map
666
+
667
+ @property
668
+ def auxiliary_eqs(self):
669
+ """A matrix containing the auxiliary equations."""
670
+ if not self._fr or not self._frstar:
671
+ raise ValueError('Need to compute Fr, Fr* first.')
672
+ if not self._uaux:
673
+ raise ValueError('No auxiliary speeds have been declared.')
674
+ return self._aux_eq
675
+
676
+ @property
677
+ def mass_matrix_kin(self):
678
+ r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system."""
679
+ return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit
680
+
681
+ @property
682
+ def forcing_kin(self):
683
+ """The kinematic "forcing vector" of the system."""
684
+ if self.explicit_kinematics:
685
+ return -(self._k_ku * Matrix(self.u) + self._f_k)
686
+ else:
687
+ return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit)
688
+
689
+ @property
690
+ def mass_matrix(self):
691
+ """The mass matrix of the system."""
692
+ if not self._fr or not self._frstar:
693
+ raise ValueError('Need to compute Fr, Fr* first.')
694
+ return Matrix([self._k_d, self._k_dnh])
695
+
696
+ @property
697
+ def forcing(self):
698
+ """The forcing vector of the system."""
699
+ if not self._fr or not self._frstar:
700
+ raise ValueError('Need to compute Fr, Fr* first.')
701
+ return -Matrix([self._f_d, self._f_dnh])
702
+
703
+ @property
704
+ def mass_matrix_full(self):
705
+ """The mass matrix of the system, augmented by the kinematic
706
+ differential equations in explicit or implicit form."""
707
+ if not self._fr or not self._frstar:
708
+ raise ValueError('Need to compute Fr, Fr* first.')
709
+ o, n = len(self.u), len(self.q)
710
+ return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join(
711
+ zeros(o, n).row_join(self.mass_matrix))
712
+
713
+ @property
714
+ def forcing_full(self):
715
+ """The forcing vector of the system, augmented by the kinematic
716
+ differential equations in explicit or implicit form."""
717
+ return Matrix([self.forcing_kin, self.forcing])
718
+
719
+ @property
720
+ def q(self):
721
+ return self._q
722
+
723
+ @property
724
+ def u(self):
725
+ return self._u
726
+
727
+ @property
728
+ def bodylist(self):
729
+ return self._bodylist
730
+
731
+ @property
732
+ def forcelist(self):
733
+ return self._forcelist
734
+
735
+ @property
736
+ def bodies(self):
737
+ return self._bodylist
738
+
739
+ @property
740
+ def loads(self):
741
+ return self._forcelist
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import diff, zeros, Matrix, eye, sympify
2
+ from sympy.core.sorting import default_sort_key
3
+ from sympy.physics.vector import dynamicsymbols, ReferenceFrame
4
+ from sympy.physics.mechanics.method import _Methods
5
+ from sympy.physics.mechanics.functions import (
6
+ find_dynamicsymbols, msubs, _f_list_parser, _validate_coordinates)
7
+ from sympy.physics.mechanics.linearize import Linearizer
8
+ from sympy.utilities.iterables import iterable
9
+
10
+ __all__ = ['LagrangesMethod']
11
+
12
+
13
+ class LagrangesMethod(_Methods):
14
+ """Lagrange's method object.
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ This object generates the equations of motion in a two step procedure. The
20
+ first step involves the initialization of LagrangesMethod by supplying the
21
+ Lagrangian and the generalized coordinates, at the bare minimum. If there
22
+ are any constraint equations, they can be supplied as keyword arguments.
23
+ The Lagrange multipliers are automatically generated and are equal in
24
+ number to the constraint equations. Similarly any non-conservative forces
25
+ can be supplied in an iterable (as described below and also shown in the
26
+ example) along with a ReferenceFrame. This is also discussed further in the
27
+ __init__ method.
28
+
29
+ Attributes
30
+ ==========
31
+
32
+ q, u : Matrix
33
+ Matrices of the generalized coordinates and speeds
34
+ loads : iterable
35
+ Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
36
+ describing the forces on the system.
37
+ bodies : iterable
38
+ Iterable containing the rigid bodies and particles of the system.
39
+ mass_matrix : Matrix
40
+ The system's mass matrix
41
+ forcing : Matrix
42
+ The system's forcing vector
43
+ mass_matrix_full : Matrix
44
+ The "mass matrix" for the qdot's, qdoubledot's, and the
45
+ lagrange multipliers (lam)
46
+ forcing_full : Matrix
47
+ The forcing vector for the qdot's, qdoubledot's and
48
+ lagrange multipliers (lam)
49
+
50
+ Examples
51
+ ========
52
+
53
+ This is a simple example for a one degree of freedom translational
54
+ spring-mass-damper.
55
+
56
+ In this example, we first need to do the kinematics.
57
+ This involves creating generalized coordinates and their derivatives.
58
+ Then we create a point and set its velocity in a frame.
59
+
60
+ >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian
61
+ >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point
62
+ >>> from sympy.physics.mechanics import dynamicsymbols
63
+ >>> from sympy import symbols
64
+ >>> q = dynamicsymbols('q')
65
+ >>> qd = dynamicsymbols('q', 1)
66
+ >>> m, k, b = symbols('m k b')
67
+ >>> N = ReferenceFrame('N')
68
+ >>> P = Point('P')
69
+ >>> P.set_vel(N, qd * N.x)
70
+
71
+ We need to then prepare the information as required by LagrangesMethod to
72
+ generate equations of motion.
73
+ First we create the Particle, which has a point attached to it.
74
+ Following this the lagrangian is created from the kinetic and potential
75
+ energies.
76
+ Then, an iterable of nonconservative forces/torques must be constructed,
77
+ where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple,
78
+ with the Vectors representing the nonconservative forces or torques.
79
+
80
+ >>> Pa = Particle('Pa', P, m)
81
+ >>> Pa.potential_energy = k * q**2 / 2.0
82
+ >>> L = Lagrangian(N, Pa)
83
+ >>> fl = [(P, -b * qd * N.x)]
84
+
85
+ Finally we can generate the equations of motion.
86
+ First we create the LagrangesMethod object. To do this one must supply
87
+ the Lagrangian, and the generalized coordinates. The constraint equations,
88
+ the forcelist, and the inertial frame may also be provided, if relevant.
89
+ Next we generate Lagrange's equations of motion, such that:
90
+ Lagrange's equations of motion = 0.
91
+ We have the equations of motion at this point.
92
+
93
+ >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N)
94
+ >>> print(l.form_lagranges_equations())
95
+ Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]])
96
+
97
+ We can also solve for the states using the 'rhs' method.
98
+
99
+ >>> print(l.rhs())
100
+ Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]])
101
+
102
+ Please refer to the docstrings on each method for more details.
103
+ """
104
+
105
+ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None,
106
+ hol_coneqs=None, nonhol_coneqs=None):
107
+ """Supply the following for the initialization of LagrangesMethod.
108
+
109
+ Lagrangian : Sympifyable
110
+
111
+ qs : array_like
112
+ The generalized coordinates
113
+
114
+ hol_coneqs : array_like, optional
115
+ The holonomic constraint equations
116
+
117
+ nonhol_coneqs : array_like, optional
118
+ The nonholonomic constraint equations
119
+
120
+ forcelist : iterable, optional
121
+ Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector)
122
+ tuples which represent the force at a point or torque on a frame.
123
+ This feature is primarily to account for the nonconservative forces
124
+ and/or moments.
125
+
126
+ bodies : iterable, optional
127
+ Takes an iterable containing the rigid bodies and particles of the
128
+ system.
129
+
130
+ frame : ReferenceFrame, optional
131
+ Supply the inertial frame. This is used to determine the
132
+ generalized forces due to non-conservative forces.
133
+ """
134
+
135
+ self._L = Matrix([sympify(Lagrangian)])
136
+ self.eom = None
137
+ self._m_cd = Matrix() # Mass Matrix of differentiated coneqs
138
+ self._m_d = Matrix() # Mass Matrix of dynamic equations
139
+ self._f_cd = Matrix() # Forcing part of the diff coneqs
140
+ self._f_d = Matrix() # Forcing part of the dynamic equations
141
+ self.lam_coeffs = Matrix() # The coeffecients of the multipliers
142
+
143
+ forcelist = forcelist if forcelist else []
144
+ if not iterable(forcelist):
145
+ raise TypeError('Force pairs must be supplied in an iterable.')
146
+ self._forcelist = forcelist
147
+ if frame and not isinstance(frame, ReferenceFrame):
148
+ raise TypeError('frame must be a valid ReferenceFrame')
149
+ self._bodies = bodies
150
+ self.inertial = frame
151
+
152
+ self.lam_vec = Matrix()
153
+
154
+ self._term1 = Matrix()
155
+ self._term2 = Matrix()
156
+ self._term3 = Matrix()
157
+ self._term4 = Matrix()
158
+
159
+ # Creating the qs, qdots and qdoubledots
160
+ if not iterable(qs):
161
+ raise TypeError('Generalized coordinates must be an iterable')
162
+ self._q = Matrix(qs)
163
+ self._qdots = self.q.diff(dynamicsymbols._t)
164
+ self._qdoubledots = self._qdots.diff(dynamicsymbols._t)
165
+ _validate_coordinates(self.q)
166
+
167
+ mat_build = lambda x: Matrix(x) if x else Matrix()
168
+ hol_coneqs = mat_build(hol_coneqs)
169
+ nonhol_coneqs = mat_build(nonhol_coneqs)
170
+ self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t),
171
+ nonhol_coneqs])
172
+ self._hol_coneqs = hol_coneqs
173
+
174
+ def form_lagranges_equations(self):
175
+ """Method to form Lagrange's equations of motion.
176
+
177
+ Returns a vector of equations of motion using Lagrange's equations of
178
+ the second kind.
179
+ """
180
+
181
+ qds = self._qdots
182
+ qdd_zero = {i: 0 for i in self._qdoubledots}
183
+ n = len(self.q)
184
+
185
+ # Internally we represent the EOM as four terms:
186
+ # EOM = term1 - term2 - term3 - term4 = 0
187
+
188
+ # First term
189
+ self._term1 = self._L.jacobian(qds)
190
+ self._term1 = self._term1.diff(dynamicsymbols._t).T
191
+
192
+ # Second term
193
+ self._term2 = self._L.jacobian(self.q).T
194
+
195
+ # Third term
196
+ if self.coneqs:
197
+ coneqs = self.coneqs
198
+ m = len(coneqs)
199
+ # Creating the multipliers
200
+ self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1)))
201
+ self.lam_coeffs = -coneqs.jacobian(qds)
202
+ self._term3 = self.lam_coeffs.T * self.lam_vec
203
+ # Extracting the coeffecients of the qdds from the diff coneqs
204
+ diffconeqs = coneqs.diff(dynamicsymbols._t)
205
+ self._m_cd = diffconeqs.jacobian(self._qdoubledots)
206
+ # The remaining terms i.e. the 'forcing' terms in diff coneqs
207
+ self._f_cd = -diffconeqs.subs(qdd_zero)
208
+ else:
209
+ self._term3 = zeros(n, 1)
210
+
211
+ # Fourth term
212
+ if self.forcelist:
213
+ N = self.inertial
214
+ self._term4 = zeros(n, 1)
215
+ for i, qd in enumerate(qds):
216
+ flist = zip(*_f_list_parser(self.forcelist, N))
217
+ self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist)
218
+ else:
219
+ self._term4 = zeros(n, 1)
220
+
221
+ # Form the dynamic mass and forcing matrices
222
+ without_lam = self._term1 - self._term2 - self._term4
223
+ self._m_d = without_lam.jacobian(self._qdoubledots)
224
+ self._f_d = -without_lam.subs(qdd_zero)
225
+
226
+ # Form the EOM
227
+ self.eom = without_lam - self._term3
228
+ return self.eom
229
+
230
+ def _form_eoms(self):
231
+ return self.form_lagranges_equations()
232
+
233
+ @property
234
+ def mass_matrix(self):
235
+ """Returns the mass matrix, which is augmented by the Lagrange
236
+ multipliers, if necessary.
237
+
238
+ Explanation
239
+ ===========
240
+
241
+ If the system is described by 'n' generalized coordinates and there are
242
+ no constraint equations then an n X n matrix is returned.
243
+
244
+ If there are 'n' generalized coordinates and 'm' constraint equations
245
+ have been supplied during initialization then an n X (n+m) matrix is
246
+ returned. The (n + m - 1)th and (n + m)th columns contain the
247
+ coefficients of the Lagrange multipliers.
248
+ """
249
+
250
+ if self.eom is None:
251
+ raise ValueError('Need to compute the equations of motion first')
252
+ if self.coneqs:
253
+ return (self._m_d).row_join(self.lam_coeffs.T)
254
+ else:
255
+ return self._m_d
256
+
257
+ @property
258
+ def mass_matrix_full(self):
259
+ """Augments the coefficients of qdots to the mass_matrix."""
260
+
261
+ if self.eom is None:
262
+ raise ValueError('Need to compute the equations of motion first')
263
+ n = len(self.q)
264
+ m = len(self.coneqs)
265
+ row1 = eye(n).row_join(zeros(n, n + m))
266
+ row2 = zeros(n, n).row_join(self.mass_matrix)
267
+ if self.coneqs:
268
+ row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m))
269
+ return row1.col_join(row2).col_join(row3)
270
+ else:
271
+ return row1.col_join(row2)
272
+
273
+ @property
274
+ def forcing(self):
275
+ """Returns the forcing vector from 'lagranges_equations' method."""
276
+
277
+ if self.eom is None:
278
+ raise ValueError('Need to compute the equations of motion first')
279
+ return self._f_d
280
+
281
+ @property
282
+ def forcing_full(self):
283
+ """Augments qdots to the forcing vector above."""
284
+
285
+ if self.eom is None:
286
+ raise ValueError('Need to compute the equations of motion first')
287
+ if self.coneqs:
288
+ return self._qdots.col_join(self.forcing).col_join(self._f_cd)
289
+ else:
290
+ return self._qdots.col_join(self.forcing)
291
+
292
+ def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None):
293
+ """Returns an instance of the Linearizer class, initiated from the
294
+ data in the LagrangesMethod class. This may be more desirable than using
295
+ the linearize class method, as the Linearizer object will allow more
296
+ efficient recalculation (i.e. about varying operating points).
297
+
298
+ Parameters
299
+ ==========
300
+
301
+ q_ind, qd_ind : array_like, optional
302
+ The independent generalized coordinates and speeds.
303
+ q_dep, qd_dep : array_like, optional
304
+ The dependent generalized coordinates and speeds.
305
+ """
306
+
307
+ # Compose vectors
308
+ t = dynamicsymbols._t
309
+ q = self.q
310
+ u = self._qdots
311
+ ud = u.diff(t)
312
+ # Get vector of lagrange multipliers
313
+ lams = self.lam_vec
314
+
315
+ mat_build = lambda x: Matrix(x) if x else Matrix()
316
+ q_i = mat_build(q_ind)
317
+ q_d = mat_build(q_dep)
318
+ u_i = mat_build(qd_ind)
319
+ u_d = mat_build(qd_dep)
320
+
321
+ # Compose general form equations
322
+ f_c = self._hol_coneqs
323
+ f_v = self.coneqs
324
+ f_a = f_v.diff(t)
325
+ f_0 = u
326
+ f_1 = -u
327
+ f_2 = self._term1
328
+ f_3 = -(self._term2 + self._term4)
329
+ f_4 = -self._term3
330
+
331
+ # Check that there are an appropriate number of independent and
332
+ # dependent coordinates
333
+ if len(q_d) != len(f_c) or len(u_d) != len(f_v):
334
+ raise ValueError(("Must supply {:} dependent coordinates, and " +
335
+ "{:} dependent speeds").format(len(f_c), len(f_v)))
336
+ if set(Matrix([q_i, q_d])) != set(q):
337
+ raise ValueError("Must partition q into q_ind and q_dep, with " +
338
+ "no extra or missing symbols.")
339
+ if set(Matrix([u_i, u_d])) != set(u):
340
+ raise ValueError("Must partition qd into qd_ind and qd_dep, " +
341
+ "with no extra or missing symbols.")
342
+
343
+ # Find all other dynamic symbols, forming the forcing vector r.
344
+ # Sort r to make it canonical.
345
+ insyms = set(Matrix([q, u, ud, lams]))
346
+ r = list(find_dynamicsymbols(f_3, insyms))
347
+ r.sort(key=default_sort_key)
348
+ # Check for any derivatives of variables in r that are also found in r.
349
+ for i in r:
350
+ if diff(i, dynamicsymbols._t) in r:
351
+ raise ValueError('Cannot have derivatives of specified \
352
+ quantities when linearizing forcing terms.')
353
+
354
+ return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i,
355
+ q_d, u_i, u_d, r, lams)
356
+
357
+ def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None,
358
+ **kwargs):
359
+ """Linearize the equations of motion about a symbolic operating point.
360
+
361
+ Explanation
362
+ ===========
363
+
364
+ If kwarg A_and_B is False (default), returns M, A, B, r for the
365
+ linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.
366
+
367
+ If kwarg A_and_B is True, returns A, B, r for the linearized form
368
+ dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
369
+ computationally intensive if there are many symbolic parameters. For
370
+ this reason, it may be more desirable to use the default A_and_B=False,
371
+ returning M, A, and B. Values may then be substituted in to these
372
+ matrices, and the state space form found as
373
+ A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.
374
+
375
+ In both cases, r is found as all dynamicsymbols in the equations of
376
+ motion that are not part of q, u, q', or u'. They are sorted in
377
+ canonical form.
378
+
379
+ The operating points may be also entered using the ``op_point`` kwarg.
380
+ This takes a dictionary of {symbol: value}, or a an iterable of such
381
+ dictionaries. The values may be numeric or symbolic. The more values
382
+ you can specify beforehand, the faster this computation will run.
383
+
384
+ For more documentation, please see the ``Linearizer`` class."""
385
+
386
+ linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep)
387
+ result = linearizer.linearize(**kwargs)
388
+ return result + (linearizer.r,)
389
+
390
+ def solve_multipliers(self, op_point=None, sol_type='dict'):
391
+ """Solves for the values of the lagrange multipliers symbolically at
392
+ the specified operating point.
393
+
394
+ Parameters
395
+ ==========
396
+
397
+ op_point : dict or iterable of dicts, optional
398
+ Point at which to solve at. The operating point is specified as
399
+ a dictionary or iterable of dictionaries of {symbol: value}. The
400
+ value may be numeric or symbolic itself.
401
+
402
+ sol_type : str, optional
403
+ Solution return type. Valid options are:
404
+ - 'dict': A dict of {symbol : value} (default)
405
+ - 'Matrix': An ordered column matrix of the solution
406
+ """
407
+
408
+ # Determine number of multipliers
409
+ k = len(self.lam_vec)
410
+ if k == 0:
411
+ raise ValueError("System has no lagrange multipliers to solve for.")
412
+ # Compose dict of operating conditions
413
+ if isinstance(op_point, dict):
414
+ op_point_dict = op_point
415
+ elif iterable(op_point):
416
+ op_point_dict = {}
417
+ for op in op_point:
418
+ op_point_dict.update(op)
419
+ elif op_point is None:
420
+ op_point_dict = {}
421
+ else:
422
+ raise TypeError("op_point must be either a dictionary or an "
423
+ "iterable of dictionaries.")
424
+ # Compose the system to be solved
425
+ mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join(
426
+ zeros(k, k)))
427
+ force_matrix = self.forcing.col_join(self._f_cd)
428
+ # Sub in the operating point
429
+ mass_matrix = msubs(mass_matrix, op_point_dict)
430
+ force_matrix = msubs(force_matrix, op_point_dict)
431
+ # Solve for the multipliers
432
+ sol_list = mass_matrix.LUsolve(-force_matrix)[-k:]
433
+ if sol_type == 'dict':
434
+ return dict(zip(self.lam_vec, sol_list))
435
+ elif sol_type == 'Matrix':
436
+ return Matrix(sol_list)
437
+ else:
438
+ raise ValueError("Unknown sol_type {:}.".format(sol_type))
439
+
440
+ def rhs(self, inv_method=None, **kwargs):
441
+ """Returns equations that can be solved numerically.
442
+
443
+ Parameters
444
+ ==========
445
+
446
+ inv_method : str
447
+ The specific sympy inverse matrix calculation method to use. For a
448
+ list of valid methods, see
449
+ :meth:`~sympy.matrices.matrices.MatrixBase.inv`
450
+ """
451
+
452
+ if inv_method is None:
453
+ self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full)
454
+ else:
455
+ self._rhs = (self.mass_matrix_full.inv(inv_method,
456
+ try_block_diag=True) * self.forcing_full)
457
+ return self._rhs
458
+
459
+ @property
460
+ def q(self):
461
+ return self._q
462
+
463
+ @property
464
+ def u(self):
465
+ return self._qdots
466
+
467
+ @property
468
+ def bodies(self):
469
+ return self._bodies
470
+
471
+ @property
472
+ def forcelist(self):
473
+ return self._forcelist
474
+
475
+ @property
476
+ def loads(self):
477
+ return self._forcelist
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ['Linearizer']
2
+
3
+ from sympy.core.backend import Matrix, eye, zeros
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.utilities.iterables import flatten
6
+ from sympy.physics.vector import dynamicsymbols
7
+ from sympy.physics.mechanics.functions import msubs
8
+
9
+ from collections import namedtuple
10
+ from collections.abc import Iterable
11
+
12
+ class Linearizer:
13
+ """This object holds the general model form for a dynamic system.
14
+ This model is used for computing the linearized form of the system,
15
+ while properly dealing with constraints leading to dependent
16
+ coordinates and speeds.
17
+
18
+ Attributes
19
+ ==========
20
+
21
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix
22
+ Matrices holding the general system form.
23
+ q, u, r : Matrix
24
+ Matrices holding the generalized coordinates, speeds, and
25
+ input vectors.
26
+ q_i, u_i : Matrix
27
+ Matrices of the independent generalized coordinates and speeds.
28
+ q_d, u_d : Matrix
29
+ Matrices of the dependent generalized coordinates and speeds.
30
+ perm_mat : Matrix
31
+ Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T
32
+ """
33
+
34
+ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u,
35
+ q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None):
36
+ """
37
+ Parameters
38
+ ==========
39
+
40
+ f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like
41
+ System of equations holding the general system form.
42
+ Supply empty array or Matrix if the parameter
43
+ does not exist.
44
+ q : array_like
45
+ The generalized coordinates.
46
+ u : array_like
47
+ The generalized speeds
48
+ q_i, u_i : array_like, optional
49
+ The independent generalized coordinates and speeds.
50
+ q_d, u_d : array_like, optional
51
+ The dependent generalized coordinates and speeds.
52
+ r : array_like, optional
53
+ The input variables.
54
+ lams : array_like, optional
55
+ The lagrange multipliers
56
+ """
57
+
58
+ # Generalized equation form
59
+ self.f_0 = Matrix(f_0)
60
+ self.f_1 = Matrix(f_1)
61
+ self.f_2 = Matrix(f_2)
62
+ self.f_3 = Matrix(f_3)
63
+ self.f_4 = Matrix(f_4)
64
+ self.f_c = Matrix(f_c)
65
+ self.f_v = Matrix(f_v)
66
+ self.f_a = Matrix(f_a)
67
+
68
+ # Generalized equation variables
69
+ self.q = Matrix(q)
70
+ self.u = Matrix(u)
71
+ none_handler = lambda x: Matrix(x) if x else Matrix()
72
+ self.q_i = none_handler(q_i)
73
+ self.q_d = none_handler(q_d)
74
+ self.u_i = none_handler(u_i)
75
+ self.u_d = none_handler(u_d)
76
+ self.r = none_handler(r)
77
+ self.lams = none_handler(lams)
78
+
79
+ # Derivatives of generalized equation variables
80
+ self._qd = self.q.diff(dynamicsymbols._t)
81
+ self._ud = self.u.diff(dynamicsymbols._t)
82
+ # If the user doesn't actually use generalized variables, and the
83
+ # qd and u vectors have any intersecting variables, this can cause
84
+ # problems. We'll fix this with some hackery, and Dummy variables
85
+ dup_vars = set(self._qd).intersection(self.u)
86
+ self._qd_dup = Matrix([var if var not in dup_vars else Dummy()
87
+ for var in self._qd])
88
+
89
+ # Derive dimesion terms
90
+ l = len(self.f_c)
91
+ m = len(self.f_v)
92
+ n = len(self.q)
93
+ o = len(self.u)
94
+ s = len(self.r)
95
+ k = len(self.lams)
96
+ dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k'])
97
+ self._dims = dims(l, m, n, o, s, k)
98
+
99
+ self._Pq = None
100
+ self._Pqi = None
101
+ self._Pqd = None
102
+ self._Pu = None
103
+ self._Pui = None
104
+ self._Pud = None
105
+ self._C_0 = None
106
+ self._C_1 = None
107
+ self._C_2 = None
108
+ self.perm_mat = None
109
+
110
+ self._setup_done = False
111
+
112
+ def _setup(self):
113
+ # Calculations here only need to be run once. They are moved out of
114
+ # the __init__ method to increase the speed of Linearizer creation.
115
+ self._form_permutation_matrices()
116
+ self._form_block_matrices()
117
+ self._form_coefficient_matrices()
118
+ self._setup_done = True
119
+
120
+ def _form_permutation_matrices(self):
121
+ """Form the permutation matrices Pq and Pu."""
122
+
123
+ # Extract dimension variables
124
+ l, m, n, o, s, k = self._dims
125
+ # Compute permutation matrices
126
+ if n != 0:
127
+ self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d]))
128
+ if l > 0:
129
+ self._Pqi = self._Pq[:, :-l]
130
+ self._Pqd = self._Pq[:, -l:]
131
+ else:
132
+ self._Pqi = self._Pq
133
+ self._Pqd = Matrix()
134
+ if o != 0:
135
+ self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d]))
136
+ if m > 0:
137
+ self._Pui = self._Pu[:, :-m]
138
+ self._Pud = self._Pu[:, -m:]
139
+ else:
140
+ self._Pui = self._Pu
141
+ self._Pud = Matrix()
142
+ # Compute combination permutation matrix for computing A and B
143
+ P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)])
144
+ P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)])
145
+ if P_col1:
146
+ if P_col2:
147
+ self.perm_mat = P_col1.row_join(P_col2)
148
+ else:
149
+ self.perm_mat = P_col1
150
+ else:
151
+ self.perm_mat = P_col2
152
+
153
+ def _form_coefficient_matrices(self):
154
+ """Form the coefficient matrices C_0, C_1, and C_2."""
155
+
156
+ # Extract dimension variables
157
+ l, m, n, o, s, k = self._dims
158
+ # Build up the coefficient matrices C_0, C_1, and C_2
159
+ # If there are configuration constraints (l > 0), form C_0 as normal.
160
+ # If not, C_0 is I_(nxn). Note that this works even if n=0
161
+ if l > 0:
162
+ f_c_jac_q = self.f_c.jacobian(self.q)
163
+ self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q *
164
+ self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi
165
+ else:
166
+ self._C_0 = eye(n)
167
+ # If there are motion constraints (m > 0), form C_1 and C_2 as normal.
168
+ # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if
169
+ # o = 0.
170
+ if m > 0:
171
+ f_v_jac_u = self.f_v.jacobian(self.u)
172
+ temp = f_v_jac_u * self._Pud
173
+ if n != 0:
174
+ f_v_jac_q = self.f_v.jacobian(self.q)
175
+ self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q)
176
+ else:
177
+ self._C_1 = zeros(o, n)
178
+ self._C_2 = (eye(o) - self._Pud *
179
+ temp.LUsolve(f_v_jac_u)) * self._Pui
180
+ else:
181
+ self._C_1 = zeros(o, n)
182
+ self._C_2 = eye(o)
183
+
184
+ def _form_block_matrices(self):
185
+ """Form the block matrices for composing M, A, and B."""
186
+
187
+ # Extract dimension variables
188
+ l, m, n, o, s, k = self._dims
189
+ # Block Matrix Definitions. These are only defined if under certain
190
+ # conditions. If undefined, an empty matrix is used instead
191
+ if n != 0:
192
+ self._M_qq = self.f_0.jacobian(self._qd)
193
+ self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q)
194
+ else:
195
+ self._M_qq = Matrix()
196
+ self._A_qq = Matrix()
197
+ if n != 0 and m != 0:
198
+ self._M_uqc = self.f_a.jacobian(self._qd_dup)
199
+ self._A_uqc = -self.f_a.jacobian(self.q)
200
+ else:
201
+ self._M_uqc = Matrix()
202
+ self._A_uqc = Matrix()
203
+ if n != 0 and o - m + k != 0:
204
+ self._M_uqd = self.f_3.jacobian(self._qd_dup)
205
+ self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q)
206
+ else:
207
+ self._M_uqd = Matrix()
208
+ self._A_uqd = Matrix()
209
+ if o != 0 and m != 0:
210
+ self._M_uuc = self.f_a.jacobian(self._ud)
211
+ self._A_uuc = -self.f_a.jacobian(self.u)
212
+ else:
213
+ self._M_uuc = Matrix()
214
+ self._A_uuc = Matrix()
215
+ if o != 0 and o - m + k != 0:
216
+ self._M_uud = self.f_2.jacobian(self._ud)
217
+ self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u)
218
+ else:
219
+ self._M_uud = Matrix()
220
+ self._A_uud = Matrix()
221
+ if o != 0 and n != 0:
222
+ self._A_qu = -self.f_1.jacobian(self.u)
223
+ else:
224
+ self._A_qu = Matrix()
225
+ if k != 0 and o - m + k != 0:
226
+ self._M_uld = self.f_4.jacobian(self.lams)
227
+ else:
228
+ self._M_uld = Matrix()
229
+ if s != 0 and o - m + k != 0:
230
+ self._B_u = -self.f_3.jacobian(self.r)
231
+ else:
232
+ self._B_u = Matrix()
233
+
234
+ def linearize(self, op_point=None, A_and_B=False, simplify=False):
235
+ """Linearize the system about the operating point. Note that
236
+ q_op, u_op, qd_op, ud_op must satisfy the equations of motion.
237
+ These may be either symbolic or numeric.
238
+
239
+ Parameters
240
+ ==========
241
+
242
+ op_point : dict or iterable of dicts, optional
243
+ Dictionary or iterable of dictionaries containing the operating
244
+ point conditions. These will be substituted in to the linearized
245
+ system before the linearization is complete. Leave blank if you
246
+ want a completely symbolic form. Note that any reduction in
247
+ symbols (whether substituted for numbers or expressions with a
248
+ common parameter) will result in faster runtime.
249
+
250
+ A_and_B : bool, optional
251
+ If A_and_B=False (default), (M, A, B) is returned for forming
252
+ [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True,
253
+ (A, B) is returned for forming dx = [A]x + [B]r, where
254
+ x = [q_ind, u_ind]^T.
255
+
256
+ simplify : bool, optional
257
+ Determines if returned values are simplified before return.
258
+ For large expressions this may be time consuming. Default is False.
259
+
260
+ Potential Issues
261
+ ================
262
+
263
+ Note that the process of solving with A_and_B=True is
264
+ computationally intensive if there are many symbolic parameters.
265
+ For this reason, it may be more desirable to use the default
266
+ A_and_B=False, returning M, A, and B. More values may then be
267
+ substituted in to these matrices later on. The state space form can
268
+ then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where
269
+ P = Linearizer.perm_mat.
270
+ """
271
+
272
+ # Run the setup if needed:
273
+ if not self._setup_done:
274
+ self._setup()
275
+
276
+ # Compose dict of operating conditions
277
+ if isinstance(op_point, dict):
278
+ op_point_dict = op_point
279
+ elif isinstance(op_point, Iterable):
280
+ op_point_dict = {}
281
+ for op in op_point:
282
+ op_point_dict.update(op)
283
+ else:
284
+ op_point_dict = {}
285
+
286
+ # Extract dimension variables
287
+ l, m, n, o, s, k = self._dims
288
+
289
+ # Rename terms to shorten expressions
290
+ M_qq = self._M_qq
291
+ M_uqc = self._M_uqc
292
+ M_uqd = self._M_uqd
293
+ M_uuc = self._M_uuc
294
+ M_uud = self._M_uud
295
+ M_uld = self._M_uld
296
+ A_qq = self._A_qq
297
+ A_uqc = self._A_uqc
298
+ A_uqd = self._A_uqd
299
+ A_qu = self._A_qu
300
+ A_uuc = self._A_uuc
301
+ A_uud = self._A_uud
302
+ B_u = self._B_u
303
+ C_0 = self._C_0
304
+ C_1 = self._C_1
305
+ C_2 = self._C_2
306
+
307
+ # Build up Mass Matrix
308
+ # |M_qq 0_nxo 0_nxk|
309
+ # M = |M_uqc M_uuc 0_mxk|
310
+ # |M_uqd M_uud M_uld|
311
+ if o != 0:
312
+ col2 = Matrix([zeros(n, o), M_uuc, M_uud])
313
+ if k != 0:
314
+ col3 = Matrix([zeros(n + m, k), M_uld])
315
+ if n != 0:
316
+ col1 = Matrix([M_qq, M_uqc, M_uqd])
317
+ if o != 0 and k != 0:
318
+ M = col1.row_join(col2).row_join(col3)
319
+ elif o != 0:
320
+ M = col1.row_join(col2)
321
+ else:
322
+ M = col1
323
+ elif k != 0:
324
+ M = col2.row_join(col3)
325
+ else:
326
+ M = col2
327
+ M_eq = msubs(M, op_point_dict)
328
+
329
+ # Build up state coefficient matrix A
330
+ # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2|
331
+ # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2|
332
+ # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2|
333
+ # Col 1 is only defined if n != 0
334
+ if n != 0:
335
+ r1c1 = A_qq
336
+ if o != 0:
337
+ r1c1 += (A_qu * C_1)
338
+ r1c1 = r1c1 * C_0
339
+ if m != 0:
340
+ r2c1 = A_uqc
341
+ if o != 0:
342
+ r2c1 += (A_uuc * C_1)
343
+ r2c1 = r2c1 * C_0
344
+ else:
345
+ r2c1 = Matrix()
346
+ if o - m + k != 0:
347
+ r3c1 = A_uqd
348
+ if o != 0:
349
+ r3c1 += (A_uud * C_1)
350
+ r3c1 = r3c1 * C_0
351
+ else:
352
+ r3c1 = Matrix()
353
+ col1 = Matrix([r1c1, r2c1, r3c1])
354
+ else:
355
+ col1 = Matrix()
356
+ # Col 2 is only defined if o != 0
357
+ if o != 0:
358
+ if n != 0:
359
+ r1c2 = A_qu * C_2
360
+ else:
361
+ r1c2 = Matrix()
362
+ if m != 0:
363
+ r2c2 = A_uuc * C_2
364
+ else:
365
+ r2c2 = Matrix()
366
+ if o - m + k != 0:
367
+ r3c2 = A_uud * C_2
368
+ else:
369
+ r3c2 = Matrix()
370
+ col2 = Matrix([r1c2, r2c2, r3c2])
371
+ else:
372
+ col2 = Matrix()
373
+ if col1:
374
+ if col2:
375
+ Amat = col1.row_join(col2)
376
+ else:
377
+ Amat = col1
378
+ else:
379
+ Amat = col2
380
+ Amat_eq = msubs(Amat, op_point_dict)
381
+
382
+ # Build up the B matrix if there are forcing variables
383
+ # |0_(n + m)xs|
384
+ # B = |B_u |
385
+ if s != 0 and o - m + k != 0:
386
+ Bmat = zeros(n + m, s).col_join(B_u)
387
+ Bmat_eq = msubs(Bmat, op_point_dict)
388
+ else:
389
+ Bmat_eq = Matrix()
390
+
391
+ # kwarg A_and_B indicates to return A, B for forming the equation
392
+ # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T,
393
+ if A_and_B:
394
+ A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq)
395
+ if Bmat_eq:
396
+ B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq)
397
+ else:
398
+ # Bmat = Matrix([]), so no need to sub
399
+ B_cont = Bmat_eq
400
+ if simplify:
401
+ A_cont.simplify()
402
+ B_cont.simplify()
403
+ return A_cont, B_cont
404
+ # Otherwise return M, A, B for forming the equation
405
+ # [M]dx = [A]x + [B]r, where x = [q, u]^T
406
+ else:
407
+ if simplify:
408
+ M_eq.simplify()
409
+ Amat_eq.simplify()
410
+ Bmat_eq.simplify()
411
+ return M_eq, Amat_eq, Bmat_eq
412
+
413
+
414
+ def permutation_matrix(orig_vec, per_vec):
415
+ """Compute the permutation matrix to change order of
416
+ orig_vec into order of per_vec.
417
+
418
+ Parameters
419
+ ==========
420
+
421
+ orig_vec : array_like
422
+ Symbols in original ordering.
423
+ per_vec : array_like
424
+ Symbols in new ordering.
425
+
426
+ Returns
427
+ =======
428
+
429
+ p_matrix : Matrix
430
+ Permutation matrix such that orig_vec == (p_matrix * per_vec).
431
+ """
432
+ if not isinstance(orig_vec, (list, tuple)):
433
+ orig_vec = flatten(orig_vec)
434
+ if not isinstance(per_vec, (list, tuple)):
435
+ per_vec = flatten(per_vec)
436
+ if set(orig_vec) != set(per_vec):
437
+ raise ValueError("orig_vec and per_vec must be the same length, " +
438
+ "and contain the same symbols.")
439
+ ind_list = [orig_vec.index(i) for i in per_vec]
440
+ p_matrix = zeros(len(orig_vec))
441
+ for i, j in enumerate(ind_list):
442
+ p_matrix[i, j] = 1
443
+ return p_matrix
llmeval-env/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.")
llmeval-env/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
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import sympify
2
+ from sympy.physics.vector import Point
3
+
4
+ from sympy.utilities.exceptions import sympy_deprecation_warning
5
+
6
+ __all__ = ['Particle']
7
+
8
+
9
+ class Particle:
10
+ """A particle.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ Particles have a non-zero mass and lack spatial extension; they take up no
16
+ space.
17
+
18
+ Values need to be supplied on initialization, but can be changed later.
19
+
20
+ Parameters
21
+ ==========
22
+
23
+ name : str
24
+ Name of particle
25
+ point : Point
26
+ A physics/mechanics Point which represents the position, velocity, and
27
+ acceleration of this Particle
28
+ mass : sympifyable
29
+ A SymPy expression representing the Particle's mass
30
+
31
+ Examples
32
+ ========
33
+
34
+ >>> from sympy.physics.mechanics import Particle, Point
35
+ >>> from sympy import Symbol
36
+ >>> po = Point('po')
37
+ >>> m = Symbol('m')
38
+ >>> pa = Particle('pa', po, m)
39
+ >>> # Or you could change these later
40
+ >>> pa.mass = m
41
+ >>> pa.point = po
42
+
43
+ """
44
+
45
+ def __init__(self, name, point, mass):
46
+ if not isinstance(name, str):
47
+ raise TypeError('Supply a valid name.')
48
+ self._name = name
49
+ self.mass = mass
50
+ self.point = point
51
+ self.potential_energy = 0
52
+
53
+ def __str__(self):
54
+ return self._name
55
+
56
+ def __repr__(self):
57
+ return self.__str__()
58
+
59
+ @property
60
+ def mass(self):
61
+ """Mass of the particle."""
62
+ return self._mass
63
+
64
+ @mass.setter
65
+ def mass(self, value):
66
+ self._mass = sympify(value)
67
+
68
+ @property
69
+ def point(self):
70
+ """Point of the particle."""
71
+ return self._point
72
+
73
+ @point.setter
74
+ def point(self, p):
75
+ if not isinstance(p, Point):
76
+ raise TypeError("Particle point attribute must be a Point object.")
77
+ self._point = p
78
+
79
+ def linear_momentum(self, frame):
80
+ """Linear momentum of the particle.
81
+
82
+ Explanation
83
+ ===========
84
+
85
+ The linear momentum L, of a particle P, with respect to frame N is
86
+ given by:
87
+
88
+ L = m * v
89
+
90
+ where m is the mass of the particle, and v is the velocity of the
91
+ particle in the frame N.
92
+
93
+ Parameters
94
+ ==========
95
+
96
+ frame : ReferenceFrame
97
+ The frame in which linear momentum is desired.
98
+
99
+ Examples
100
+ ========
101
+
102
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
103
+ >>> from sympy.physics.mechanics import dynamicsymbols
104
+ >>> from sympy.physics.vector import init_vprinting
105
+ >>> init_vprinting(pretty_print=False)
106
+ >>> m, v = dynamicsymbols('m v')
107
+ >>> N = ReferenceFrame('N')
108
+ >>> P = Point('P')
109
+ >>> A = Particle('A', P, m)
110
+ >>> P.set_vel(N, v * N.x)
111
+ >>> A.linear_momentum(N)
112
+ m*v*N.x
113
+
114
+ """
115
+
116
+ return self.mass * self.point.vel(frame)
117
+
118
+ def angular_momentum(self, point, frame):
119
+ """Angular momentum of the particle about the point.
120
+
121
+ Explanation
122
+ ===========
123
+
124
+ The angular momentum H, about some point O of a particle, P, is given
125
+ by:
126
+
127
+ ``H = cross(r, m * v)``
128
+
129
+ where r is the position vector from point O to the particle P, m is
130
+ the mass of the particle, and v is the velocity of the particle in
131
+ the inertial frame, N.
132
+
133
+ Parameters
134
+ ==========
135
+
136
+ point : Point
137
+ The point about which angular momentum of the particle is desired.
138
+
139
+ frame : ReferenceFrame
140
+ The frame in which angular momentum is desired.
141
+
142
+ Examples
143
+ ========
144
+
145
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
146
+ >>> from sympy.physics.mechanics import dynamicsymbols
147
+ >>> from sympy.physics.vector import init_vprinting
148
+ >>> init_vprinting(pretty_print=False)
149
+ >>> m, v, r = dynamicsymbols('m v r')
150
+ >>> N = ReferenceFrame('N')
151
+ >>> O = Point('O')
152
+ >>> A = O.locatenew('A', r * N.x)
153
+ >>> P = Particle('P', A, m)
154
+ >>> P.point.set_vel(N, v * N.y)
155
+ >>> P.angular_momentum(O, N)
156
+ m*r*v*N.z
157
+
158
+ """
159
+
160
+ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame))
161
+
162
+ def kinetic_energy(self, frame):
163
+ """Kinetic energy of the particle.
164
+
165
+ Explanation
166
+ ===========
167
+
168
+ The kinetic energy, T, of a particle, P, is given by:
169
+
170
+ ``T = 1/2 (dot(m * v, v))``
171
+
172
+ where m is the mass of particle P, and v is the velocity of the
173
+ particle in the supplied ReferenceFrame.
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ frame : ReferenceFrame
179
+ The Particle's velocity is typically defined with respect to
180
+ an inertial frame but any relevant frame in which the velocity is
181
+ known can be supplied.
182
+
183
+ Examples
184
+ ========
185
+
186
+ >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame
187
+ >>> from sympy import symbols
188
+ >>> m, v, r = symbols('m v r')
189
+ >>> N = ReferenceFrame('N')
190
+ >>> O = Point('O')
191
+ >>> P = Particle('P', O, m)
192
+ >>> P.point.set_vel(N, v * N.y)
193
+ >>> P.kinetic_energy(N)
194
+ m*v**2/2
195
+
196
+ """
197
+
198
+ return (self.mass / sympify(2) * self.point.vel(frame) &
199
+ self.point.vel(frame))
200
+
201
+ @property
202
+ def potential_energy(self):
203
+ """The potential energy of the Particle.
204
+
205
+ Examples
206
+ ========
207
+
208
+ >>> from sympy.physics.mechanics import Particle, Point
209
+ >>> from sympy import symbols
210
+ >>> m, g, h = symbols('m g h')
211
+ >>> O = Point('O')
212
+ >>> P = Particle('P', O, m)
213
+ >>> P.potential_energy = m * g * h
214
+ >>> P.potential_energy
215
+ g*h*m
216
+
217
+ """
218
+
219
+ return self._pe
220
+
221
+ @potential_energy.setter
222
+ def potential_energy(self, scalar):
223
+ """Used to set the potential energy of the Particle.
224
+
225
+ Parameters
226
+ ==========
227
+
228
+ scalar : Sympifyable
229
+ The potential energy (a scalar) of the Particle.
230
+
231
+ Examples
232
+ ========
233
+
234
+ >>> from sympy.physics.mechanics import Particle, Point
235
+ >>> from sympy import symbols
236
+ >>> m, g, h = symbols('m g h')
237
+ >>> O = Point('O')
238
+ >>> P = Particle('P', O, m)
239
+ >>> P.potential_energy = m * g * h
240
+
241
+ """
242
+
243
+ self._pe = sympify(scalar)
244
+
245
+ def set_potential_energy(self, scalar):
246
+ sympy_deprecation_warning(
247
+ """
248
+ The sympy.physics.mechanics.Particle.set_potential_energy()
249
+ method is deprecated. Instead use
250
+
251
+ P.potential_energy = scalar
252
+ """,
253
+ deprecated_since_version="1.5",
254
+ active_deprecations_target="deprecated-set-potential-energy",
255
+ )
256
+ self.potential_energy = scalar
257
+
258
+ def parallel_axis(self, point, frame):
259
+ """Returns an inertia dyadic of the particle with respect to another
260
+ point and frame.
261
+
262
+ Parameters
263
+ ==========
264
+
265
+ point : sympy.physics.vector.Point
266
+ The point to express the inertia dyadic about.
267
+ frame : sympy.physics.vector.ReferenceFrame
268
+ The reference frame used to construct the dyadic.
269
+
270
+ Returns
271
+ =======
272
+
273
+ inertia : sympy.physics.vector.Dyadic
274
+ The inertia dyadic of the particle expressed about the provided
275
+ point and frame.
276
+
277
+ """
278
+ # circular import issue
279
+ from sympy.physics.mechanics import inertia_of_point_mass
280
+ return inertia_of_point_mass(self.mass, self.point.pos_from(point),
281
+ frame)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import sympify
2
+ from sympy.physics.vector import Point, ReferenceFrame, Dyadic
3
+
4
+ from sympy.utilities.exceptions import sympy_deprecation_warning
5
+
6
+ __all__ = ['RigidBody']
7
+
8
+
9
+ class RigidBody:
10
+ """An idealized rigid body.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ This is essentially a container which holds the various components which
16
+ describe a rigid body: a name, mass, center of mass, reference frame, and
17
+ inertia.
18
+
19
+ All of these need to be supplied on creation, but can be changed
20
+ afterwards.
21
+
22
+ Attributes
23
+ ==========
24
+
25
+ name : string
26
+ The body's name.
27
+ masscenter : Point
28
+ The point which represents the center of mass of the rigid body.
29
+ frame : ReferenceFrame
30
+ The ReferenceFrame which the rigid body is fixed in.
31
+ mass : Sympifyable
32
+ The body's mass.
33
+ inertia : (Dyadic, Point)
34
+ The body's inertia about a point; stored in a tuple as shown above.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy import Symbol
40
+ >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody
41
+ >>> from sympy.physics.mechanics import outer
42
+ >>> m = Symbol('m')
43
+ >>> A = ReferenceFrame('A')
44
+ >>> P = Point('P')
45
+ >>> I = outer (A.x, A.x)
46
+ >>> inertia_tuple = (I, P)
47
+ >>> B = RigidBody('B', P, A, m, inertia_tuple)
48
+ >>> # Or you could change them afterwards
49
+ >>> m2 = Symbol('m2')
50
+ >>> B.mass = m2
51
+
52
+ """
53
+
54
+ def __init__(self, name, masscenter, frame, mass, inertia):
55
+ if not isinstance(name, str):
56
+ raise TypeError('Supply a valid name.')
57
+ self._name = name
58
+ self.masscenter = masscenter
59
+ self.mass = mass
60
+ self.frame = frame
61
+ self.inertia = inertia
62
+ self.potential_energy = 0
63
+
64
+ def __str__(self):
65
+ return self._name
66
+
67
+ def __repr__(self):
68
+ return self.__str__()
69
+
70
+ @property
71
+ def frame(self):
72
+ """The ReferenceFrame fixed to the body."""
73
+ return self._frame
74
+
75
+ @frame.setter
76
+ def frame(self, F):
77
+ if not isinstance(F, ReferenceFrame):
78
+ raise TypeError("RigidBody frame must be a ReferenceFrame object.")
79
+ self._frame = F
80
+
81
+ @property
82
+ def masscenter(self):
83
+ """The body's center of mass."""
84
+ return self._masscenter
85
+
86
+ @masscenter.setter
87
+ def masscenter(self, p):
88
+ if not isinstance(p, Point):
89
+ raise TypeError("RigidBody center of mass must be a Point object.")
90
+ self._masscenter = p
91
+
92
+ @property
93
+ def mass(self):
94
+ """The body's mass."""
95
+ return self._mass
96
+
97
+ @mass.setter
98
+ def mass(self, m):
99
+ self._mass = sympify(m)
100
+
101
+ @property
102
+ def inertia(self):
103
+ """The body's inertia about a point; stored as (Dyadic, Point)."""
104
+ return (self._inertia, self._inertia_point)
105
+
106
+ @inertia.setter
107
+ def inertia(self, I):
108
+ if not isinstance(I[0], Dyadic):
109
+ raise TypeError("RigidBody inertia must be a Dyadic object.")
110
+ if not isinstance(I[1], Point):
111
+ raise TypeError("RigidBody inertia must be about a Point.")
112
+ self._inertia = I[0]
113
+ self._inertia_point = I[1]
114
+ # have I S/O, want I S/S*
115
+ # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O
116
+ # I_S/S* = I_S/O - I_S*/O
117
+ from sympy.physics.mechanics.functions import inertia_of_point_mass
118
+ I_Ss_O = inertia_of_point_mass(self.mass,
119
+ self.masscenter.pos_from(I[1]),
120
+ self.frame)
121
+ self._central_inertia = I[0] - I_Ss_O
122
+
123
+ @property
124
+ def central_inertia(self):
125
+ """The body's central inertia dyadic."""
126
+ return self._central_inertia
127
+
128
+ @central_inertia.setter
129
+ def central_inertia(self, I):
130
+ if not isinstance(I, Dyadic):
131
+ raise TypeError("RigidBody inertia must be a Dyadic object.")
132
+ self.inertia = (I, self.masscenter)
133
+
134
+ def linear_momentum(self, frame):
135
+ """ Linear momentum of the rigid body.
136
+
137
+ Explanation
138
+ ===========
139
+
140
+ The linear momentum L, of a rigid body B, with respect to frame N is
141
+ given by:
142
+
143
+ L = M * v*
144
+
145
+ where M is the mass of the rigid body and v* is the velocity of
146
+ the mass center of B in the frame, N.
147
+
148
+ Parameters
149
+ ==========
150
+
151
+ frame : ReferenceFrame
152
+ The frame in which linear momentum is desired.
153
+
154
+ Examples
155
+ ========
156
+
157
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
158
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
159
+ >>> from sympy.physics.vector import init_vprinting
160
+ >>> init_vprinting(pretty_print=False)
161
+ >>> M, v = dynamicsymbols('M v')
162
+ >>> N = ReferenceFrame('N')
163
+ >>> P = Point('P')
164
+ >>> P.set_vel(N, v * N.x)
165
+ >>> I = outer (N.x, N.x)
166
+ >>> Inertia_tuple = (I, P)
167
+ >>> B = RigidBody('B', P, N, M, Inertia_tuple)
168
+ >>> B.linear_momentum(N)
169
+ M*v*N.x
170
+
171
+ """
172
+
173
+ return self.mass * self.masscenter.vel(frame)
174
+
175
+ def angular_momentum(self, point, frame):
176
+ """Returns the angular momentum of the rigid body about a point in the
177
+ given frame.
178
+
179
+ Explanation
180
+ ===========
181
+
182
+ The angular momentum H of a rigid body B about some point O in a frame
183
+ N is given by:
184
+
185
+ ``H = dot(I, w) + cross(r, M * v)``
186
+
187
+ where I is the central inertia dyadic of B, w is the angular velocity
188
+ of body B in the frame, N, r is the position vector from point O to the
189
+ mass center of B, and v is the velocity of the mass center in the
190
+ frame, N.
191
+
192
+ Parameters
193
+ ==========
194
+
195
+ point : Point
196
+ The point about which angular momentum is desired.
197
+ frame : ReferenceFrame
198
+ The frame in which angular momentum is desired.
199
+
200
+ Examples
201
+ ========
202
+
203
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
204
+ >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols
205
+ >>> from sympy.physics.vector import init_vprinting
206
+ >>> init_vprinting(pretty_print=False)
207
+ >>> M, v, r, omega = dynamicsymbols('M v r omega')
208
+ >>> N = ReferenceFrame('N')
209
+ >>> b = ReferenceFrame('b')
210
+ >>> b.set_ang_vel(N, omega * b.x)
211
+ >>> P = Point('P')
212
+ >>> P.set_vel(N, 1 * N.x)
213
+ >>> I = outer(b.x, b.x)
214
+ >>> B = RigidBody('B', P, b, M, (I, P))
215
+ >>> B.angular_momentum(P, N)
216
+ omega*b.x
217
+
218
+ """
219
+ I = self.central_inertia
220
+ w = self.frame.ang_vel_in(frame)
221
+ m = self.mass
222
+ r = self.masscenter.pos_from(point)
223
+ v = self.masscenter.vel(frame)
224
+
225
+ return I.dot(w) + r.cross(m * v)
226
+
227
+ def kinetic_energy(self, frame):
228
+ """Kinetic energy of the rigid body.
229
+
230
+ Explanation
231
+ ===========
232
+
233
+ The kinetic energy, T, of a rigid body, B, is given by:
234
+
235
+ ``T = 1/2 * (dot(dot(I, w), w) + dot(m * v, v))``
236
+
237
+ where I and m are the central inertia dyadic and mass of rigid body B,
238
+ respectively, omega is the body's angular velocity and v is the
239
+ velocity of the body's mass center in the supplied ReferenceFrame.
240
+
241
+ Parameters
242
+ ==========
243
+
244
+ frame : ReferenceFrame
245
+ The RigidBody's angular velocity and the velocity of it's mass
246
+ center are typically defined with respect to an inertial frame but
247
+ any relevant frame in which the velocities are known can be supplied.
248
+
249
+ Examples
250
+ ========
251
+
252
+ >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer
253
+ >>> from sympy.physics.mechanics import RigidBody
254
+ >>> from sympy import symbols
255
+ >>> M, v, r, omega = symbols('M v r omega')
256
+ >>> N = ReferenceFrame('N')
257
+ >>> b = ReferenceFrame('b')
258
+ >>> b.set_ang_vel(N, omega * b.x)
259
+ >>> P = Point('P')
260
+ >>> P.set_vel(N, v * N.x)
261
+ >>> I = outer (b.x, b.x)
262
+ >>> inertia_tuple = (I, P)
263
+ >>> B = RigidBody('B', P, b, M, inertia_tuple)
264
+ >>> B.kinetic_energy(N)
265
+ M*v**2/2 + omega**2/2
266
+
267
+ """
268
+
269
+ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia &
270
+ self.frame.ang_vel_in(frame)) / sympify(2))
271
+
272
+ translational_KE = (self.mass * (self.masscenter.vel(frame) &
273
+ self.masscenter.vel(frame)) / sympify(2))
274
+
275
+ return rotational_KE + translational_KE
276
+
277
+ @property
278
+ def potential_energy(self):
279
+ """The potential energy of the RigidBody.
280
+
281
+ Examples
282
+ ========
283
+
284
+ >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame
285
+ >>> from sympy import symbols
286
+ >>> M, g, h = symbols('M g h')
287
+ >>> b = ReferenceFrame('b')
288
+ >>> P = Point('P')
289
+ >>> I = outer (b.x, b.x)
290
+ >>> Inertia_tuple = (I, P)
291
+ >>> B = RigidBody('B', P, b, M, Inertia_tuple)
292
+ >>> B.potential_energy = M * g * h
293
+ >>> B.potential_energy
294
+ M*g*h
295
+
296
+ """
297
+
298
+ return self._pe
299
+
300
+ @potential_energy.setter
301
+ def potential_energy(self, scalar):
302
+ """Used to set the potential energy of this RigidBody.
303
+
304
+ Parameters
305
+ ==========
306
+
307
+ scalar: Sympifyable
308
+ The potential energy (a scalar) of the RigidBody.
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy.physics.mechanics import Point, outer
314
+ >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame
315
+ >>> from sympy import symbols
316
+ >>> b = ReferenceFrame('b')
317
+ >>> M, g, h = symbols('M g h')
318
+ >>> P = Point('P')
319
+ >>> I = outer (b.x, b.x)
320
+ >>> Inertia_tuple = (I, P)
321
+ >>> B = RigidBody('B', P, b, M, Inertia_tuple)
322
+ >>> B.potential_energy = M * g * h
323
+
324
+ """
325
+
326
+ self._pe = sympify(scalar)
327
+
328
+ def set_potential_energy(self, scalar):
329
+ sympy_deprecation_warning(
330
+ """
331
+ The sympy.physics.mechanics.RigidBody.set_potential_energy()
332
+ method is deprecated. Instead use
333
+
334
+ B.potential_energy = scalar
335
+ """,
336
+ deprecated_since_version="1.5",
337
+ active_deprecations_target="deprecated-set-potential-energy",
338
+ )
339
+ self.potential_energy = scalar
340
+
341
+ def parallel_axis(self, point, frame=None):
342
+ """Returns the inertia dyadic of the body with respect to another
343
+ point.
344
+
345
+ Parameters
346
+ ==========
347
+
348
+ point : sympy.physics.vector.Point
349
+ The point to express the inertia dyadic about.
350
+ frame : sympy.physics.vector.ReferenceFrame
351
+ The reference frame used to construct the dyadic.
352
+
353
+ Returns
354
+ =======
355
+
356
+ inertia : sympy.physics.vector.Dyadic
357
+ The inertia dyadic of the rigid body expressed about the provided
358
+ point.
359
+
360
+ """
361
+ # circular import issue
362
+ from sympy.physics.mechanics.functions import inertia_of_point_mass
363
+ if frame is None:
364
+ frame = self.frame
365
+ return self.central_inertia + inertia_of_point_mass(
366
+ self.mass, self.masscenter.pos_from(point), frame)
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/system.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import eye, Matrix, zeros
2
+ from sympy.physics.mechanics import dynamicsymbols
3
+ from sympy.physics.mechanics.functions import find_dynamicsymbols
4
+
5
+ __all__ = ['SymbolicSystem']
6
+
7
+
8
+ class SymbolicSystem:
9
+ """SymbolicSystem is a class that contains all the information about a
10
+ system in a symbolic format such as the equations of motions and the bodies
11
+ and loads in the system.
12
+
13
+ There are three ways that the equations of motion can be described for
14
+ Symbolic System:
15
+
16
+
17
+ [1] Explicit form where the kinematics and dynamics are combined
18
+ x' = F_1(x, t, r, p)
19
+
20
+ [2] Implicit form where the kinematics and dynamics are combined
21
+ M_2(x, p) x' = F_2(x, t, r, p)
22
+
23
+ [3] Implicit form where the kinematics and dynamics are separate
24
+ M_3(q, p) u' = F_3(q, u, t, r, p)
25
+ q' = G(q, u, t, r, p)
26
+
27
+ where
28
+
29
+ x : states, e.g. [q, u]
30
+ t : time
31
+ r : specified (exogenous) inputs
32
+ p : constants
33
+ q : generalized coordinates
34
+ u : generalized speeds
35
+ F_1 : right hand side of the combined equations in explicit form
36
+ F_2 : right hand side of the combined equations in implicit form
37
+ F_3 : right hand side of the dynamical equations in implicit form
38
+ M_2 : mass matrix of the combined equations in implicit form
39
+ M_3 : mass matrix of the dynamical equations in implicit form
40
+ G : right hand side of the kinematical differential equations
41
+
42
+ Parameters
43
+ ==========
44
+
45
+ coord_states : ordered iterable of functions of time
46
+ This input will either be a collection of the coordinates or states
47
+ of the system depending on whether or not the speeds are also
48
+ given. If speeds are specified this input will be assumed to
49
+ be the coordinates otherwise this input will be assumed to
50
+ be the states.
51
+
52
+ right_hand_side : Matrix
53
+ This variable is the right hand side of the equations of motion in
54
+ any of the forms. The specific form will be assumed depending on
55
+ whether a mass matrix or coordinate derivatives are given.
56
+
57
+ speeds : ordered iterable of functions of time, optional
58
+ This is a collection of the generalized speeds of the system. If
59
+ given it will be assumed that the first argument (coord_states)
60
+ will represent the generalized coordinates of the system.
61
+
62
+ mass_matrix : Matrix, optional
63
+ The matrix of the implicit forms of the equations of motion (forms
64
+ [2] and [3]). The distinction between the forms is determined by
65
+ whether or not the coordinate derivatives are passed in. If
66
+ they are given form [3] will be assumed otherwise form [2] is
67
+ assumed.
68
+
69
+ coordinate_derivatives : Matrix, optional
70
+ The right hand side of the kinematical equations in explicit form.
71
+ If given it will be assumed that the equations of motion are being
72
+ entered in form [3].
73
+
74
+ alg_con : Iterable, optional
75
+ The indexes of the rows in the equations of motion that contain
76
+ algebraic constraints instead of differential equations. If the
77
+ equations are input in form [3], it will be assumed the indexes are
78
+ referencing the mass_matrix/right_hand_side combination and not the
79
+ coordinate_derivatives.
80
+
81
+ output_eqns : Dictionary, optional
82
+ Any output equations that are desired to be tracked are stored in a
83
+ dictionary where the key corresponds to the name given for the
84
+ specific equation and the value is the equation itself in symbolic
85
+ form
86
+
87
+ coord_idxs : Iterable, optional
88
+ If coord_states corresponds to the states rather than the
89
+ coordinates this variable will tell SymbolicSystem which indexes of
90
+ the states correspond to generalized coordinates.
91
+
92
+ speed_idxs : Iterable, optional
93
+ If coord_states corresponds to the states rather than the
94
+ coordinates this variable will tell SymbolicSystem which indexes of
95
+ the states correspond to generalized speeds.
96
+
97
+ bodies : iterable of Body/Rigidbody objects, optional
98
+ Iterable containing the bodies of the system
99
+
100
+ loads : iterable of load instances (described below), optional
101
+ Iterable containing the loads of the system where forces are given
102
+ by (point of application, force vector) and torques are given by
103
+ (reference frame acting upon, torque vector). Ex [(point, force),
104
+ (ref_frame, torque)]
105
+
106
+ Attributes
107
+ ==========
108
+
109
+ coordinates : Matrix, shape(n, 1)
110
+ This is a matrix containing the generalized coordinates of the system
111
+
112
+ speeds : Matrix, shape(m, 1)
113
+ This is a matrix containing the generalized speeds of the system
114
+
115
+ states : Matrix, shape(o, 1)
116
+ This is a matrix containing the state variables of the system
117
+
118
+ alg_con : List
119
+ This list contains the indices of the algebraic constraints in the
120
+ combined equations of motion. The presence of these constraints
121
+ requires that a DAE solver be used instead of an ODE solver.
122
+ If the system is given in form [3] the alg_con variable will be
123
+ adjusted such that it is a representation of the combined kinematics
124
+ and dynamics thus make sure it always matches the mass matrix
125
+ entered.
126
+
127
+ dyn_implicit_mat : Matrix, shape(m, m)
128
+ This is the M matrix in form [3] of the equations of motion (the mass
129
+ matrix or generalized inertia matrix of the dynamical equations of
130
+ motion in implicit form).
131
+
132
+ dyn_implicit_rhs : Matrix, shape(m, 1)
133
+ This is the F vector in form [3] of the equations of motion (the right
134
+ hand side of the dynamical equations of motion in implicit form).
135
+
136
+ comb_implicit_mat : Matrix, shape(o, o)
137
+ This is the M matrix in form [2] of the equations of motion.
138
+ This matrix contains a block diagonal structure where the top
139
+ left block (the first rows) represent the matrix in the
140
+ implicit form of the kinematical equations and the bottom right
141
+ block (the last rows) represent the matrix in the implicit form
142
+ of the dynamical equations.
143
+
144
+ comb_implicit_rhs : Matrix, shape(o, 1)
145
+ This is the F vector in form [2] of the equations of motion. The top
146
+ part of the vector represents the right hand side of the implicit form
147
+ of the kinemaical equations and the bottom of the vector represents the
148
+ right hand side of the implicit form of the dynamical equations of
149
+ motion.
150
+
151
+ comb_explicit_rhs : Matrix, shape(o, 1)
152
+ This vector represents the right hand side of the combined equations of
153
+ motion in explicit form (form [1] from above).
154
+
155
+ kin_explicit_rhs : Matrix, shape(m, 1)
156
+ This is the right hand side of the explicit form of the kinematical
157
+ equations of motion as can be seen in form [3] (the G matrix).
158
+
159
+ output_eqns : Dictionary
160
+ If output equations were given they are stored in a dictionary where
161
+ the key corresponds to the name given for the specific equation and
162
+ the value is the equation itself in symbolic form
163
+
164
+ bodies : Tuple
165
+ If the bodies in the system were given they are stored in a tuple for
166
+ future access
167
+
168
+ loads : Tuple
169
+ If the loads in the system were given they are stored in a tuple for
170
+ future access. This includes forces and torques where forces are given
171
+ by (point of application, force vector) and torques are given by
172
+ (reference frame acted upon, torque vector).
173
+
174
+ Example
175
+ =======
176
+
177
+ As a simple example, the dynamics of a simple pendulum will be input into a
178
+ SymbolicSystem object manually. First some imports will be needed and then
179
+ symbols will be set up for the length of the pendulum (l), mass at the end
180
+ of the pendulum (m), and a constant for gravity (g). ::
181
+
182
+ >>> from sympy import Matrix, sin, symbols
183
+ >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem
184
+ >>> l, m, g = symbols('l m g')
185
+
186
+ The system will be defined by an angle of theta from the vertical and a
187
+ generalized speed of omega will be used where omega = theta_dot. ::
188
+
189
+ >>> theta, omega = dynamicsymbols('theta omega')
190
+
191
+ Now the equations of motion are ready to be formed and passed to the
192
+ SymbolicSystem object. ::
193
+
194
+ >>> kin_explicit_rhs = Matrix([omega])
195
+ >>> dyn_implicit_mat = Matrix([l**2 * m])
196
+ >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)])
197
+ >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega],
198
+ ... dyn_implicit_mat)
199
+
200
+ Notes
201
+ =====
202
+
203
+ m : number of generalized speeds
204
+ n : number of generalized coordinates
205
+ o : number of states
206
+
207
+ """
208
+
209
+ def __init__(self, coord_states, right_hand_side, speeds=None,
210
+ mass_matrix=None, coordinate_derivatives=None, alg_con=None,
211
+ output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None,
212
+ loads=None):
213
+ """Initializes a SymbolicSystem object"""
214
+
215
+ # Extract information on speeds, coordinates and states
216
+ if speeds is None:
217
+ self._states = Matrix(coord_states)
218
+
219
+ if coord_idxs is None:
220
+ self._coordinates = None
221
+ else:
222
+ coords = [coord_states[i] for i in coord_idxs]
223
+ self._coordinates = Matrix(coords)
224
+
225
+ if speed_idxs is None:
226
+ self._speeds = None
227
+ else:
228
+ speeds_inter = [coord_states[i] for i in speed_idxs]
229
+ self._speeds = Matrix(speeds_inter)
230
+ else:
231
+ self._coordinates = Matrix(coord_states)
232
+ self._speeds = Matrix(speeds)
233
+ self._states = self._coordinates.col_join(self._speeds)
234
+
235
+ # Extract equations of motion form
236
+ if coordinate_derivatives is not None:
237
+ self._kin_explicit_rhs = coordinate_derivatives
238
+ self._dyn_implicit_rhs = right_hand_side
239
+ self._dyn_implicit_mat = mass_matrix
240
+ self._comb_implicit_rhs = None
241
+ self._comb_implicit_mat = None
242
+ self._comb_explicit_rhs = None
243
+ elif mass_matrix is not None:
244
+ self._kin_explicit_rhs = None
245
+ self._dyn_implicit_rhs = None
246
+ self._dyn_implicit_mat = None
247
+ self._comb_implicit_rhs = right_hand_side
248
+ self._comb_implicit_mat = mass_matrix
249
+ self._comb_explicit_rhs = None
250
+ else:
251
+ self._kin_explicit_rhs = None
252
+ self._dyn_implicit_rhs = None
253
+ self._dyn_implicit_mat = None
254
+ self._comb_implicit_rhs = None
255
+ self._comb_implicit_mat = None
256
+ self._comb_explicit_rhs = right_hand_side
257
+
258
+ # Set the remainder of the inputs as instance attributes
259
+ if alg_con is not None and coordinate_derivatives is not None:
260
+ alg_con = [i + len(coordinate_derivatives) for i in alg_con]
261
+ self._alg_con = alg_con
262
+ self.output_eqns = output_eqns
263
+
264
+ # Change the body and loads iterables to tuples if they are not tuples
265
+ # already
266
+ if not isinstance(bodies, tuple) and bodies is not None:
267
+ bodies = tuple(bodies)
268
+ if not isinstance(loads, tuple) and loads is not None:
269
+ loads = tuple(loads)
270
+ self._bodies = bodies
271
+ self._loads = loads
272
+
273
+ @property
274
+ def coordinates(self):
275
+ """Returns the column matrix of the generalized coordinates"""
276
+ if self._coordinates is None:
277
+ raise AttributeError("The coordinates were not specified.")
278
+ else:
279
+ return self._coordinates
280
+
281
+ @property
282
+ def speeds(self):
283
+ """Returns the column matrix of generalized speeds"""
284
+ if self._speeds is None:
285
+ raise AttributeError("The speeds were not specified.")
286
+ else:
287
+ return self._speeds
288
+
289
+ @property
290
+ def states(self):
291
+ """Returns the column matrix of the state variables"""
292
+ return self._states
293
+
294
+ @property
295
+ def alg_con(self):
296
+ """Returns a list with the indices of the rows containing algebraic
297
+ constraints in the combined form of the equations of motion"""
298
+ return self._alg_con
299
+
300
+ @property
301
+ def dyn_implicit_mat(self):
302
+ """Returns the matrix, M, corresponding to the dynamic equations in
303
+ implicit form, M x' = F, where the kinematical equations are not
304
+ included"""
305
+ if self._dyn_implicit_mat is None:
306
+ raise AttributeError("dyn_implicit_mat is not specified for "
307
+ "equations of motion form [1] or [2].")
308
+ else:
309
+ return self._dyn_implicit_mat
310
+
311
+ @property
312
+ def dyn_implicit_rhs(self):
313
+ """Returns the column matrix, F, corresponding to the dynamic equations
314
+ in implicit form, M x' = F, where the kinematical equations are not
315
+ included"""
316
+ if self._dyn_implicit_rhs is None:
317
+ raise AttributeError("dyn_implicit_rhs is not specified for "
318
+ "equations of motion form [1] or [2].")
319
+ else:
320
+ return self._dyn_implicit_rhs
321
+
322
+ @property
323
+ def comb_implicit_mat(self):
324
+ """Returns the matrix, M, corresponding to the equations of motion in
325
+ implicit form (form [2]), M x' = F, where the kinematical equations are
326
+ included"""
327
+ if self._comb_implicit_mat is None:
328
+ if self._dyn_implicit_mat is not None:
329
+ num_kin_eqns = len(self._kin_explicit_rhs)
330
+ num_dyn_eqns = len(self._dyn_implicit_rhs)
331
+ zeros1 = zeros(num_kin_eqns, num_dyn_eqns)
332
+ zeros2 = zeros(num_dyn_eqns, num_kin_eqns)
333
+ inter1 = eye(num_kin_eqns).row_join(zeros1)
334
+ inter2 = zeros2.row_join(self._dyn_implicit_mat)
335
+ self._comb_implicit_mat = inter1.col_join(inter2)
336
+ return self._comb_implicit_mat
337
+ else:
338
+ raise AttributeError("comb_implicit_mat is not specified for "
339
+ "equations of motion form [1].")
340
+ else:
341
+ return self._comb_implicit_mat
342
+
343
+ @property
344
+ def comb_implicit_rhs(self):
345
+ """Returns the column matrix, F, corresponding to the equations of
346
+ motion in implicit form (form [2]), M x' = F, where the kinematical
347
+ equations are included"""
348
+ if self._comb_implicit_rhs is None:
349
+ if self._dyn_implicit_rhs is not None:
350
+ kin_inter = self._kin_explicit_rhs
351
+ dyn_inter = self._dyn_implicit_rhs
352
+ self._comb_implicit_rhs = kin_inter.col_join(dyn_inter)
353
+ return self._comb_implicit_rhs
354
+ else:
355
+ raise AttributeError("comb_implicit_mat is not specified for "
356
+ "equations of motion in form [1].")
357
+ else:
358
+ return self._comb_implicit_rhs
359
+
360
+ def compute_explicit_form(self):
361
+ """If the explicit right hand side of the combined equations of motion
362
+ is to provided upon initialization, this method will calculate it. This
363
+ calculation can potentially take awhile to compute."""
364
+ if self._comb_explicit_rhs is not None:
365
+ raise AttributeError("comb_explicit_rhs is already formed.")
366
+
367
+ inter1 = getattr(self, 'kin_explicit_rhs', None)
368
+ if inter1 is not None:
369
+ inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs)
370
+ out = inter1.col_join(inter2)
371
+ else:
372
+ out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs)
373
+
374
+ self._comb_explicit_rhs = out
375
+
376
+ @property
377
+ def comb_explicit_rhs(self):
378
+ """Returns the right hand side of the equations of motion in explicit
379
+ form, x' = F, where the kinematical equations are included"""
380
+ if self._comb_explicit_rhs is None:
381
+ raise AttributeError("Please run .combute_explicit_form before "
382
+ "attempting to access comb_explicit_rhs.")
383
+ else:
384
+ return self._comb_explicit_rhs
385
+
386
+ @property
387
+ def kin_explicit_rhs(self):
388
+ """Returns the right hand side of the kinematical equations in explicit
389
+ form, q' = G"""
390
+ if self._kin_explicit_rhs is None:
391
+ raise AttributeError("kin_explicit_rhs is not specified for "
392
+ "equations of motion form [1] or [2].")
393
+ else:
394
+ return self._kin_explicit_rhs
395
+
396
+ def dynamic_symbols(self):
397
+ """Returns a column matrix containing all of the symbols in the system
398
+ that depend on time"""
399
+ # Create a list of all of the expressions in the equations of motion
400
+ if self._comb_explicit_rhs is None:
401
+ eom_expressions = (self.comb_implicit_mat[:] +
402
+ self.comb_implicit_rhs[:])
403
+ else:
404
+ eom_expressions = (self._comb_explicit_rhs[:])
405
+
406
+ functions_of_time = set()
407
+ for expr in eom_expressions:
408
+ functions_of_time = functions_of_time.union(
409
+ find_dynamicsymbols(expr))
410
+ functions_of_time = functions_of_time.union(self._states)
411
+
412
+ return tuple(functions_of_time)
413
+
414
+ def constant_symbols(self):
415
+ """Returns a column matrix containing all of the symbols in the system
416
+ that do not depend on time"""
417
+ # Create a list of all of the expressions in the equations of motion
418
+ if self._comb_explicit_rhs is None:
419
+ eom_expressions = (self.comb_implicit_mat[:] +
420
+ self.comb_implicit_rhs[:])
421
+ else:
422
+ eom_expressions = (self._comb_explicit_rhs[:])
423
+
424
+ constants = set()
425
+ for expr in eom_expressions:
426
+ constants = constants.union(expr.free_symbols)
427
+ constants.remove(dynamicsymbols._t)
428
+
429
+ return tuple(constants)
430
+
431
+ @property
432
+ def bodies(self):
433
+ """Returns the bodies in the system"""
434
+ if self._bodies is None:
435
+ raise AttributeError("bodies were not specified for the system.")
436
+ else:
437
+ return self._bodies
438
+
439
+ @property
440
+ def loads(self):
441
+ """Returns the loads in the system"""
442
+ if self._loads is None:
443
+ raise AttributeError("loads were not specified for the system.")
444
+ else:
445
+ return self._loads
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc ADDED
Binary file (39.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc ADDED
Binary file (4.25 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-310.pyc ADDED
Binary file (2.54 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py ADDED
@@ -0,0 +1,1144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand_mul
2
+ from sympy.core.numbers import pi
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.elementary.trigonometric import (cos, sin)
6
+ from sympy.core.backend import Matrix, _simplify_matrix, eye, zeros
7
+ from sympy.core.symbol import symbols
8
+ from sympy.physics.mechanics import (dynamicsymbols, Body, JointsMethod,
9
+ PinJoint, PrismaticJoint, CylindricalJoint,
10
+ PlanarJoint, SphericalJoint, WeldJoint)
11
+ from sympy.physics.mechanics.joint import Joint
12
+ from sympy.physics.vector import Vector, ReferenceFrame, Point
13
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
14
+
15
+
16
+ Vector.simp = True
17
+ t = dynamicsymbols._t # type: ignore
18
+
19
+
20
+ def _generate_body(interframe=False):
21
+ N = ReferenceFrame('N')
22
+ A = ReferenceFrame('A')
23
+ P = Body('P', frame=N)
24
+ C = Body('C', frame=A)
25
+ if interframe:
26
+ Pint, Cint = ReferenceFrame('P_int'), ReferenceFrame('C_int')
27
+ Pint.orient_axis(N, N.x, pi)
28
+ Cint.orient_axis(A, A.y, -pi / 2)
29
+ return N, A, P, C, Pint, Cint
30
+ return N, A, P, C
31
+
32
+
33
+ def test_Joint():
34
+ parent = Body('parent')
35
+ child = Body('child')
36
+ raises(TypeError, lambda: Joint('J', parent, child))
37
+
38
+
39
+ def test_coordinate_generation():
40
+ q, u, qj, uj = dynamicsymbols('q u q_J u_J')
41
+ q0j, q1j, q2j, q3j, u0j, u1j, u2j, u3j = dynamicsymbols('q0:4_J u0:4_J')
42
+ q0, q1, q2, q3, u0, u1, u2, u3 = dynamicsymbols('q0:4 u0:4')
43
+ _, _, P, C = _generate_body()
44
+ # Using PinJoint to access Joint's coordinate generation method
45
+ J = PinJoint('J', P, C)
46
+ # Test single given
47
+ assert J._fill_coordinate_list(q, 1) == Matrix([q])
48
+ assert J._fill_coordinate_list([u], 1) == Matrix([u])
49
+ assert J._fill_coordinate_list([u], 1, offset=2) == Matrix([u])
50
+ # Test None
51
+ assert J._fill_coordinate_list(None, 1) == Matrix([qj])
52
+ assert J._fill_coordinate_list([None], 1) == Matrix([qj])
53
+ assert J._fill_coordinate_list([q0, None, None], 3) == Matrix(
54
+ [q0, q1j, q2j])
55
+ # Test autofill
56
+ assert J._fill_coordinate_list(None, 3) == Matrix([q0j, q1j, q2j])
57
+ assert J._fill_coordinate_list([], 3) == Matrix([q0j, q1j, q2j])
58
+ # Test offset
59
+ assert J._fill_coordinate_list([], 3, offset=1) == Matrix([q1j, q2j, q3j])
60
+ assert J._fill_coordinate_list([q1, None, q3], 3, offset=1) == Matrix(
61
+ [q1, q2j, q3])
62
+ assert J._fill_coordinate_list(None, 2, offset=2) == Matrix([q2j, q3j])
63
+ # Test label
64
+ assert J._fill_coordinate_list(None, 1, 'u') == Matrix([uj])
65
+ assert J._fill_coordinate_list([], 3, 'u') == Matrix([u0j, u1j, u2j])
66
+ # Test single numbering
67
+ assert J._fill_coordinate_list(None, 1, number_single=True) == Matrix([q0j])
68
+ assert J._fill_coordinate_list([], 1, 'u', 2, True) == Matrix([u2j])
69
+ assert J._fill_coordinate_list([], 3, 'q') == Matrix([q0j, q1j, q2j])
70
+ # Test invalid number of coordinates supplied
71
+ raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 1))
72
+ raises(ValueError, lambda: J._fill_coordinate_list([u0, u1, None], 2, 'u'))
73
+ raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 3))
74
+ # Test incorrect coordinate type
75
+ raises(TypeError, lambda: J._fill_coordinate_list([q0, symbols('q1')], 2))
76
+ raises(TypeError, lambda: J._fill_coordinate_list([q0 + q1, q1], 2))
77
+ # Test if derivative as generalized speed is allowed
78
+ _, _, P, C = _generate_body()
79
+ PinJoint('J', P, C, q1, q1.diff(t))
80
+ # Test duplicate coordinates
81
+ _, _, P, C = _generate_body()
82
+ raises(ValueError, lambda: SphericalJoint('J', P, C, [q1j, None, None]))
83
+ raises(ValueError, lambda: SphericalJoint('J', P, C, speeds=[u0, u0, u1]))
84
+
85
+
86
+ def test_pin_joint():
87
+ P = Body('P')
88
+ C = Body('C')
89
+ l, m = symbols('l m')
90
+ q, u = dynamicsymbols('q_J, u_J')
91
+ Pj = PinJoint('J', P, C)
92
+ assert Pj.name == 'J'
93
+ assert Pj.parent == P
94
+ assert Pj.child == C
95
+ assert Pj.coordinates == Matrix([q])
96
+ assert Pj.speeds == Matrix([u])
97
+ assert Pj.kdes == Matrix([u - q.diff(t)])
98
+ assert Pj.joint_axis == P.frame.x
99
+ assert Pj.child_point.pos_from(C.masscenter) == Vector(0)
100
+ assert Pj.parent_point.pos_from(P.masscenter) == Vector(0)
101
+ assert Pj.parent_point.pos_from(Pj._child_point) == Vector(0)
102
+ assert C.masscenter.pos_from(P.masscenter) == Vector(0)
103
+ assert Pj.parent_interframe == P.frame
104
+ assert Pj.child_interframe == C.frame
105
+ assert Pj.__str__() == 'PinJoint: J parent: P child: C'
106
+
107
+ P1 = Body('P1')
108
+ C1 = Body('C1')
109
+ Pint = ReferenceFrame('P_int')
110
+ Pint.orient_axis(P1.frame, P1.y, pi / 2)
111
+ J1 = PinJoint('J1', P1, C1, parent_point=l*P1.frame.x,
112
+ child_point=m*C1.frame.y, joint_axis=P1.frame.z,
113
+ parent_interframe=Pint)
114
+ assert J1._joint_axis == P1.frame.z
115
+ assert J1._child_point.pos_from(C1.masscenter) == m * C1.frame.y
116
+ assert J1._parent_point.pos_from(P1.masscenter) == l * P1.frame.x
117
+ assert J1._parent_point.pos_from(J1._child_point) == Vector(0)
118
+ assert (P1.masscenter.pos_from(C1.masscenter) ==
119
+ -l*P1.frame.x + m*C1.frame.y)
120
+ assert J1.parent_interframe == Pint
121
+ assert J1.child_interframe == C1.frame
122
+
123
+ q, u = dynamicsymbols('q, u')
124
+ N, A, P, C, Pint, Cint = _generate_body(True)
125
+ parent_point = P.masscenter.locatenew('parent_point', N.x + N.y)
126
+ child_point = C.masscenter.locatenew('child_point', C.y + C.z)
127
+ J = PinJoint('J', P, C, q, u, parent_point=parent_point,
128
+ child_point=child_point, parent_interframe=Pint,
129
+ child_interframe=Cint, joint_axis=N.z)
130
+ assert J.joint_axis == N.z
131
+ assert J.parent_point.vel(N) == 0
132
+ assert J.parent_point == parent_point
133
+ assert J.child_point == child_point
134
+ assert J.child_point.pos_from(P.masscenter) == N.x + N.y
135
+ assert J.parent_point.pos_from(C.masscenter) == C.y + C.z
136
+ assert C.masscenter.pos_from(P.masscenter) == N.x + N.y - C.y - C.z
137
+ assert C.masscenter.vel(N).express(N) == (u * sin(q) - u * cos(q)) * N.x + (
138
+ -u * sin(q) - u * cos(q)) * N.y
139
+ assert J.parent_interframe == Pint
140
+ assert J.child_interframe == Cint
141
+
142
+
143
+ def test_pin_joint_double_pendulum():
144
+ q1, q2 = dynamicsymbols('q1 q2')
145
+ u1, u2 = dynamicsymbols('u1 u2')
146
+ m, l = symbols('m l')
147
+ N = ReferenceFrame('N')
148
+ A = ReferenceFrame('A')
149
+ B = ReferenceFrame('B')
150
+ C = Body('C', frame=N) # ceiling
151
+ PartP = Body('P', frame=A, mass=m)
152
+ PartR = Body('R', frame=B, mass=m)
153
+
154
+ J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
155
+ child_point=-l*A.x, joint_axis=C.frame.z)
156
+ J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
157
+ child_point=-l*B.x, joint_axis=PartP.frame.z)
158
+
159
+ # Check orientation
160
+ assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0],
161
+ [sin(q1), cos(q1), 0], [0, 0, 1]])
162
+ assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0],
163
+ [sin(q2), cos(q2), 0], [0, 0, 1]])
164
+ assert _simplify_matrix(N.dcm(B)) == Matrix([[cos(q1 + q2), -sin(q1 + q2), 0],
165
+ [sin(q1 + q2), cos(q1 + q2), 0],
166
+ [0, 0, 1]])
167
+
168
+ # Check Angular Velocity
169
+ assert A.ang_vel_in(N) == u1 * N.z
170
+ assert B.ang_vel_in(A) == u2 * A.z
171
+ assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z
172
+
173
+ # Check kde
174
+ assert J1.kdes == Matrix([u1 - q1.diff(t)])
175
+ assert J2.kdes == Matrix([u2 - q2.diff(t)])
176
+
177
+ # Check Linear Velocity
178
+ assert PartP.masscenter.vel(N) == l*u1*A.y
179
+ assert PartR.masscenter.vel(A) == l*u2*B.y
180
+ assert PartR.masscenter.vel(N) == l*u1*A.y + l*(u1 + u2)*B.y
181
+
182
+
183
+ def test_pin_joint_chaos_pendulum():
184
+ mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h')
185
+ theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
186
+ N = ReferenceFrame('N')
187
+ A = ReferenceFrame('A')
188
+ B = ReferenceFrame('B')
189
+ lA = (lB - h / 2) / 2
190
+ lC = (lB/2 + h/4)
191
+ rod = Body('rod', frame=A, mass=mA)
192
+ plate = Body('plate', mass=mB, frame=B)
193
+ C = Body('C', frame=N)
194
+ J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
195
+ child_point=lA*A.z, joint_axis=N.y)
196
+ J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
197
+ parent_point=lC*A.z, joint_axis=A.z)
198
+
199
+ # Check orientation
200
+ assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)],
201
+ [0, 1, 0],
202
+ [sin(theta), 0, cos(theta)]])
203
+ assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0],
204
+ [sin(phi), cos(phi), 0],
205
+ [0, 0, 1]])
206
+ assert B.dcm(N) == Matrix([
207
+ [cos(phi)*cos(theta), sin(phi), -sin(theta)*cos(phi)],
208
+ [-sin(phi)*cos(theta), cos(phi), sin(phi)*sin(theta)],
209
+ [sin(theta), 0, cos(theta)]])
210
+
211
+ # Check Angular Velocity
212
+ assert A.ang_vel_in(N) == omega*N.y
213
+ assert A.ang_vel_in(B) == -alpha*A.z
214
+ assert N.ang_vel_in(B) == -omega*N.y - alpha*A.z
215
+
216
+ # Check kde
217
+ assert J1.kdes == Matrix([omega - theta.diff(t)])
218
+ assert J2.kdes == Matrix([alpha - phi.diff(t)])
219
+
220
+ # Check pos of masscenters
221
+ assert C.masscenter.pos_from(rod.masscenter) == lA*A.z
222
+ assert rod.masscenter.pos_from(plate.masscenter) == - lC * A.z
223
+
224
+ # Check Linear Velocities
225
+ assert rod.masscenter.vel(N) == (h/4 - lB/2)*omega*A.x
226
+ assert plate.masscenter.vel(N) == ((h/4 - lB/2)*omega +
227
+ (h/4 + lB/2)*omega)*A.x
228
+
229
+
230
+ def test_pin_joint_interframe():
231
+ q, u = dynamicsymbols('q, u')
232
+ # Check not connected
233
+ N, A, P, C = _generate_body()
234
+ Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint')
235
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint))
236
+ raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint))
237
+ # Check not fixed interframe
238
+ Pint.orient_axis(N, N.z, q)
239
+ Cint.orient_axis(A, A.z, q)
240
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint))
241
+ raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint))
242
+ # Check only parent_interframe
243
+ N, A, P, C = _generate_body()
244
+ Pint = ReferenceFrame('Pint')
245
+ Pint.orient_body_fixed(N, (pi / 4, pi, pi / 3), 'xyz')
246
+ PinJoint('J', P, C, q, u, parent_point=N.x, child_point=-C.y,
247
+ parent_interframe=Pint, joint_axis=Pint.x)
248
+ assert _simplify_matrix(N.dcm(A)) - Matrix([
249
+ [-1 / 2, sqrt(3) * cos(q) / 2, -sqrt(3) * sin(q) / 2],
250
+ [sqrt(6) / 4, sqrt(2) * (2 * sin(q) + cos(q)) / 4,
251
+ sqrt(2) * (-sin(q) + 2 * cos(q)) / 4],
252
+ [sqrt(6) / 4, sqrt(2) * (-2 * sin(q) + cos(q)) / 4,
253
+ -sqrt(2) * (sin(q) + 2 * cos(q)) / 4]]) == zeros(3)
254
+ assert A.ang_vel_in(N) == u * Pint.x
255
+ assert C.masscenter.pos_from(P.masscenter) == N.x + A.y
256
+ assert C.masscenter.vel(N) == u * A.z
257
+ assert P.masscenter.vel(Pint) == Vector(0)
258
+ assert C.masscenter.vel(Pint) == u * A.z
259
+ # Check only child_interframe
260
+ N, A, P, C = _generate_body()
261
+ Cint = ReferenceFrame('Cint')
262
+ Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz')
263
+ PinJoint('J', P, C, q, u, parent_point=-N.z, child_point=C.x,
264
+ child_interframe=Cint, joint_axis=P.x + P.z)
265
+ assert _simplify_matrix(N.dcm(A)) == Matrix([
266
+ [-sqrt(2) * sin(q) / 2,
267
+ -sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4,
268
+ sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4],
269
+ [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4,
270
+ (-sqrt(2) + sqrt(6)) * sin(q) / 4],
271
+ [sqrt(2) * sin(q) / 2,
272
+ sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4,
273
+ sqrt(3) * (1 - cos(q)) / 4 + cos(q) / 4 + S(1) / 4]])
274
+ assert A.ang_vel_in(N) == sqrt(2) * u / 2 * N.x + sqrt(2) * u / 2 * N.z
275
+ assert C.masscenter.pos_from(P.masscenter) == - N.z - A.x
276
+ assert C.masscenter.vel(N).simplify() == (
277
+ -sqrt(6) - sqrt(2)) * u / 4 * A.y + (
278
+ -sqrt(2) + sqrt(6)) * u / 4 * A.z
279
+ assert C.masscenter.vel(Cint) == Vector(0)
280
+ # Check combination
281
+ N, A, P, C = _generate_body()
282
+ Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint')
283
+ Pint.orient_body_fixed(N, (-pi / 2, pi, pi / 2), 'xyz')
284
+ Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz')
285
+ PinJoint('J', P, C, q, u, parent_point=N.x - N.y, child_point=-C.z,
286
+ parent_interframe=Pint, child_interframe=Cint,
287
+ joint_axis=Pint.x + Pint.z)
288
+ assert _simplify_matrix(N.dcm(A)) == Matrix([
289
+ [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4,
290
+ (-sqrt(2) + sqrt(6)) * sin(q) / 4],
291
+ [-sqrt(2) * sin(q) / 2,
292
+ -sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4,
293
+ sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4],
294
+ [sqrt(2) * sin(q) / 2,
295
+ sqrt(3) * (cos(q) - 1) / 4 + cos(q) / 4 + S(1) / 4,
296
+ -sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4]])
297
+ assert A.ang_vel_in(N) == sqrt(2) * u / 2 * Pint.x + sqrt(
298
+ 2) * u / 2 * Pint.z
299
+ assert C.masscenter.pos_from(P.masscenter) == N.x - N.y + A.z
300
+ N_v_C = (-sqrt(2) + sqrt(6)) * u / 4 * A.x
301
+ assert C.masscenter.vel(N).simplify() == N_v_C
302
+ assert C.masscenter.vel(Pint).simplify() == N_v_C
303
+ assert C.masscenter.vel(Cint) == Vector(0)
304
+
305
+
306
+ def test_pin_joint_joint_axis():
307
+ q, u = dynamicsymbols('q, u')
308
+ # Check parent as reference
309
+ N, A, P, C, Pint, Cint = _generate_body(True)
310
+ pin = PinJoint('J', P, C, q, u, parent_interframe=Pint,
311
+ child_interframe=Cint, joint_axis=P.y)
312
+ assert pin.joint_axis == P.y
313
+ assert N.dcm(A) == Matrix([[sin(q), 0, cos(q)], [0, -1, 0],
314
+ [cos(q), 0, -sin(q)]])
315
+ # Check parent_interframe as reference
316
+ N, A, P, C, Pint, Cint = _generate_body(True)
317
+ pin = PinJoint('J', P, C, q, u, parent_interframe=Pint,
318
+ child_interframe=Cint, joint_axis=Pint.y)
319
+ assert pin.joint_axis == Pint.y
320
+ assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0],
321
+ [cos(q), 0, sin(q)]])
322
+ # Check combination of joint_axis with interframes supplied as vectors (2x)
323
+ N, A, P, C = _generate_body()
324
+ pin = PinJoint('J', P, C, q, u, parent_interframe=N.z,
325
+ child_interframe=-C.z, joint_axis=N.z)
326
+ assert pin.joint_axis == N.z
327
+ assert N.dcm(A) == Matrix([[-cos(q), -sin(q), 0], [-sin(q), cos(q), 0],
328
+ [0, 0, -1]])
329
+ N, A, P, C = _generate_body()
330
+ pin = PinJoint('J', P, C, q, u, parent_interframe=N.z,
331
+ child_interframe=-C.z, joint_axis=N.x)
332
+ assert pin.joint_axis == N.x
333
+ assert N.dcm(A) == Matrix([[-1, 0, 0], [0, cos(q), sin(q)],
334
+ [0, sin(q), -cos(q)]])
335
+ # Check time varying axis
336
+ N, A, P, C, Pint, Cint = _generate_body(True)
337
+ raises(ValueError, lambda: PinJoint('J', P, C,
338
+ joint_axis=cos(q) * N.x + sin(q) * N.y))
339
+ # Check joint_axis provided in child frame
340
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=C.x))
341
+ # Check some invalid combinations
342
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=P.x + C.y))
343
+ raises(ValueError, lambda: PinJoint(
344
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
345
+ joint_axis=Pint.x + C.y))
346
+ raises(ValueError, lambda: PinJoint(
347
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
348
+ joint_axis=P.x + Cint.y))
349
+ # Check valid special combination
350
+ N, A, P, C, Pint, Cint = _generate_body(True)
351
+ PinJoint('J', P, C, parent_interframe=Pint, child_interframe=Cint,
352
+ joint_axis=Pint.x + P.y)
353
+ # Check invalid zero vector
354
+ raises(Exception, lambda: PinJoint(
355
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
356
+ joint_axis=Vector(0)))
357
+ raises(Exception, lambda: PinJoint(
358
+ 'J', P, C, parent_interframe=Pint, child_interframe=Cint,
359
+ joint_axis=P.y + Pint.y))
360
+
361
+
362
+ def test_pin_joint_arbitrary_axis():
363
+ q, u = dynamicsymbols('q_J, u_J')
364
+
365
+ # When the bodies are attached though masscenters but axes are opposite.
366
+ N, A, P, C = _generate_body()
367
+ PinJoint('J', P, C, child_interframe=-A.x)
368
+
369
+ assert (-A.x).angle_between(N.x) == 0
370
+ assert -A.x.express(N) == N.x
371
+ assert A.dcm(N) == Matrix([[-1, 0, 0],
372
+ [0, -cos(q), -sin(q)],
373
+ [0, -sin(q), cos(q)]])
374
+ assert A.ang_vel_in(N) == u*N.x
375
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
376
+ assert C.masscenter.pos_from(P.masscenter) == 0
377
+ assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == 0
378
+ assert C.masscenter.vel(N) == 0
379
+
380
+ # When axes are different and parent joint is at masscenter but child joint
381
+ # is at a unit vector from child masscenter.
382
+ N, A, P, C = _generate_body()
383
+ PinJoint('J', P, C, child_interframe=A.y, child_point=A.x)
384
+
385
+ assert A.y.angle_between(N.x) == 0 # Axis are aligned
386
+ assert A.y.express(N) == N.x
387
+ assert A.dcm(N) == Matrix([[0, -cos(q), -sin(q)],
388
+ [1, 0, 0],
389
+ [0, -sin(q), cos(q)]])
390
+ assert A.ang_vel_in(N) == u*N.x
391
+ assert A.ang_vel_in(N).express(A) == u * A.y
392
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
393
+ assert A.ang_vel_in(N).cross(A.y) == 0
394
+ assert C.masscenter.vel(N) == u*A.z
395
+ assert C.masscenter.pos_from(P.masscenter) == -A.x
396
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
397
+ cos(q)*N.y + sin(q)*N.z)
398
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
399
+
400
+ # Similar to previous case but wrt parent body
401
+ N, A, P, C = _generate_body()
402
+ PinJoint('J', P, C, parent_interframe=N.y, parent_point=N.x)
403
+
404
+ assert N.y.angle_between(A.x) == 0 # Axis are aligned
405
+ assert N.y.express(A) == A.x
406
+ assert A.dcm(N) == Matrix([[0, 1, 0],
407
+ [-cos(q), 0, sin(q)],
408
+ [sin(q), 0, cos(q)]])
409
+ assert A.ang_vel_in(N) == u*N.y
410
+ assert A.ang_vel_in(N).express(A) == u*A.x
411
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
412
+ angle = A.ang_vel_in(N).angle_between(A.x)
413
+ assert angle.xreplace({u: 1}) == 0
414
+ assert C.masscenter.vel(N) == 0
415
+ assert C.masscenter.pos_from(P.masscenter) == N.x
416
+
417
+ # Both joint pos id defined but different axes
418
+ N, A, P, C = _generate_body()
419
+ PinJoint('J', P, C, parent_point=N.x, child_point=A.x,
420
+ child_interframe=A.x + A.y)
421
+ assert expand_mul(N.x.angle_between(A.x + A.y)) == 0 # Axis are aligned
422
+ assert (A.x + A.y).express(N).simplify() == sqrt(2)*N.x
423
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
424
+ [sqrt(2)/2, -sqrt(2)*cos(q)/2, -sqrt(2)*sin(q)/2],
425
+ [sqrt(2)/2, sqrt(2)*cos(q)/2, sqrt(2)*sin(q)/2],
426
+ [0, -sin(q), cos(q)]])
427
+ assert A.ang_vel_in(N) == u*N.x
428
+ assert (A.ang_vel_in(N).express(A).simplify() ==
429
+ (u*A.x + u*A.y)/sqrt(2))
430
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
431
+ angle = A.ang_vel_in(N).angle_between(A.x + A.y)
432
+ assert angle.xreplace({u: 1}) == 0
433
+ assert C.masscenter.vel(N).simplify() == (u * A.z)/sqrt(2)
434
+ assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
435
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
436
+ (1 - sqrt(2)/2)*N.x + sqrt(2)*cos(q)/2*N.y +
437
+ sqrt(2)*sin(q)/2*N.z)
438
+ assert (C.masscenter.vel(N).express(N).simplify() ==
439
+ -sqrt(2)*u*sin(q)/2*N.y + sqrt(2)*u*cos(q)/2*N.z)
440
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
441
+
442
+ N, A, P, C = _generate_body()
443
+ PinJoint('J', P, C, parent_point=N.x, child_point=A.x,
444
+ child_interframe=A.x + A.y - A.z)
445
+ assert expand_mul(N.x.angle_between(A.x + A.y - A.z)) == 0 # Axis aligned
446
+ assert (A.x + A.y - A.z).express(N).simplify() == sqrt(3)*N.x
447
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
448
+ [sqrt(3)/3, -sqrt(6)*sin(q + pi/4)/3,
449
+ sqrt(6)*cos(q + pi/4)/3],
450
+ [sqrt(3)/3, sqrt(6)*cos(q + pi/12)/3,
451
+ sqrt(6)*sin(q + pi/12)/3],
452
+ [-sqrt(3)/3, sqrt(6)*cos(q + 5*pi/12)/3,
453
+ sqrt(6)*sin(q + 5*pi/12)/3]])
454
+ assert A.ang_vel_in(N) == u*N.x
455
+ assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y -
456
+ u*A.z)/sqrt(3)
457
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
458
+ angle = A.ang_vel_in(N).angle_between(A.x + A.y-A.z)
459
+ assert angle.xreplace({u: 1}) == 0
460
+ assert C.masscenter.vel(N).simplify() == (u*A.y + u*A.z)/sqrt(3)
461
+ assert C.masscenter.pos_from(P.masscenter) == N.x - A.x
462
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
463
+ (1 - sqrt(3)/3)*N.x + sqrt(6)*sin(q + pi/4)/3*N.y -
464
+ sqrt(6)*cos(q + pi/4)/3*N.z)
465
+ assert (C.masscenter.vel(N).express(N).simplify() ==
466
+ sqrt(6)*u*cos(q + pi/4)/3*N.y +
467
+ sqrt(6)*u*sin(q + pi/4)/3*N.z)
468
+ assert C.masscenter.vel(N).angle_between(A.x) == pi/2
469
+
470
+ N, A, P, C = _generate_body()
471
+ m, n = symbols('m n')
472
+ PinJoint('J', P, C, parent_point=m * N.x, child_point=n * A.x,
473
+ child_interframe=A.x + A.y - A.z,
474
+ parent_interframe=N.x - N.y + N.z)
475
+ angle = (N.x - N.y + N.z).angle_between(A.x + A.y - A.z)
476
+ assert expand_mul(angle) == 0 # Axis are aligned
477
+ assert ((A.x-A.y+A.z).express(N).simplify() ==
478
+ (-4*cos(q)/3 - S(1)/3)*N.x + (S(1)/3 - 4*sin(q + pi/6)/3)*N.y +
479
+ (4*cos(q + pi/3)/3 - S(1)/3)*N.z)
480
+ assert _simplify_matrix(A.dcm(N)) == Matrix([
481
+ [S(1)/3 - 2*cos(q)/3, -2*sin(q + pi/6)/3 - S(1)/3,
482
+ 2*cos(q + pi/3)/3 + S(1)/3],
483
+ [2*cos(q + pi/3)/3 + S(1)/3, 2*cos(q)/3 - S(1)/3,
484
+ 2*sin(q + pi/6)/3 + S(1)/3],
485
+ [-2*sin(q + pi/6)/3 - S(1)/3, 2*cos(q + pi/3)/3 + S(1)/3,
486
+ 2*cos(q)/3 - S(1)/3]])
487
+ assert A.ang_vel_in(N) == (u*N.x - u*N.y + u*N.z)/sqrt(3)
488
+ assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y -
489
+ u*A.z)/sqrt(3)
490
+ assert A.ang_vel_in(N).magnitude() == sqrt(u**2)
491
+ angle = A.ang_vel_in(N).angle_between(A.x+A.y-A.z)
492
+ assert angle.xreplace({u: 1}) == 0
493
+ assert (C.masscenter.vel(N).simplify() ==
494
+ sqrt(3)*n*u/3*A.y + sqrt(3)*n*u/3*A.z)
495
+ assert C.masscenter.pos_from(P.masscenter) == m*N.x - n*A.x
496
+ assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() ==
497
+ (m + n*(2*cos(q) - 1)/3)*N.x + n*(2*sin(q + pi/6) +
498
+ 1)/3*N.y - n*(2*cos(q + pi/3) + 1)/3*N.z)
499
+ assert (C.masscenter.vel(N).express(N).simplify() ==
500
+ - 2*n*u*sin(q)/3*N.x + 2*n*u*cos(q + pi/6)/3*N.y +
501
+ 2*n*u*sin(q + pi/3)/3*N.z)
502
+ assert C.masscenter.vel(N).dot(N.x - N.y + N.z).simplify() == 0
503
+
504
+
505
+ def test_create_aligned_frame_pi():
506
+ N, A, P, C = _generate_body()
507
+ f = Joint._create_aligned_interframe(P, -P.x, P.x)
508
+ assert f.z == P.z
509
+ f = Joint._create_aligned_interframe(P, -P.y, P.y)
510
+ assert f.x == P.x
511
+ f = Joint._create_aligned_interframe(P, -P.z, P.z)
512
+ assert f.y == P.y
513
+ f = Joint._create_aligned_interframe(P, -P.x - P.y, P.x + P.y)
514
+ assert f.z == P.z
515
+ f = Joint._create_aligned_interframe(P, -P.y - P.z, P.y + P.z)
516
+ assert f.x == P.x
517
+ f = Joint._create_aligned_interframe(P, -P.x - P.z, P.x + P.z)
518
+ assert f.y == P.y
519
+ f = Joint._create_aligned_interframe(P, -P.x - P.y - P.z, P.x + P.y + P.z)
520
+ assert f.y - f.z == P.y - P.z
521
+
522
+
523
+ def test_pin_joint_axis():
524
+ q, u = dynamicsymbols('q u')
525
+ # Test default joint axis
526
+ N, A, P, C, Pint, Cint = _generate_body(True)
527
+ J = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint)
528
+ assert J.joint_axis == Pint.x
529
+ # Test for the same joint axis expressed in different frames
530
+ N_R_A = Matrix([[0, sin(q), cos(q)],
531
+ [0, -cos(q), sin(q)],
532
+ [1, 0, 0]])
533
+ N, A, P, C, Pint, Cint = _generate_body(True)
534
+ PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint,
535
+ joint_axis=N.z)
536
+ assert N.dcm(A) == N_R_A
537
+ N, A, P, C, Pint, Cint = _generate_body(True)
538
+ PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint,
539
+ joint_axis=-Pint.z)
540
+ assert N.dcm(A) == N_R_A
541
+ # Test time varying joint axis
542
+ N, A, P, C, Pint, Cint = _generate_body(True)
543
+ raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=q * N.z))
544
+
545
+
546
+ def test_locate_joint_pos():
547
+ # Test Vector and default
548
+ N, A, P, C = _generate_body()
549
+ joint = PinJoint('J', P, C, parent_point=N.y + N.z)
550
+ assert joint.parent_point.name == 'J_P_joint'
551
+ assert joint.parent_point.pos_from(P.masscenter) == N.y + N.z
552
+ assert joint.child_point == C.masscenter
553
+ # Test Point objects
554
+ N, A, P, C = _generate_body()
555
+ parent_point = P.masscenter.locatenew('p', N.y + N.z)
556
+ joint = PinJoint('J', P, C, parent_point=parent_point,
557
+ child_point=C.masscenter)
558
+ assert joint.parent_point == parent_point
559
+ assert joint.child_point == C.masscenter
560
+ # Check invalid type
561
+ N, A, P, C = _generate_body()
562
+ raises(TypeError,
563
+ lambda: PinJoint('J', P, C, parent_point=N.x.to_matrix(N)))
564
+ # Test time varying positions
565
+ q = dynamicsymbols('q')
566
+ N, A, P, C = _generate_body()
567
+ raises(ValueError, lambda: PinJoint('J', P, C, parent_point=q * N.x))
568
+ N, A, P, C = _generate_body()
569
+ child_point = C.masscenter.locatenew('p', q * A.y)
570
+ raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point))
571
+ # Test undefined position
572
+ child_point = Point('p')
573
+ raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point))
574
+
575
+
576
+ def test_locate_joint_frame():
577
+ # Test rotated frame and default
578
+ N, A, P, C = _generate_body()
579
+ parent_interframe = ReferenceFrame('int_frame')
580
+ parent_interframe.orient_axis(N, N.z, 1)
581
+ joint = PinJoint('J', P, C, parent_interframe=parent_interframe)
582
+ assert joint.parent_interframe == parent_interframe
583
+ assert joint.parent_interframe.ang_vel_in(N) == 0
584
+ assert joint.child_interframe == A
585
+ # Test time varying orientations
586
+ q = dynamicsymbols('q')
587
+ N, A, P, C = _generate_body()
588
+ parent_interframe = ReferenceFrame('int_frame')
589
+ parent_interframe.orient_axis(N, N.z, q)
590
+ raises(ValueError,
591
+ lambda: PinJoint('J', P, C, parent_interframe=parent_interframe))
592
+ # Test undefined frame
593
+ N, A, P, C = _generate_body()
594
+ child_interframe = ReferenceFrame('int_frame')
595
+ child_interframe.orient_axis(N, N.z, 1) # Defined with respect to parent
596
+ raises(ValueError,
597
+ lambda: PinJoint('J', P, C, child_interframe=child_interframe))
598
+
599
+
600
+ def test_sliding_joint():
601
+ _, _, P, C = _generate_body()
602
+ q, u = dynamicsymbols('q_S, u_S')
603
+ S = PrismaticJoint('S', P, C)
604
+ assert S.name == 'S'
605
+ assert S.parent == P
606
+ assert S.child == C
607
+ assert S.coordinates == Matrix([q])
608
+ assert S.speeds == Matrix([u])
609
+ assert S.kdes == Matrix([u - q.diff(t)])
610
+ assert S.joint_axis == P.frame.x
611
+ assert S.child_point.pos_from(C.masscenter) == Vector(0)
612
+ assert S.parent_point.pos_from(P.masscenter) == Vector(0)
613
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.x
614
+ assert P.masscenter.pos_from(C.masscenter) == - q * P.frame.x
615
+ assert C.masscenter.vel(P.frame) == u * P.frame.x
616
+ assert P.ang_vel_in(C) == 0
617
+ assert C.ang_vel_in(P) == 0
618
+ assert S.__str__() == 'PrismaticJoint: S parent: P child: C'
619
+
620
+ N, A, P, C = _generate_body()
621
+ l, m = symbols('l m')
622
+ Pint = ReferenceFrame('P_int')
623
+ Pint.orient_axis(P.frame, P.y, pi / 2)
624
+ S = PrismaticJoint('S', P, C, parent_point=l * P.frame.x,
625
+ child_point=m * C.frame.y, joint_axis=P.frame.z,
626
+ parent_interframe=Pint)
627
+
628
+ assert S.joint_axis == P.frame.z
629
+ assert S.child_point.pos_from(C.masscenter) == m * C.frame.y
630
+ assert S.parent_point.pos_from(P.masscenter) == l * P.frame.x
631
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z
632
+ assert P.masscenter.pos_from(C.masscenter) == - l*N.x - q*N.z + m*A.y
633
+ assert C.masscenter.vel(P.frame) == u * P.frame.z
634
+ assert P.masscenter.vel(Pint) == Vector(0)
635
+ assert C.ang_vel_in(P) == 0
636
+ assert P.ang_vel_in(C) == 0
637
+
638
+ _, _, P, C = _generate_body()
639
+ Pint = ReferenceFrame('P_int')
640
+ Pint.orient_axis(P.frame, P.y, pi / 2)
641
+ S = PrismaticJoint('S', P, C, parent_point=l * P.frame.z,
642
+ child_point=m * C.frame.x, joint_axis=P.frame.z,
643
+ parent_interframe=Pint)
644
+ assert S.joint_axis == P.frame.z
645
+ assert S.child_point.pos_from(C.masscenter) == m * C.frame.x
646
+ assert S.parent_point.pos_from(P.masscenter) == l * P.frame.z
647
+ assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z
648
+ assert P.masscenter.pos_from(C.masscenter) == (-l - q)*P.frame.z + m*C.frame.x
649
+ assert C.masscenter.vel(P.frame) == u * P.frame.z
650
+ assert C.ang_vel_in(P) == 0
651
+ assert P.ang_vel_in(C) == 0
652
+
653
+
654
+ def test_sliding_joint_arbitrary_axis():
655
+ q, u = dynamicsymbols('q_S, u_S')
656
+
657
+ N, A, P, C = _generate_body()
658
+ PrismaticJoint('S', P, C, child_interframe=-A.x)
659
+
660
+ assert (-A.x).angle_between(N.x) == 0
661
+ assert -A.x.express(N) == N.x
662
+ assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])
663
+ assert C.masscenter.pos_from(P.masscenter) == q * N.x
664
+ assert C.masscenter.pos_from(P.masscenter).express(A).simplify() == -q * A.x
665
+ assert C.masscenter.vel(N) == u * N.x
666
+ assert C.masscenter.vel(N).express(A) == -u * A.x
667
+ assert A.ang_vel_in(N) == 0
668
+ assert N.ang_vel_in(A) == 0
669
+
670
+ #When axes are different and parent joint is at masscenter but child joint is at a unit vector from
671
+ #child masscenter.
672
+ N, A, P, C = _generate_body()
673
+ PrismaticJoint('S', P, C, child_interframe=A.y, child_point=A.x)
674
+
675
+ assert A.y.angle_between(N.x) == 0 #Axis are aligned
676
+ assert A.y.express(N) == N.x
677
+ assert A.dcm(N) == Matrix([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
678
+ assert C.masscenter.vel(N) == u * N.x
679
+ assert C.masscenter.vel(N).express(A) == u * A.y
680
+ assert C.masscenter.pos_from(P.masscenter) == q*N.x - A.x
681
+ assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == q*N.x + N.y
682
+ assert A.ang_vel_in(N) == 0
683
+ assert N.ang_vel_in(A) == 0
684
+
685
+ #Similar to previous case but wrt parent body
686
+ N, A, P, C = _generate_body()
687
+ PrismaticJoint('S', P, C, parent_interframe=N.y, parent_point=N.x)
688
+
689
+ assert N.y.angle_between(A.x) == 0 #Axis are aligned
690
+ assert N.y.express(A) == A.x
691
+ assert A.dcm(N) == Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 1]])
692
+ assert C.masscenter.vel(N) == u * N.y
693
+ assert C.masscenter.vel(N).express(A) == u * A.x
694
+ assert C.masscenter.pos_from(P.masscenter) == N.x + q*N.y
695
+ assert A.ang_vel_in(N) == 0
696
+ assert N.ang_vel_in(A) == 0
697
+
698
+ #Both joint pos is defined but different axes
699
+ N, A, P, C = _generate_body()
700
+ PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x,
701
+ child_interframe=A.x + A.y)
702
+ assert N.x.angle_between(A.x + A.y) == 0 #Axis are aligned
703
+ assert (A.x + A.y).express(N) == sqrt(2)*N.x
704
+ assert A.dcm(N) == Matrix([[sqrt(2)/2, -sqrt(2)/2, 0], [sqrt(2)/2, sqrt(2)/2, 0], [0, 0, 1]])
705
+ assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x
706
+ assert C.masscenter.pos_from(P.masscenter).express(N) == (q - sqrt(2)/2 + 1)*N.x + sqrt(2)/2*N.y
707
+ assert C.masscenter.vel(N).express(A) == u * (A.x + A.y)/sqrt(2)
708
+ assert C.masscenter.vel(N) == u*N.x
709
+ assert A.ang_vel_in(N) == 0
710
+ assert N.ang_vel_in(A) == 0
711
+
712
+ N, A, P, C = _generate_body()
713
+ PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x,
714
+ child_interframe=A.x + A.y - A.z)
715
+ assert N.x.angle_between(A.x + A.y - A.z) == 0 #Axis are aligned
716
+ assert (A.x + A.y - A.z).express(N) == sqrt(3)*N.x
717
+ assert _simplify_matrix(A.dcm(N)) == Matrix([[sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3],
718
+ [sqrt(3)/3, sqrt(3)/6 + S(1)/2, S(1)/2 - sqrt(3)/6],
719
+ [-sqrt(3)/3, S(1)/2 - sqrt(3)/6, sqrt(3)/6 + S(1)/2]])
720
+ assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x
721
+ assert C.masscenter.pos_from(P.masscenter).express(N) == \
722
+ (q - sqrt(3)/3 + 1)*N.x + sqrt(3)/3*N.y - sqrt(3)/3*N.z
723
+ assert C.masscenter.vel(N) == u*N.x
724
+ assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z
725
+ assert A.ang_vel_in(N) == 0
726
+ assert N.ang_vel_in(A) == 0
727
+
728
+ N, A, P, C = _generate_body()
729
+ m, n = symbols('m n')
730
+ PrismaticJoint('S', P, C, parent_point=m*N.x, child_point=n*A.x,
731
+ child_interframe=A.x + A.y - A.z,
732
+ parent_interframe=N.x - N.y + N.z)
733
+ # 0 angle means that the axis are aligned
734
+ assert (N.x-N.y+N.z).angle_between(A.x+A.y-A.z).simplify() == 0
735
+ assert (A.x+A.y-A.z).express(N) == N.x - N.y + N.z
736
+ assert _simplify_matrix(A.dcm(N)) == Matrix([[-S(1)/3, -S(2)/3, S(2)/3],
737
+ [S(2)/3, S(1)/3, S(2)/3],
738
+ [-S(2)/3, S(2)/3, S(1)/3]])
739
+ assert C.masscenter.pos_from(P.masscenter) == \
740
+ (m + sqrt(3)*q/3)*N.x - sqrt(3)*q/3*N.y + sqrt(3)*q/3*N.z - n*A.x
741
+ assert C.masscenter.pos_from(P.masscenter).express(N) == \
742
+ (m + n/3 + sqrt(3)*q/3)*N.x + (2*n/3 - sqrt(3)*q/3)*N.y + (-2*n/3 + sqrt(3)*q/3)*N.z
743
+ assert C.masscenter.vel(N) == sqrt(3)*u/3*N.x - sqrt(3)*u/3*N.y + sqrt(3)*u/3*N.z
744
+ assert C.masscenter.vel(N).express(A) == sqrt(3)*u/3*A.x + sqrt(3)*u/3*A.y - sqrt(3)*u/3*A.z
745
+ assert A.ang_vel_in(N) == 0
746
+ assert N.ang_vel_in(A) == 0
747
+
748
+
749
+ def test_cylindrical_joint():
750
+ N, A, P, C = _generate_body()
751
+ q0_def, q1_def, u0_def, u1_def = dynamicsymbols('q0:2_J, u0:2_J')
752
+ Cj = CylindricalJoint('J', P, C)
753
+ assert Cj.name == 'J'
754
+ assert Cj.parent == P
755
+ assert Cj.child == C
756
+ assert Cj.coordinates == Matrix([q0_def, q1_def])
757
+ assert Cj.speeds == Matrix([u0_def, u1_def])
758
+ assert Cj.rotation_coordinate == q0_def
759
+ assert Cj.translation_coordinate == q1_def
760
+ assert Cj.rotation_speed == u0_def
761
+ assert Cj.translation_speed == u1_def
762
+ assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t)])
763
+ assert Cj.joint_axis == N.x
764
+ assert Cj.child_point.pos_from(C.masscenter) == Vector(0)
765
+ assert Cj.parent_point.pos_from(P.masscenter) == Vector(0)
766
+ assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.x
767
+ assert C.masscenter.pos_from(P.masscenter) == q1_def * N.x
768
+ assert Cj.child_point.vel(N) == u1_def * N.x
769
+ assert A.ang_vel_in(N) == u0_def * N.x
770
+ assert Cj.parent_interframe == N
771
+ assert Cj.child_interframe == A
772
+ assert Cj.__str__() == 'CylindricalJoint: J parent: P child: C'
773
+
774
+ q0, q1, u0, u1 = dynamicsymbols('q0:2, u0:2')
775
+ l, m = symbols('l, m')
776
+ N, A, P, C, Pint, Cint = _generate_body(True)
777
+ Cj = CylindricalJoint('J', P, C, rotation_coordinate=q0, rotation_speed=u0,
778
+ translation_speed=u1, parent_point=m * N.x,
779
+ child_point=l * A.y, parent_interframe=Pint,
780
+ child_interframe=Cint, joint_axis=2 * N.z)
781
+ assert Cj.coordinates == Matrix([q0, q1_def])
782
+ assert Cj.speeds == Matrix([u0, u1])
783
+ assert Cj.rotation_coordinate == q0
784
+ assert Cj.translation_coordinate == q1_def
785
+ assert Cj.rotation_speed == u0
786
+ assert Cj.translation_speed == u1
787
+ assert Cj.kdes == Matrix([u0 - q0.diff(t), u1 - q1_def.diff(t)])
788
+ assert Cj.joint_axis == 2 * N.z
789
+ assert Cj.child_point.pos_from(C.masscenter) == l * A.y
790
+ assert Cj.parent_point.pos_from(P.masscenter) == m * N.x
791
+ assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.z
792
+ assert C.masscenter.pos_from(
793
+ P.masscenter) == m * N.x + q1_def * N.z - l * A.y
794
+ assert C.masscenter.vel(N) == u1 * N.z - u0 * l * A.z
795
+ assert A.ang_vel_in(N) == u0 * N.z
796
+
797
+
798
+ def test_planar_joint():
799
+ N, A, P, C = _generate_body()
800
+ q0_def, q1_def, q2_def = dynamicsymbols('q0:3_J')
801
+ u0_def, u1_def, u2_def = dynamicsymbols('u0:3_J')
802
+ Cj = PlanarJoint('J', P, C)
803
+ assert Cj.name == 'J'
804
+ assert Cj.parent == P
805
+ assert Cj.child == C
806
+ assert Cj.coordinates == Matrix([q0_def, q1_def, q2_def])
807
+ assert Cj.speeds == Matrix([u0_def, u1_def, u2_def])
808
+ assert Cj.rotation_coordinate == q0_def
809
+ assert Cj.planar_coordinates == Matrix([q1_def, q2_def])
810
+ assert Cj.rotation_speed == u0_def
811
+ assert Cj.planar_speeds == Matrix([u1_def, u2_def])
812
+ assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t),
813
+ u2_def - q2_def.diff(t)])
814
+ assert Cj.rotation_axis == N.x
815
+ assert Cj.planar_vectors == [N.y, N.z]
816
+ assert Cj.child_point.pos_from(C.masscenter) == Vector(0)
817
+ assert Cj.parent_point.pos_from(P.masscenter) == Vector(0)
818
+ r_P_C = q1_def * N.y + q2_def * N.z
819
+ assert Cj.parent_point.pos_from(Cj.child_point) == -r_P_C
820
+ assert C.masscenter.pos_from(P.masscenter) == r_P_C
821
+ assert Cj.child_point.vel(N) == u1_def * N.y + u2_def * N.z
822
+ assert A.ang_vel_in(N) == u0_def * N.x
823
+ assert Cj.parent_interframe == N
824
+ assert Cj.child_interframe == A
825
+ assert Cj.__str__() == 'PlanarJoint: J parent: P child: C'
826
+
827
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
828
+ l, m = symbols('l, m')
829
+ N, A, P, C, Pint, Cint = _generate_body(True)
830
+ Cj = PlanarJoint('J', P, C, rotation_coordinate=q0,
831
+ planar_coordinates=[q1, q2], planar_speeds=[u1, u2],
832
+ parent_point=m * N.x, child_point=l * A.y,
833
+ parent_interframe=Pint, child_interframe=Cint)
834
+ assert Cj.coordinates == Matrix([q0, q1, q2])
835
+ assert Cj.speeds == Matrix([u0_def, u1, u2])
836
+ assert Cj.rotation_coordinate == q0
837
+ assert Cj.planar_coordinates == Matrix([q1, q2])
838
+ assert Cj.rotation_speed == u0_def
839
+ assert Cj.planar_speeds == Matrix([u1, u2])
840
+ assert Cj.kdes == Matrix([u0_def - q0.diff(t), u1 - q1.diff(t),
841
+ u2 - q2.diff(t)])
842
+ assert Cj.rotation_axis == Pint.x
843
+ assert Cj.planar_vectors == [Pint.y, Pint.z]
844
+ assert Cj.child_point.pos_from(C.masscenter) == l * A.y
845
+ assert Cj.parent_point.pos_from(P.masscenter) == m * N.x
846
+ assert Cj.parent_point.pos_from(Cj.child_point) == q1 * N.y + q2 * N.z
847
+ assert C.masscenter.pos_from(
848
+ P.masscenter) == m * N.x - q1 * N.y - q2 * N.z - l * A.y
849
+ assert C.masscenter.vel(N) == -u1 * N.y - u2 * N.z + u0_def * l * A.x
850
+ assert A.ang_vel_in(N) == u0_def * N.x
851
+
852
+
853
+ def test_planar_joint_advanced():
854
+ # Tests whether someone is able to just specify two normals, which will form
855
+ # the rotation axis seen from the parent and child body.
856
+ # This specific example is a block on a slope, which has that same slope of
857
+ # 30 degrees, so in the zero configuration the frames of the parent and
858
+ # child are actually aligned.
859
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
860
+ l1, l2 = symbols('l1:3')
861
+ N, A, P, C = _generate_body()
862
+ J = PlanarJoint('J', P, C, q0, [q1, q2], u0, [u1, u2],
863
+ parent_point=l1 * N.z,
864
+ child_point=-l2 * C.z,
865
+ parent_interframe=N.z + N.y / sqrt(3),
866
+ child_interframe=A.z + A.y / sqrt(3))
867
+ assert J.rotation_axis.express(N) == (N.z + N.y / sqrt(3)).normalize()
868
+ assert J.rotation_axis.express(A) == (A.z + A.y / sqrt(3)).normalize()
869
+ assert J.rotation_axis.angle_between(N.z) == pi / 6
870
+ assert N.dcm(A).xreplace({q0: 0, q1: 0, q2: 0}) == eye(3)
871
+ N_R_A = Matrix([
872
+ [cos(q0), -sqrt(3) * sin(q0) / 2, sin(q0) / 2],
873
+ [sqrt(3) * sin(q0) / 2, 3 * cos(q0) / 4 + 1 / 4,
874
+ sqrt(3) * (1 - cos(q0)) / 4],
875
+ [-sin(q0) / 2, sqrt(3) * (1 - cos(q0)) / 4, cos(q0) / 4 + 3 / 4]])
876
+ # N.dcm(A) == N_R_A did not work
877
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
878
+
879
+
880
+ def test_spherical_joint():
881
+ N, A, P, C = _generate_body()
882
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3_S, u0:3_S')
883
+ S = SphericalJoint('S', P, C)
884
+ assert S.name == 'S'
885
+ assert S.parent == P
886
+ assert S.child == C
887
+ assert S.coordinates == Matrix([q0, q1, q2])
888
+ assert S.speeds == Matrix([u0, u1, u2])
889
+ assert S.kdes == Matrix([u0 - q0.diff(t), u1 - q1.diff(t), u2 - q2.diff(t)])
890
+ assert S.child_point.pos_from(C.masscenter) == Vector(0)
891
+ assert S.parent_point.pos_from(P.masscenter) == Vector(0)
892
+ assert S.parent_point.pos_from(S.child_point) == Vector(0)
893
+ assert P.masscenter.pos_from(C.masscenter) == Vector(0)
894
+ assert C.masscenter.vel(N) == Vector(0)
895
+ assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + (
896
+ u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + (
897
+ -u0 * sin(q1) - u2) * A.z
898
+ assert C.ang_vel_in(P) == (u0 * cos(q1) * cos(q2) + u1 * sin(q2)) * A.x + (
899
+ -u0 * sin(q2) * cos(q1) + u1 * cos(q2)) * A.y + (
900
+ u0 * sin(q1) + u2) * A.z
901
+ assert S.__str__() == 'SphericalJoint: S parent: P child: C'
902
+ assert S._rot_type == 'BODY'
903
+ assert S._rot_order == 123
904
+ assert S._amounts is None
905
+
906
+
907
+ def test_spherical_joint_speeds_as_derivative_terms():
908
+ # This tests checks whether the system remains valid if the user chooses to
909
+ # pass the derivative of the generalized coordinates as generalized speeds
910
+ q0, q1, q2 = dynamicsymbols('q0:3')
911
+ u0, u1, u2 = dynamicsymbols('q0:3', 1)
912
+ N, A, P, C = _generate_body()
913
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2])
914
+ assert S.coordinates == Matrix([q0, q1, q2])
915
+ assert S.speeds == Matrix([u0, u1, u2])
916
+ assert S.kdes == Matrix([0, 0, 0])
917
+ assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + (
918
+ u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + (
919
+ -u0 * sin(q1) - u2) * A.z
920
+
921
+
922
+ def test_spherical_joint_coords():
923
+ q0s, q1s, q2s, u0s, u1s, u2s = dynamicsymbols('q0:3_S, u0:3_S')
924
+ q0, q1, q2, q3, u0, u1, u2, u4 = dynamicsymbols('q0:4, u0:4')
925
+ # Test coordinates as list
926
+ N, A, P, C = _generate_body()
927
+ S = SphericalJoint('S', P, C, [q0, q1, q2], [u0, u1, u2])
928
+ assert S.coordinates == Matrix([q0, q1, q2])
929
+ assert S.speeds == Matrix([u0, u1, u2])
930
+ # Test coordinates as Matrix
931
+ N, A, P, C = _generate_body()
932
+ S = SphericalJoint('S', P, C, Matrix([q0, q1, q2]),
933
+ Matrix([u0, u1, u2]))
934
+ assert S.coordinates == Matrix([q0, q1, q2])
935
+ assert S.speeds == Matrix([u0, u1, u2])
936
+ # Test too few generalized coordinates
937
+ N, A, P, C = _generate_body()
938
+ raises(ValueError,
939
+ lambda: SphericalJoint('S', P, C, Matrix([q0, q1]), Matrix([u0])))
940
+ # Test too many generalized coordinates
941
+ raises(ValueError, lambda: SphericalJoint(
942
+ 'S', P, C, Matrix([q0, q1, q2, q3]), Matrix([u0, u1, u2])))
943
+ raises(ValueError, lambda: SphericalJoint(
944
+ 'S', P, C, Matrix([q0, q1, q2]), Matrix([u0, u1, u2, u4])))
945
+
946
+
947
+ def test_spherical_joint_orient_body():
948
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
949
+ N_R_A = Matrix([
950
+ [-sin(q1), -sin(q2) * cos(q1), cos(q1) * cos(q2)],
951
+ [-sin(q0) * cos(q1), sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2),
952
+ -sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0)],
953
+ [cos(q0) * cos(q1), -sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0),
954
+ -sin(q0) * sin(q2) + sin(q1) * cos(q0) * cos(q2)]])
955
+ N_w_A = Matrix([[-u0 * sin(q1) - u2],
956
+ [-u0 * sin(q2) * cos(q1) + u1 * cos(q2)],
957
+ [u0 * cos(q1) * cos(q2) + u1 * sin(q2)]])
958
+ N_v_Co = Matrix([
959
+ [-sqrt(2) * (u0 * cos(q2 + pi / 4) * cos(q1) + u1 * sin(q2 + pi / 4))],
960
+ [-u0 * sin(q1) - u2], [-u0 * sin(q1) - u2]])
961
+ # Test default rot_type='BODY', rot_order=123
962
+ N, A, P, C, Pint, Cint = _generate_body(True)
963
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
964
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
965
+ parent_interframe=Pint, child_interframe=Cint,
966
+ rot_type='body', rot_order=123)
967
+ assert S._rot_type.upper() == 'BODY'
968
+ assert S._rot_order == 123
969
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
970
+ assert A.ang_vel_in(N).to_matrix(A) == N_w_A
971
+ assert C.masscenter.vel(N).to_matrix(A) == N_v_Co
972
+ # Test change of amounts
973
+ N, A, P, C, Pint, Cint = _generate_body(True)
974
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
975
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
976
+ parent_interframe=Pint, child_interframe=Cint,
977
+ rot_type='BODY', amounts=(q1, q0, q2), rot_order=123)
978
+ switch_order = lambda expr: expr.xreplace(
979
+ {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2})
980
+ assert S._rot_type.upper() == 'BODY'
981
+ assert S._rot_order == 123
982
+ assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3)
983
+ assert A.ang_vel_in(N).to_matrix(A) == switch_order(N_w_A)
984
+ assert C.masscenter.vel(N).to_matrix(A) == switch_order(N_v_Co)
985
+ # Test different rot_order
986
+ N, A, P, C, Pint, Cint = _generate_body(True)
987
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
988
+ parent_point=N.x + N.y, child_point=-A.y + A.z,
989
+ parent_interframe=Pint, child_interframe=Cint,
990
+ rot_type='BodY', rot_order='yxz')
991
+ assert S._rot_type.upper() == 'BODY'
992
+ assert S._rot_order == 'yxz'
993
+ assert _simplify_matrix(N.dcm(A) - Matrix([
994
+ [-sin(q0) * cos(q1), sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0),
995
+ sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)],
996
+ [-sin(q1), -cos(q1) * cos(q2), -sin(q2) * cos(q1)],
997
+ [cos(q0) * cos(q1), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
998
+ sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0)]])) == zeros(3)
999
+ assert A.ang_vel_in(N).to_matrix(A) == Matrix([
1000
+ [u0 * sin(q1) - u2], [u0 * cos(q1) * cos(q2) - u1 * sin(q2)],
1001
+ [u0 * sin(q2) * cos(q1) + u1 * cos(q2)]])
1002
+ assert C.masscenter.vel(N).to_matrix(A) == Matrix([
1003
+ [-sqrt(2) * (u0 * sin(q2 + pi / 4) * cos(q1) + u1 * cos(q2 + pi / 4))],
1004
+ [u0 * sin(q1) - u2], [u0 * sin(q1) - u2]])
1005
+
1006
+
1007
+ def test_spherical_joint_orient_space():
1008
+ q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3')
1009
+ N_R_A = Matrix([
1010
+ [-sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
1011
+ sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0), cos(q1) * cos(q2)],
1012
+ [-sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0),
1013
+ -sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2), -sin(q2) * cos(q1)],
1014
+ [cos(q0) * cos(q1), -sin(q0) * cos(q1), sin(q1)]])
1015
+ N_w_A = Matrix([
1016
+ [u1 * sin(q0) - u2 * cos(q0) * cos(q1)],
1017
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)], [u0 - u2 * sin(q1)]])
1018
+ N_v_Co = Matrix([
1019
+ [u0 - u2 * sin(q1)], [u0 - u2 * sin(q1)],
1020
+ [sqrt(2) * (-u1 * sin(q0 + pi / 4) + u2 * cos(q0 + pi / 4) * cos(q1))]])
1021
+ # Test default rot_type='BODY', rot_order=123
1022
+ N, A, P, C, Pint, Cint = _generate_body(True)
1023
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1024
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1025
+ parent_interframe=Pint, child_interframe=Cint,
1026
+ rot_type='space', rot_order=123)
1027
+ assert S._rot_type.upper() == 'SPACE'
1028
+ assert S._rot_order == 123
1029
+ assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3)
1030
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == N_w_A
1031
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == N_v_Co
1032
+ # Test change of amounts
1033
+ switch_order = lambda expr: expr.xreplace(
1034
+ {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2})
1035
+ N, A, P, C, Pint, Cint = _generate_body(True)
1036
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1037
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1038
+ parent_interframe=Pint, child_interframe=Cint,
1039
+ rot_type='SPACE', amounts=(q1, q0, q2), rot_order=123)
1040
+ assert S._rot_type.upper() == 'SPACE'
1041
+ assert S._rot_order == 123
1042
+ assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3)
1043
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == switch_order(N_w_A)
1044
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == switch_order(N_v_Co)
1045
+ # Test different rot_order
1046
+ N, A, P, C, Pint, Cint = _generate_body(True)
1047
+ S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2],
1048
+ parent_point=N.x + N.z, child_point=-A.x + A.y,
1049
+ parent_interframe=Pint, child_interframe=Cint,
1050
+ rot_type='SPaCe', rot_order='zxy')
1051
+ assert S._rot_type.upper() == 'SPACE'
1052
+ assert S._rot_order == 'zxy'
1053
+ assert _simplify_matrix(N.dcm(A) - Matrix([
1054
+ [-sin(q2) * cos(q1), -sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0),
1055
+ sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)],
1056
+ [-sin(q1), -cos(q0) * cos(q1), -sin(q0) * cos(q1)],
1057
+ [cos(q1) * cos(q2), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2),
1058
+ -sin(q0) * sin(q1) * cos(q2) + sin(q2) * cos(q0)]]))
1059
+ assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A) - Matrix([
1060
+ [-u0 + u2 * sin(q1)], [-u1 * sin(q0) + u2 * cos(q0) * cos(q1)],
1061
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)]])) == zeros(3, 1)
1062
+ assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A) - Matrix([
1063
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)],
1064
+ [u1 * cos(q0) + u2 * sin(q0) * cos(q1)],
1065
+ [u0 + u1 * sin(q0) - u2 * sin(q1) -
1066
+ u2 * cos(q0) * cos(q1)]])) == zeros(3, 1)
1067
+
1068
+
1069
+ def test_weld_joint():
1070
+ _, _, P, C = _generate_body()
1071
+ W = WeldJoint('W', P, C)
1072
+ assert W.name == 'W'
1073
+ assert W.parent == P
1074
+ assert W.child == C
1075
+ assert W.coordinates == Matrix()
1076
+ assert W.speeds == Matrix()
1077
+ assert W.kdes == Matrix(1, 0, []).T
1078
+ assert P.dcm(C) == eye(3)
1079
+ assert W.child_point.pos_from(C.masscenter) == Vector(0)
1080
+ assert W.parent_point.pos_from(P.masscenter) == Vector(0)
1081
+ assert W.parent_point.pos_from(W.child_point) == Vector(0)
1082
+ assert P.masscenter.pos_from(C.masscenter) == Vector(0)
1083
+ assert C.masscenter.vel(P.frame) == Vector(0)
1084
+ assert P.ang_vel_in(C) == 0
1085
+ assert C.ang_vel_in(P) == 0
1086
+ assert W.__str__() == 'WeldJoint: W parent: P child: C'
1087
+
1088
+ N, A, P, C = _generate_body()
1089
+ l, m = symbols('l m')
1090
+ Pint = ReferenceFrame('P_int')
1091
+ Pint.orient_axis(P.frame, P.y, pi / 2)
1092
+ W = WeldJoint('W', P, C, parent_point=l * P.frame.x,
1093
+ child_point=m * C.frame.y, parent_interframe=Pint)
1094
+
1095
+ assert W.child_point.pos_from(C.masscenter) == m * C.frame.y
1096
+ assert W.parent_point.pos_from(P.masscenter) == l * P.frame.x
1097
+ assert W.parent_point.pos_from(W.child_point) == Vector(0)
1098
+ assert P.masscenter.pos_from(C.masscenter) == - l * N.x + m * A.y
1099
+ assert C.masscenter.vel(P.frame) == Vector(0)
1100
+ assert P.masscenter.vel(Pint) == Vector(0)
1101
+ assert C.ang_vel_in(P) == 0
1102
+ assert P.ang_vel_in(C) == 0
1103
+ assert P.x == A.z
1104
+
1105
+ JointsMethod(P, W) # Tests #10770
1106
+
1107
+
1108
+ def test_deprecated_parent_child_axis():
1109
+ q, u = dynamicsymbols('q_J, u_J')
1110
+ N, A, P, C = _generate_body()
1111
+ with warns_deprecated_sympy():
1112
+ PinJoint('J', P, C, child_axis=-A.x)
1113
+ assert (-A.x).angle_between(N.x) == 0
1114
+ assert -A.x.express(N) == N.x
1115
+ assert A.dcm(N) == Matrix([[-1, 0, 0],
1116
+ [0, -cos(q), -sin(q)],
1117
+ [0, -sin(q), cos(q)]])
1118
+ assert A.ang_vel_in(N) == u * N.x
1119
+ assert A.ang_vel_in(N).magnitude() == sqrt(u ** 2)
1120
+
1121
+ N, A, P, C = _generate_body()
1122
+ with warns_deprecated_sympy():
1123
+ PrismaticJoint('J', P, C, parent_axis=P.x + P.y)
1124
+ assert (A.x).angle_between(N.x + N.y) == 0
1125
+ assert A.x.express(N) == (N.x + N.y) / sqrt(2)
1126
+ assert A.dcm(N) == Matrix([[sqrt(2) / 2, sqrt(2) / 2, 0],
1127
+ [-sqrt(2) / 2, sqrt(2) / 2, 0], [0, 0, 1]])
1128
+ assert A.ang_vel_in(N) == Vector(0)
1129
+
1130
+
1131
+ def test_deprecated_joint_pos():
1132
+ N, A, P, C = _generate_body()
1133
+ with warns_deprecated_sympy():
1134
+ pin = PinJoint('J', P, C, parent_joint_pos=N.x + N.y,
1135
+ child_joint_pos=C.y - C.z)
1136
+ assert pin.parent_point.pos_from(P.masscenter) == N.x + N.y
1137
+ assert pin.child_point.pos_from(C.masscenter) == C.y - C.z
1138
+
1139
+ N, A, P, C = _generate_body()
1140
+ with warns_deprecated_sympy():
1141
+ slider = PrismaticJoint('J', P, C, parent_joint_pos=N.z + N.y,
1142
+ child_joint_pos=C.y - C.x)
1143
+ assert slider.parent_point.pos_from(P.masscenter) == N.z + N.y
1144
+ assert slider.child_point.pos_from(C.masscenter) == C.y - C.x
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand
2
+ from sympy.core.symbol import symbols
3
+ from sympy.functions.elementary.trigonometric import (cos, sin)
4
+ from sympy.matrices.dense import Matrix
5
+ from sympy.simplify.trigsimp import trigsimp
6
+ from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod,
7
+ PrismaticJoint, LagrangesMethod, inertia)
8
+ from sympy.physics.vector import dynamicsymbols, ReferenceFrame
9
+ from sympy.testing.pytest import raises
10
+ from sympy.core.backend import zeros
11
+ from sympy.utilities.lambdify import lambdify
12
+ from sympy.solvers.solvers import solve
13
+
14
+
15
+ t = dynamicsymbols._t # type: ignore
16
+
17
+
18
+ def test_jointsmethod():
19
+ P = Body('P')
20
+ C = Body('C')
21
+ Pin = PinJoint('P1', P, C)
22
+ C_ixx, g = symbols('C_ixx g')
23
+ q, u = dynamicsymbols('q_P1, u_P1')
24
+ P.apply_force(g*P.y)
25
+ method = JointsMethod(P, Pin)
26
+ assert method.frame == P.frame
27
+ assert method.bodies == [C, P]
28
+ assert method.loads == [(P.masscenter, g*P.frame.y)]
29
+ assert method.q == Matrix([q])
30
+ assert method.u == Matrix([u])
31
+ assert method.kdes == Matrix([u - q.diff()])
32
+ soln = method.form_eoms()
33
+ assert soln == Matrix([[-C_ixx*u.diff()]])
34
+ assert method.forcing_full == Matrix([[u], [0]])
35
+ assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]])
36
+ assert isinstance(method.method, KanesMethod)
37
+
38
+ def test_jointmethod_duplicate_coordinates_speeds():
39
+ P = Body('P')
40
+ C = Body('C')
41
+ T = Body('T')
42
+ q, u = dynamicsymbols('q u')
43
+ P1 = PinJoint('P1', P, C, q)
44
+ P2 = PrismaticJoint('P2', C, T, q)
45
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
46
+
47
+ P1 = PinJoint('P1', P, C, speeds=u)
48
+ P2 = PrismaticJoint('P2', C, T, speeds=u)
49
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
50
+
51
+ P1 = PinJoint('P1', P, C, q, u)
52
+ P2 = PrismaticJoint('P2', C, T, q, u)
53
+ raises(ValueError, lambda: JointsMethod(P, P1, P2))
54
+
55
+ def test_complete_simple_double_pendulum():
56
+ q1, q2 = dynamicsymbols('q1 q2')
57
+ u1, u2 = dynamicsymbols('u1 u2')
58
+ m, l, g = symbols('m l g')
59
+ C = Body('C') # ceiling
60
+ PartP = Body('P', mass=m)
61
+ PartR = Body('R', mass=m)
62
+ J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
63
+ child_point=-l*PartP.x, joint_axis=C.z)
64
+ J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
65
+ child_point=-l*PartR.x, joint_axis=PartP.z)
66
+
67
+ PartP.apply_force(m*g*C.x)
68
+ PartR.apply_force(m*g*C.x)
69
+
70
+ method = JointsMethod(C, J1, J2)
71
+ method.form_eoms()
72
+
73
+ assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0],
74
+ [0, 1, 0, 0],
75
+ [0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m],
76
+ [0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]])
77
+ assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) -
78
+ g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)],
79
+ [-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]]))
80
+
81
+ def test_two_dof_joints():
82
+ q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
83
+ m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
84
+ W = Body('W')
85
+ B1 = Body('B1', mass=m)
86
+ B2 = Body('B2', mass=m)
87
+ J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1)
88
+ J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2)
89
+ W.apply_force(k1*q1*W.x, reaction_body=B1)
90
+ W.apply_force(c1*u1*W.x, reaction_body=B1)
91
+ B1.apply_force(k2*q2*W.x, reaction_body=B2)
92
+ B1.apply_force(c2*u2*W.x, reaction_body=B2)
93
+ method = JointsMethod(W, J1, J2)
94
+ method.form_eoms()
95
+ MM = method.mass_matrix
96
+ forcing = method.forcing
97
+ rhs = MM.LUsolve(forcing)
98
+ assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
99
+ assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
100
+ c2 * u2) / m)
101
+
102
+ def test_simple_pedulum():
103
+ l, m, g = symbols('l m g')
104
+ C = Body('C')
105
+ b = Body('b', mass=m)
106
+ q = dynamicsymbols('q')
107
+ P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q,
108
+ child_point=-l * b.x, joint_axis=C.z)
109
+ b.potential_energy = - m * g * l * cos(q)
110
+ method = JointsMethod(C, P)
111
+ method.form_eoms(LagrangesMethod)
112
+ rhs = method.rhs()
113
+ assert rhs[1] == -g*sin(q)/l
114
+
115
+ def test_chaos_pendulum():
116
+ #https://www.pydy.org/examples/chaos_pendulum.html
117
+ mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g')
118
+ theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
119
+
120
+ A = ReferenceFrame('A')
121
+ B = ReferenceFrame('B')
122
+
123
+ rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0))
124
+ plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz))
125
+ C = Body('C')
126
+ J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
127
+ child_point=-lA * rod.z, joint_axis=C.y)
128
+ J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
129
+ parent_point=(lB - lA) * rod.z, joint_axis=rod.z)
130
+
131
+ rod.apply_force(mA*g*C.z)
132
+ plate.apply_force(mB*g*C.z)
133
+
134
+ method = JointsMethod(C, J1, J2)
135
+ method.form_eoms()
136
+
137
+ MM = method.mass_matrix
138
+ forcing = method.forcing
139
+ rhs = MM.LUsolve(forcing)
140
+ xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) *
141
+ cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx *
142
+ sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB)
143
+ assert (rhs[0] - xd).simplify() == 0
144
+ xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz
145
+ assert (rhs[1] - xd).simplify() == 0
146
+
147
+ def test_four_bar_linkage_with_manual_constraints():
148
+ q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4, u1:4')
149
+ l1, l2, l3, l4, rho = symbols('l1:5, rho')
150
+
151
+ N = ReferenceFrame('N')
152
+ inertias = [inertia(N, 0, 0, rho * l ** 3 / 12) for l in (l1, l2, l3, l4)]
153
+ link1 = Body('Link1', frame=N, mass=rho * l1, central_inertia=inertias[0])
154
+ link2 = Body('Link2', mass=rho * l2, central_inertia=inertias[1])
155
+ link3 = Body('Link3', mass=rho * l3, central_inertia=inertias[2])
156
+ link4 = Body('Link4', mass=rho * l4, central_inertia=inertias[3])
157
+
158
+ joint1 = PinJoint(
159
+ 'J1', link1, link2, coordinates=q1, speeds=u1, joint_axis=link1.z,
160
+ parent_point=l1 / 2 * link1.x, child_point=-l2 / 2 * link2.x)
161
+ joint2 = PinJoint(
162
+ 'J2', link2, link3, coordinates=q2, speeds=u2, joint_axis=link2.z,
163
+ parent_point=l2 / 2 * link2.x, child_point=-l3 / 2 * link3.x)
164
+ joint3 = PinJoint(
165
+ 'J3', link3, link4, coordinates=q3, speeds=u3, joint_axis=link3.z,
166
+ parent_point=l3 / 2 * link3.x, child_point=-l4 / 2 * link4.x)
167
+
168
+ loop = link4.masscenter.pos_from(link1.masscenter) \
169
+ + l1 / 2 * link1.x + l4 / 2 * link4.x
170
+
171
+ fh = Matrix([loop.dot(link1.x), loop.dot(link1.y)])
172
+
173
+ method = JointsMethod(link1, joint1, joint2, joint3)
174
+
175
+ t = dynamicsymbols._t
176
+ qdots = solve(method.kdes, [q1.diff(t), q2.diff(t), q3.diff(t)])
177
+ fhd = fh.diff(t).subs(qdots)
178
+
179
+ kane = KanesMethod(method.frame, q_ind=[q1], u_ind=[u1],
180
+ q_dependent=[q2, q3], u_dependent=[u2, u3],
181
+ kd_eqs=method.kdes, configuration_constraints=fh,
182
+ velocity_constraints=fhd, forcelist=method.loads,
183
+ bodies=method.bodies)
184
+ fr, frs = kane.kanes_equations()
185
+ assert fr == zeros(1)
186
+
187
+ # Numerically check the mass- and forcing-matrix
188
+ p = Matrix([l1, l2, l3, l4, rho])
189
+ q = Matrix([q1, q2, q3])
190
+ u = Matrix([u1, u2, u3])
191
+ eval_m = lambdify((q, p), kane.mass_matrix)
192
+ eval_f = lambdify((q, u, p), kane.forcing)
193
+ eval_fhd = lambdify((q, u, p), fhd)
194
+
195
+ p_vals = [0.13, 0.24, 0.21, 0.34, 997]
196
+ q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # Satisfies fh
197
+ u_vals = [0.2, -0.17963733938852067, 0.1309060540601612] # Satisfies fhd
198
+ mass_check = Matrix([[3.452709815256506e+01, 7.003948798374735e+00,
199
+ -4.939690970641498e+00],
200
+ [-2.203792703880936e-14, 2.071702479957077e-01,
201
+ 2.842917573033711e-01],
202
+ [-1.300000000000123e-01, -8.836934896046506e-03,
203
+ 1.864891330060847e-01]])
204
+ forcing_check = Matrix([[-0.031211821321648],
205
+ [-0.00066022608181],
206
+ [0.001813559741243]])
207
+ eps = 1e-10
208
+ assert all(abs(x) < eps for x in eval_fhd(q_vals, u_vals, p_vals))
209
+ assert all(abs(x) < eps for x in
210
+ (Matrix(eval_m(q_vals, p_vals)) - mass_check))
211
+ assert all(abs(x) < eps for x in
212
+ (Matrix(eval_f(q_vals, u_vals, p_vals)) - forcing_check))
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import (cos, sin, Matrix, symbols)
2
+ from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point,
3
+ KanesMethod, Particle)
4
+
5
+ def test_replace_qdots_in_force():
6
+ # Test PR 16700 "Replaces qdots with us in force-list in kanes.py"
7
+ # The new functionality allows one to specify forces in qdots which will
8
+ # automatically be replaced with u:s which are defined by the kde supplied
9
+ # to KanesMethod. The test case is the double pendulum with interacting
10
+ # forces in the example of chapter 4.7 "CONTRIBUTING INTERACTION FORCES"
11
+ # in Ref. [1]. Reference list at end test function.
12
+
13
+ q1, q2 = dynamicsymbols('q1, q2')
14
+ qd1, qd2 = dynamicsymbols('q1, q2', level=1)
15
+ u1, u2 = dynamicsymbols('u1, u2')
16
+
17
+ l, m = symbols('l, m')
18
+
19
+ N = ReferenceFrame('N') # Inertial frame
20
+ A = N.orientnew('A', 'Axis', (q1, N.z)) # Rod A frame
21
+ B = A.orientnew('B', 'Axis', (q2, N.z)) # Rod B frame
22
+
23
+ O = Point('O') # Origo
24
+ O.set_vel(N, 0)
25
+
26
+ P = O.locatenew('P', ( l * A.x )) # Point @ end of rod A
27
+ P.v2pt_theory(O, N, A)
28
+
29
+ Q = P.locatenew('Q', ( l * B.x )) # Point @ end of rod B
30
+ Q.v2pt_theory(P, N, B)
31
+
32
+ Ap = Particle('Ap', P, m)
33
+ Bp = Particle('Bp', Q, m)
34
+
35
+ # The forces are specified below. sigma is the torsional spring stiffness
36
+ # and delta is the viscous damping coefficient acting between the two
37
+ # bodies. Here, we specify the viscous damper as function of qdots prior
38
+ # forming the kde. In more complex systems it not might be obvious which
39
+ # kde is most efficient, why it is convenient to specify viscous forces in
40
+ # qdots independently of the kde.
41
+ sig, delta = symbols('sigma, delta')
42
+ Ta = (sig * q2 + delta * qd2) * N.z
43
+ forces = [(A, Ta), (B, -Ta)]
44
+
45
+ # Try different kdes.
46
+ kde1 = [u1 - qd1, u2 - qd2]
47
+ kde2 = [u1 - qd1, u2 - (qd1 + qd2)]
48
+
49
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
50
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
51
+
52
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
53
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
54
+
55
+ # Check EOM for KM2:
56
+ # Mass and force matrix from p.6 in Ref. [2] with added forces from
57
+ # example of chapter 4.7 in [1] and without gravity.
58
+ forcing_matrix_expected = Matrix( [ [ m * l**2 * sin(q2) * u2**2 + sig * q2
59
+ + delta * (u2 - u1)],
60
+ [ m * l**2 * sin(q2) * -u1**2 - sig * q2
61
+ - delta * (u2 - u1)] ] )
62
+ mass_matrix_expected = Matrix( [ [ 2 * m * l**2, m * l**2 * cos(q2) ],
63
+ [ m * l**2 * cos(q2), m * l**2 ] ] )
64
+
65
+ assert (KM2.mass_matrix.expand() == mass_matrix_expected.expand())
66
+ assert (KM2.forcing.expand() == forcing_matrix_expected.expand())
67
+
68
+ # Check fr1 with reference fr_expected from [1] with u:s instead of qdots.
69
+ fr1_expected = Matrix([ 0, -(sig*q2 + delta * u2) ])
70
+ assert fr1.expand() == fr1_expected.expand()
71
+
72
+ # Check fr2
73
+ fr2_expected = Matrix([sig * q2 + delta * (u2 - u1),
74
+ - sig * q2 - delta * (u2 - u1)])
75
+ assert fr2.expand() == fr2_expected.expand()
76
+
77
+ # Specifying forces in u:s should stay the same:
78
+ Ta = (sig * q2 + delta * u2) * N.z
79
+ forces = [(A, Ta), (B, -Ta)]
80
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
81
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
82
+
83
+ assert fr1.expand() == fr1_expected.expand()
84
+
85
+ Ta = (sig * q2 + delta * (u2-u1)) * N.z
86
+ forces = [(A, Ta), (B, -Ta)]
87
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
88
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
89
+
90
+ assert fr2.expand() == fr2_expected.expand()
91
+
92
+ # Test if we have a qubic qdot force:
93
+ Ta = (sig * q2 + delta * qd2**3) * N.z
94
+ forces = [(A, Ta), (B, -Ta)]
95
+
96
+ KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1)
97
+ fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces)
98
+
99
+ fr1_cubic_expected = Matrix([ 0, -(sig*q2 + delta * u2**3) ])
100
+
101
+ assert fr1.expand() == fr1_cubic_expected.expand()
102
+
103
+ KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2)
104
+ fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces)
105
+
106
+ fr2_cubic_expected = Matrix([sig * q2 + delta * (u2 - u1)**3,
107
+ - sig * q2 - delta * (u2 - u1)**3])
108
+
109
+ assert fr2.expand() == fr2_cubic_expected.expand()
110
+
111
+ # References:
112
+ # [1] T.R. Kane, D. a Levinson, Dynamics Theory and Applications, 2005.
113
+ # [2] Arun K Banerjee, Flexible Multibody Dynamics:Efficient Formulations
114
+ # and Applications, John Wiley and Sons, Ltd, 2016.
115
+ # doi:http://dx.doi.org/10.1002/9781119015635.
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend import symbols
2
+ from sympy.physics.mechanics import dynamicsymbols
3
+ from sympy.physics.mechanics import ReferenceFrame, Point, Particle
4
+ from sympy.physics.mechanics import LagrangesMethod, Lagrangian
5
+
6
+ ### This test asserts that a system with more than one external forces
7
+ ### is acurately formed with Lagrange method (see issue #8626)
8
+
9
+ def test_lagrange_2forces():
10
+ ### Equations for two damped springs in serie with two forces
11
+
12
+ ### generalized coordinates
13
+ q1, q2 = dynamicsymbols('q1, q2')
14
+ ### generalized speeds
15
+ q1d, q2d = dynamicsymbols('q1, q2', 1)
16
+
17
+ ### Mass, spring strength, friction coefficient
18
+ m, k, nu = symbols('m, k, nu')
19
+
20
+ N = ReferenceFrame('N')
21
+ O = Point('O')
22
+
23
+ ### Two points
24
+ P1 = O.locatenew('P1', q1 * N.x)
25
+ P1.set_vel(N, q1d * N.x)
26
+ P2 = O.locatenew('P1', q2 * N.x)
27
+ P2.set_vel(N, q2d * N.x)
28
+
29
+ pP1 = Particle('pP1', P1, m)
30
+ pP1.potential_energy = k * q1**2 / 2
31
+
32
+ pP2 = Particle('pP2', P2, m)
33
+ pP2.potential_energy = k * (q1 - q2)**2 / 2
34
+
35
+ #### Friction forces
36
+ forcelist = [(P1, - nu * q1d * N.x),
37
+ (P2, - nu * q2d * N.x)]
38
+ lag = Lagrangian(N, pP1, pP2)
39
+
40
+ l_method = LagrangesMethod(lag, (q1, q2), forcelist=forcelist, frame=N)
41
+ l_method.form_lagranges_equations()
42
+
43
+ eq1 = l_method.eom[0]
44
+ assert eq1.diff(q1d) == nu
45
+ eq2 = l_method.eom[1]
46
+ assert eq2.diff(q2d) == nu
llmeval-env/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())
llmeval-env/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.core.backend 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])
llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.backend 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
llmeval-env/lib/python3.10/site-packages/sympy/physics/sho.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, pi, Rational
2
+ from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2
3
+
4
+
5
+ def R_nl(n, l, nu, r):
6
+ """
7
+ Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic
8
+ oscillator.
9
+
10
+ Parameters
11
+ ==========
12
+
13
+ n :
14
+ The "nodal" quantum number. Corresponds to the number of nodes in
15
+ the wavefunction. ``n >= 0``
16
+ l :
17
+ The quantum number for orbital angular momentum.
18
+ nu :
19
+ mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass
20
+ and `omega` the frequency of the oscillator.
21
+ (in atomic units ``nu == omega/2``)
22
+ r :
23
+ Radial coordinate.
24
+
25
+ Examples
26
+ ========
27
+
28
+ >>> from sympy.physics.sho import R_nl
29
+ >>> from sympy.abc import r, nu, l
30
+ >>> R_nl(0, 0, 1, r)
31
+ 2*2**(3/4)*exp(-r**2)/pi**(1/4)
32
+ >>> R_nl(1, 0, 1, r)
33
+ 4*2**(1/4)*sqrt(3)*(3/2 - 2*r**2)*exp(-r**2)/(3*pi**(1/4))
34
+
35
+ l, nu and r may be symbolic:
36
+
37
+ >>> R_nl(0, 0, nu, r)
38
+ 2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4)
39
+ >>> R_nl(0, l, 1, r)
40
+ r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4)
41
+
42
+ The normalization of the radial wavefunction is:
43
+
44
+ >>> from sympy import Integral, oo
45
+ >>> Integral(R_nl(0, 0, 1, r)**2*r**2, (r, 0, oo)).n()
46
+ 1.00000000000000
47
+ >>> Integral(R_nl(1, 0, 1, r)**2*r**2, (r, 0, oo)).n()
48
+ 1.00000000000000
49
+ >>> Integral(R_nl(1, 1, 1, r)**2*r**2, (r, 0, oo)).n()
50
+ 1.00000000000000
51
+
52
+ """
53
+ n, l, nu, r = map(S, [n, l, nu, r])
54
+
55
+ # formula uses n >= 1 (instead of nodal n >= 0)
56
+ n = n + 1
57
+ C = sqrt(
58
+ ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/
59
+ (sqrt(pi)*(factorial2(2*n + 2*l - 1)))
60
+ )
61
+ return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S.Half, 2*nu*r**2)
62
+
63
+
64
+ def E_nl(n, l, hw):
65
+ """
66
+ Returns the Energy of an isotropic harmonic oscillator.
67
+
68
+ Parameters
69
+ ==========
70
+
71
+ n :
72
+ The "nodal" quantum number.
73
+ l :
74
+ The orbital angular momentum.
75
+ hw :
76
+ The harmonic oscillator parameter.
77
+
78
+ Notes
79
+ =====
80
+
81
+ The unit of the returned value matches the unit of hw, since the energy is
82
+ calculated as:
83
+
84
+ E_nl = (2*n + l + 3/2)*hw
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy.physics.sho import E_nl
90
+ >>> from sympy import symbols
91
+ >>> x, y, z = symbols('x, y, z')
92
+ >>> E_nl(x, y, z)
93
+ z*(2*x + y + 3/2)
94
+ """
95
+ return (2*n + l + Rational(3, 2))*hw
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc ADDED
Binary file (7.87 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc ADDED
Binary file (5.27 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc ADDED
Binary file (1.63 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc ADDED
Binary file (1.75 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc ADDED
Binary file (2.27 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, pi, Rational)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.functions.special.spherical_harmonics import Ynm
8
+ from sympy.matrices.dense import Matrix
9
+ from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt,
10
+ real_gaunt, racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d)
11
+ from sympy.testing.pytest import raises
12
+
13
+ # for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients
14
+
15
+ def test_clebsch_gordan_docs():
16
+ assert clebsch_gordan(Rational(3, 2), S.Half, 2, Rational(3, 2), S.Half, 2) == 1
17
+ assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(3, 2), Rational(-1, 2), 1) == sqrt(3)/2
18
+ assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2
19
+
20
+
21
+ def test_clebsch_gordan():
22
+ # Argument order: (j_1, j_2, j, m_1, m_2, m)
23
+
24
+ h = S.One
25
+ k = S.Half
26
+ l = Rational(3, 2)
27
+ i = Rational(-1, 2)
28
+ n = Rational(7, 2)
29
+ p = Rational(5, 2)
30
+ assert clebsch_gordan(k, k, 1, k, k, 1) == 1
31
+ assert clebsch_gordan(k, k, 1, k, k, 0) == 0
32
+ assert clebsch_gordan(k, k, 1, i, i, -1) == 1
33
+ assert clebsch_gordan(k, k, 1, k, i, 0) == sqrt(2)/2
34
+ assert clebsch_gordan(k, k, 0, k, i, 0) == sqrt(2)/2
35
+ assert clebsch_gordan(k, k, 1, i, k, 0) == sqrt(2)/2
36
+ assert clebsch_gordan(k, k, 0, i, k, 0) == -sqrt(2)/2
37
+ assert clebsch_gordan(h, k, l, 1, k, l) == 1
38
+ assert clebsch_gordan(h, k, l, 1, i, k) == 1/sqrt(3)
39
+ assert clebsch_gordan(h, k, k, 1, i, k) == sqrt(2)/sqrt(3)
40
+ assert clebsch_gordan(h, k, k, 0, k, k) == -1/sqrt(3)
41
+ assert clebsch_gordan(h, k, l, 0, k, k) == sqrt(2)/sqrt(3)
42
+ assert clebsch_gordan(h, h, S(2), 1, 1, S(2)) == 1
43
+ assert clebsch_gordan(h, h, S(2), 1, 0, 1) == 1/sqrt(2)
44
+ assert clebsch_gordan(h, h, S(2), 0, 1, 1) == 1/sqrt(2)
45
+ assert clebsch_gordan(h, h, 1, 1, 0, 1) == 1/sqrt(2)
46
+ assert clebsch_gordan(h, h, 1, 0, 1, 1) == -1/sqrt(2)
47
+ assert clebsch_gordan(l, l, S(3), l, l, S(3)) == 1
48
+ assert clebsch_gordan(l, l, S(2), l, k, S(2)) == 1/sqrt(2)
49
+ assert clebsch_gordan(l, l, S(3), l, k, S(2)) == 1/sqrt(2)
50
+ assert clebsch_gordan(S(2), S(2), S(4), S(2), S(2), S(4)) == 1
51
+ assert clebsch_gordan(S(2), S(2), S(3), S(2), 1, S(3)) == 1/sqrt(2)
52
+ assert clebsch_gordan(S(2), S(2), S(3), 1, 1, S(2)) == 0
53
+ assert clebsch_gordan(p, h, n, p, 1, n) == 1
54
+ assert clebsch_gordan(p, h, p, p, 0, p) == sqrt(5)/sqrt(7)
55
+ assert clebsch_gordan(p, h, l, k, 1, l) == 1/sqrt(15)
56
+
57
+
58
+ def test_wigner():
59
+ def tn(a, b):
60
+ return (a - b).n(64) < S('1e-64')
61
+ assert tn(wigner_9j(1, 1, 1, 1, 1, 1, 1, 1, 0, prec=64), Rational(1, 18))
62
+ assert wigner_9j(3, 3, 2, 3, 3, 2, 3, 3, 2) == 3221*sqrt(
63
+ 70)/(246960*sqrt(105)) - 365/(3528*sqrt(70)*sqrt(105))
64
+ assert wigner_6j(5, 5, 5, 5, 5, 5) == Rational(1, 52)
65
+ assert tn(wigner_6j(8, 8, 8, 8, 8, 8, prec=64), Rational(-12219, 965770))
66
+ # regression test for #8747
67
+ half = S.Half
68
+ assert wigner_9j(0, 0, 0, 0, half, half, 0, half, half) == half
69
+ assert (wigner_9j(3, 5, 4,
70
+ 7 * half, 5 * half, 4,
71
+ 9 * half, 9 * half, 0)
72
+ == -sqrt(Rational(361, 205821000)))
73
+ assert (wigner_9j(1, 4, 3,
74
+ 5 * half, 4, 5 * half,
75
+ 5 * half, 2, 7 * half)
76
+ == -sqrt(Rational(3971, 373403520)))
77
+ assert (wigner_9j(4, 9 * half, 5 * half,
78
+ 2, 4, 4,
79
+ 5, 7 * half, 7 * half)
80
+ == -sqrt(Rational(3481, 5042614500)))
81
+
82
+
83
+ def test_gaunt():
84
+ def tn(a, b):
85
+ return (a - b).n(64) < S('1e-64')
86
+ assert gaunt(1, 0, 1, 1, 0, -1) == -1/(2*sqrt(pi))
87
+ assert isinstance(gaunt(1, 1, 0, -1, 1, 0).args[0], Rational)
88
+ assert isinstance(gaunt(0, 1, 1, 0, -1, 1).args[0], Rational)
89
+
90
+ assert tn(gaunt(
91
+ 10, 10, 12, 9, 3, -12, prec=64), (Rational(-98, 62031)) * sqrt(6279)/sqrt(pi))
92
+ def gaunt_ref(l1, l2, l3, m1, m2, m3):
93
+ return (
94
+ sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) / (4 * pi)) *
95
+ wigner_3j(l1, l2, l3, 0, 0, 0) *
96
+ wigner_3j(l1, l2, l3, m1, m2, m3)
97
+ )
98
+ threshold = 1e-10
99
+ l_max = 3
100
+ l3_max = 24
101
+ for l1 in range(l_max + 1):
102
+ for l2 in range(l_max + 1):
103
+ for l3 in range(l3_max + 1):
104
+ for m1 in range(-l1, l1 + 1):
105
+ for m2 in range(-l2, l2 + 1):
106
+ for m3 in range(-l3, l3 + 1):
107
+ args = l1, l2, l3, m1, m2, m3
108
+ g = gaunt(*args)
109
+ g0 = gaunt_ref(*args)
110
+ assert abs(g - g0) < threshold
111
+ if m1 + m2 + m3 != 0:
112
+ assert abs(g) < threshold
113
+ if (l1 + l2 + l3) % 2:
114
+ assert abs(g) < threshold
115
+ assert gaunt(1, 1, 0, 0, 2, -2) is S.Zero
116
+
117
+
118
+ def test_realgaunt():
119
+ # All non-zero values corresponding to l values from 0 to 2
120
+ for l in range(3):
121
+ for m in range(-l, l+1):
122
+ assert real_gaunt(0, l, l, 0, m, m) == 1/(2*sqrt(pi))
123
+ assert real_gaunt(1, 1, 2, 0, 0, 0) == sqrt(5)/(5*sqrt(pi))
124
+ assert real_gaunt(1, 1, 2, 1, 1, 0) == -sqrt(5)/(10*sqrt(pi))
125
+ assert real_gaunt(2, 2, 2, 0, 0, 0) == sqrt(5)/(7*sqrt(pi))
126
+ assert real_gaunt(2, 2, 2, 0, 2, 2) == -sqrt(5)/(7*sqrt(pi))
127
+ assert real_gaunt(2, 2, 2, -2, -2, 0) == -sqrt(5)/(7*sqrt(pi))
128
+ assert real_gaunt(1, 1, 2, -1, 0, -1) == sqrt(15)/(10*sqrt(pi))
129
+ assert real_gaunt(1, 1, 2, 0, 1, 1) == sqrt(15)/(10*sqrt(pi))
130
+ assert real_gaunt(1, 1, 2, 1, 1, 2) == sqrt(15)/(10*sqrt(pi))
131
+ assert real_gaunt(1, 1, 2, -1, 1, -2) == -sqrt(15)/(10*sqrt(pi))
132
+ assert real_gaunt(1, 1, 2, -1, -1, 2) == -sqrt(15)/(10*sqrt(pi))
133
+ assert real_gaunt(2, 2, 2, 0, 1, 1) == sqrt(5)/(14*sqrt(pi))
134
+ assert real_gaunt(2, 2, 2, 1, 1, 2) == sqrt(15)/(14*sqrt(pi))
135
+ assert real_gaunt(2, 2, 2, -1, -1, 2) == -sqrt(15)/(14*sqrt(pi))
136
+
137
+ assert real_gaunt(-2, -2, -2, -2, -2, 0) is S.Zero # m test
138
+ assert real_gaunt(-2, 1, 0, 1, 1, 1) is S.Zero # l test
139
+ assert real_gaunt(-2, -1, -2, -1, -1, 0) is S.Zero # m and l test
140
+ assert real_gaunt(-2, -2, -2, -2, -2, -2) is S.Zero # m and k test
141
+ assert real_gaunt(-2, -1, -2, -1, -1, -1) is S.Zero # m, l and k test
142
+
143
+ x = symbols('x', integer=True)
144
+ v = [0]*6
145
+ for i in range(len(v)):
146
+ v[i] = x # non literal ints fail
147
+ raises(ValueError, lambda: real_gaunt(*v))
148
+ v[i] = 0
149
+
150
+
151
+ def test_racah():
152
+ assert racah(3,3,3,3,3,3) == Rational(-1,14)
153
+ assert racah(2,2,2,2,2,2) == Rational(-3,70)
154
+ assert racah(7,8,7,1,7,7, prec=4).is_Float
155
+ assert racah(5.5,7.5,9.5,6.5,8,9) == -719*sqrt(598)/1158924
156
+ assert abs(racah(5.5,7.5,9.5,6.5,8,9, prec=4) - (-0.01517)) < S('1e-4')
157
+
158
+
159
+ def test_dot_rota_grad_SH():
160
+ theta, phi = symbols("theta phi")
161
+ assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0) != \
162
+ sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
163
+ assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0).doit() == \
164
+ sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi))
165
+ assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2) != \
166
+ 0
167
+ assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2).doit() == \
168
+ 0
169
+ assert dot_rot_grad_Ynm(3, 3, 3, 3, theta, phi).doit() == \
170
+ 15*sqrt(3003)*Ynm(6, 6, theta, phi)/(143*sqrt(pi))
171
+ assert dot_rot_grad_Ynm(3, 3, 1, 1, theta, phi).doit() == \
172
+ sqrt(3)*Ynm(4, 4, theta, phi)/sqrt(pi)
173
+ assert dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() == \
174
+ 3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi))
175
+ assert dot_rot_grad_Ynm(3, 2, 3, 2, theta, phi).doit().expand() == \
176
+ -sqrt(70)*Ynm(4, 4, theta, phi)/(11*sqrt(pi)) + \
177
+ 45*sqrt(182)*Ynm(6, 4, theta, phi)/(143*sqrt(pi))
178
+
179
+
180
+ def test_wigner_d():
181
+ half = S(1)/2
182
+ alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
183
+ d = wigner_d_small(half, beta).subs({beta: pi/2})
184
+ d_ = Matrix([[1, 1], [-1, 1]])/sqrt(2)
185
+ assert d == d_
186
+
187
+ D = wigner_d(half, alpha, beta, gamma)
188
+ assert D[0, 0] == exp(I*alpha/2)*exp(I*gamma/2)*cos(beta/2)
189
+ assert D[0, 1] == exp(I*alpha/2)*exp(-I*gamma/2)*sin(beta/2)
190
+ assert D[1, 0] == -exp(-I*alpha/2)*exp(I*gamma/2)*sin(beta/2)
191
+ assert D[1, 1] == exp(-I*alpha/2)*exp(-I*gamma/2)*cos(beta/2)
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.functions.elementary.trigonometric import (cos, sin)
7
+ from sympy.integrals.integrals import integrate
8
+ from sympy.simplify.simplify import simplify
9
+ from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac, Psi_nlm
10
+ from sympy.testing.pytest import raises
11
+
12
+ n, r, Z = symbols('n r Z')
13
+
14
+
15
+ def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
16
+ a = float(a)
17
+ b = float(b)
18
+ # if the numbers are close enough (absolutely), then they are equal
19
+ if abs(a - b) < max_absolute_error:
20
+ return True
21
+ # if not, they can still be equal if their relative error is small
22
+ if abs(b) > abs(a):
23
+ relative_error = abs((a - b)/b)
24
+ else:
25
+ relative_error = abs((a - b)/a)
26
+ return relative_error <= max_relative_error
27
+
28
+
29
+ def test_wavefunction():
30
+ a = 1/Z
31
+ R = {
32
+ (1, 0): 2*sqrt(1/a**3) * exp(-r/a),
33
+ (2, 0): sqrt(1/(2*a**3)) * exp(-r/(2*a)) * (1 - r/(2*a)),
34
+ (2, 1): S.Half * sqrt(1/(6*a**3)) * exp(-r/(2*a)) * r/a,
35
+ (3, 0): Rational(2, 3) * sqrt(1/(3*a**3)) * exp(-r/(3*a)) *
36
+ (1 - 2*r/(3*a) + Rational(2, 27) * (r/a)**2),
37
+ (3, 1): Rational(4, 27) * sqrt(2/(3*a**3)) * exp(-r/(3*a)) *
38
+ (1 - r/(6*a)) * r/a,
39
+ (3, 2): Rational(2, 81) * sqrt(2/(15*a**3)) * exp(-r/(3*a)) * (r/a)**2,
40
+ (4, 0): Rational(1, 4) * sqrt(1/a**3) * exp(-r/(4*a)) *
41
+ (1 - 3*r/(4*a) + Rational(1, 8) * (r/a)**2 - Rational(1, 192) * (r/a)**3),
42
+ (4, 1): Rational(1, 16) * sqrt(5/(3*a**3)) * exp(-r/(4*a)) *
43
+ (1 - r/(4*a) + Rational(1, 80) * (r/a)**2) * (r/a),
44
+ (4, 2): Rational(1, 64) * sqrt(1/(5*a**3)) * exp(-r/(4*a)) *
45
+ (1 - r/(12*a)) * (r/a)**2,
46
+ (4, 3): Rational(1, 768) * sqrt(1/(35*a**3)) * exp(-r/(4*a)) * (r/a)**3,
47
+ }
48
+ for n, l in R:
49
+ assert simplify(R_nl(n, l, r, Z) - R[(n, l)]) == 0
50
+
51
+
52
+ def test_norm():
53
+ # Maximum "n" which is tested:
54
+ n_max = 2 # it works, but is slow, for n_max > 2
55
+ for n in range(n_max + 1):
56
+ for l in range(n):
57
+ assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1
58
+
59
+ def test_psi_nlm():
60
+ r=S('r')
61
+ phi=S('phi')
62
+ theta=S('theta')
63
+ assert (Psi_nlm(1, 0, 0, r, phi, theta) == exp(-r) / sqrt(pi))
64
+ assert (Psi_nlm(2, 1, -1, r, phi, theta)) == S.Half * exp(-r / (2)) * r \
65
+ * (sin(theta) * exp(-I * phi) / (4 * sqrt(pi)))
66
+ assert (Psi_nlm(3, 2, 1, r, phi, theta, 2) == -sqrt(2) * sin(theta) \
67
+ * exp(I * phi) * cos(theta) / (4 * sqrt(pi)) * S(2) / 81 \
68
+ * sqrt(2 * 2 ** 3) * exp(-2 * r / (3)) * (r * 2) ** 2)
69
+
70
+ def test_hydrogen_energies():
71
+ assert E_nl(n, Z) == -Z**2/(2*n**2)
72
+ assert E_nl(n) == -1/(2*n**2)
73
+
74
+ assert E_nl(1, 47) == -S(47)**2/(2*1**2)
75
+ assert E_nl(2, 47) == -S(47)**2/(2*2**2)
76
+
77
+ assert E_nl(1) == -S.One/(2*1**2)
78
+ assert E_nl(2) == -S.One/(2*2**2)
79
+ assert E_nl(3) == -S.One/(2*3**2)
80
+ assert E_nl(4) == -S.One/(2*4**2)
81
+ assert E_nl(100) == -S.One/(2*100**2)
82
+
83
+ raises(ValueError, lambda: E_nl(0))
84
+
85
+
86
+ def test_hydrogen_energies_relat():
87
+ # First test exact formulas for small "c" so that we get nice expressions:
88
+ assert E_nl_dirac(2, 0, Z=1, c=1) == 1/sqrt(2) - 1
89
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=2) - ( (8*sqrt(3) + 16)
90
+ / sqrt(16*sqrt(3) + 32) - 4)) == 0
91
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=3) - ( (54*sqrt(2) + 81)
92
+ / sqrt(108*sqrt(2) + 162) - 9)) == 0
93
+
94
+ # Now test for almost the correct speed of light, without floating point
95
+ # numbers:
96
+ assert simplify(E_nl_dirac(2, 0, Z=1, c=137) - ( (352275361 + 10285412 *
97
+ sqrt(1173)) / sqrt(704550722 + 20570824 * sqrt(1173)) - 18769)) == 0
98
+ assert simplify(E_nl_dirac(2, 0, Z=82, c=137) - ( (352275361 + 2571353 *
99
+ sqrt(12045)) / sqrt(704550722 + 5142706*sqrt(12045)) - 18769)) == 0
100
+
101
+ # Test using exact speed of light, and compare against the nonrelativistic
102
+ # energies:
103
+ for n in range(1, 5):
104
+ for l in range(n):
105
+ assert feq(E_nl_dirac(n, l), E_nl(n), 1e-5, 1e-5)
106
+ if l > 0:
107
+ assert feq(E_nl_dirac(n, l, False), E_nl(n), 1e-5, 1e-5)
108
+
109
+ Z = 2
110
+ for n in range(1, 5):
111
+ for l in range(n):
112
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-4, 1e-4)
113
+ if l > 0:
114
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-4, 1e-4)
115
+
116
+ Z = 3
117
+ for n in range(1, 5):
118
+ for l in range(n):
119
+ assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-3, 1e-3)
120
+ if l > 0:
121
+ assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-3, 1e-3)
122
+
123
+ # Test the exceptions:
124
+ raises(ValueError, lambda: E_nl_dirac(0, 0))
125
+ raises(ValueError, lambda: E_nl_dirac(1, -1))
126
+ raises(ValueError, lambda: E_nl_dirac(1, 0, False))
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I
2
+ from sympy.core.symbol import symbols
3
+ from sympy.physics.paulialgebra import Pauli
4
+ from sympy.testing.pytest import XFAIL
5
+ from sympy.physics.quantum import TensorProduct
6
+
7
+ sigma1 = Pauli(1)
8
+ sigma2 = Pauli(2)
9
+ sigma3 = Pauli(3)
10
+
11
+ tau1 = symbols("tau1", commutative = False)
12
+
13
+
14
+ def test_Pauli():
15
+
16
+ assert sigma1 == sigma1
17
+ assert sigma1 != sigma2
18
+
19
+ assert sigma1*sigma2 == I*sigma3
20
+ assert sigma3*sigma1 == I*sigma2
21
+ assert sigma2*sigma3 == I*sigma1
22
+
23
+ assert sigma1*sigma1 == 1
24
+ assert sigma2*sigma2 == 1
25
+ assert sigma3*sigma3 == 1
26
+
27
+ assert sigma1**0 == 1
28
+ assert sigma1**1 == sigma1
29
+ assert sigma1**2 == 1
30
+ assert sigma1**3 == sigma1
31
+ assert sigma1**4 == 1
32
+
33
+ assert sigma3**2 == 1
34
+
35
+ assert sigma1*2*sigma1 == 2
36
+
37
+
38
+ def test_evaluate_pauli_product():
39
+ from sympy.physics.paulialgebra import evaluate_pauli_product
40
+
41
+ assert evaluate_pauli_product(I*sigma2*sigma3) == -sigma1
42
+
43
+ # Check issue 6471
44
+ assert evaluate_pauli_product(-I*4*sigma1*sigma2) == 4*sigma3
45
+
46
+ assert evaluate_pauli_product(
47
+ 1 + I*sigma1*sigma2*sigma1*sigma2 + \
48
+ I*sigma1*sigma2*tau1*sigma1*sigma3 + \
49
+ ((tau1**2).subs(tau1, I*sigma1)) + \
50
+ sigma3*((tau1**2).subs(tau1, I*sigma1)) + \
51
+ TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1)
52
+ ) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1)
53
+
54
+
55
+ @XFAIL
56
+ def test_Pauli_should_work():
57
+ assert sigma1*sigma3*sigma1 == -sigma3
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft
2
+ from sympy.core.numbers import (I, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.matrices.dense import (Matrix, eye, zeros)
6
+ from sympy.testing.pytest import warns_deprecated_sympy
7
+
8
+
9
+ def test_parallel_axis_theorem():
10
+ # This tests the parallel axis theorem matrix by comparing to test
11
+ # matrices.
12
+
13
+ # First case, 1 in all directions.
14
+ mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2)))
15
+ assert pat_matrix(1, 1, 1, 1) == mat1
16
+ assert pat_matrix(2, 1, 1, 1) == 2*mat1
17
+
18
+ # Second case, 1 in x, 0 in all others
19
+ mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1)))
20
+ assert pat_matrix(1, 1, 0, 0) == mat2
21
+ assert pat_matrix(2, 1, 0, 0) == 2*mat2
22
+
23
+ # Third case, 1 in y, 0 in all others
24
+ mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1)))
25
+ assert pat_matrix(1, 0, 1, 0) == mat3
26
+ assert pat_matrix(2, 0, 1, 0) == 2*mat3
27
+
28
+ # Fourth case, 1 in z, 0 in all others
29
+ mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0)))
30
+ assert pat_matrix(1, 0, 0, 1) == mat4
31
+ assert pat_matrix(2, 0, 0, 1) == 2*mat4
32
+
33
+
34
+ def test_Pauli():
35
+ #this and the following test are testing both Pauli and Dirac matrices
36
+ #and also that the general Matrix class works correctly in a real world
37
+ #situation
38
+ sigma1 = msigma(1)
39
+ sigma2 = msigma(2)
40
+ sigma3 = msigma(3)
41
+
42
+ assert sigma1 == sigma1
43
+ assert sigma1 != sigma2
44
+
45
+ # sigma*I -> I*sigma (see #354)
46
+ assert sigma1*sigma2 == sigma3*I
47
+ assert sigma3*sigma1 == sigma2*I
48
+ assert sigma2*sigma3 == sigma1*I
49
+
50
+ assert sigma1*sigma1 == eye(2)
51
+ assert sigma2*sigma2 == eye(2)
52
+ assert sigma3*sigma3 == eye(2)
53
+
54
+ assert sigma1*2*sigma1 == 2*eye(2)
55
+ assert sigma1*sigma3*sigma1 == -sigma3
56
+
57
+
58
+ def test_Dirac():
59
+ gamma0 = mgamma(0)
60
+ gamma1 = mgamma(1)
61
+ gamma2 = mgamma(2)
62
+ gamma3 = mgamma(3)
63
+ gamma5 = mgamma(5)
64
+
65
+ # gamma*I -> I*gamma (see #354)
66
+ assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I
67
+ assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4)
68
+ assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0]
69
+ assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0]
70
+ assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2]
71
+
72
+ assert mgamma(5, True) == \
73
+ mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I
74
+
75
+ def test_mdft():
76
+ with warns_deprecated_sympy():
77
+ assert mdft(1) == Matrix([[1]])
78
+ with warns_deprecated_sympy():
79
+ assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
80
+ with warns_deprecated_sympy():
81
+ assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half],
82
+ [S.Half, -I/2, Rational(-1,2), I/2],
83
+ [S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
84
+ [S.Half, I/2, Rational(-1,2), -I/2]])
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_pring.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.pring import wavefunction, energy
2
+ from sympy.core.numbers import (I, pi)
3
+ from sympy.functions.elementary.exponential import exp
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.integrals.integrals import integrate
6
+ from sympy.simplify.simplify import simplify
7
+ from sympy.abc import m, x, r
8
+ from sympy.physics.quantum.constants import hbar
9
+
10
+
11
+ def test_wavefunction():
12
+ Psi = {
13
+ 0: (1/sqrt(2 * pi)),
14
+ 1: (1/sqrt(2 * pi)) * exp(I * x),
15
+ 2: (1/sqrt(2 * pi)) * exp(2 * I * x),
16
+ 3: (1/sqrt(2 * pi)) * exp(3 * I * x)
17
+ }
18
+ for n in Psi:
19
+ assert simplify(wavefunction(n, x) - Psi[n]) == 0
20
+
21
+
22
+ def test_norm(n=1):
23
+ # Maximum "n" which is tested:
24
+ for i in range(n + 1):
25
+ assert integrate(
26
+ wavefunction(i, x) * wavefunction(-i, x), (x, 0, 2 * pi)) == 1
27
+
28
+
29
+ def test_orthogonality(n=1):
30
+ # Maximum "n" which is tested:
31
+ for i in range(n + 1):
32
+ for j in range(i+1, n+1):
33
+ assert integrate(
34
+ wavefunction(i, x) * wavefunction(j, x), (x, 0, 2 * pi)) == 0
35
+
36
+
37
+ def test_energy(n=1):
38
+ # Maximum "n" which is tested:
39
+ for i in range(n+1):
40
+ assert simplify(
41
+ energy(i, m, r) - ((i**2 * hbar**2) / (2 * m * r**2))) == 0
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.integrals.integrals import integrate
7
+ from sympy.simplify.simplify import simplify
8
+ from sympy.abc import omega, m, x
9
+ from sympy.physics.qho_1d import psi_n, E_n, coherent_state
10
+ from sympy.physics.quantum.constants import hbar
11
+
12
+ nu = m * omega / hbar
13
+
14
+
15
+ def test_wavefunction():
16
+ Psi = {
17
+ 0: (nu/pi)**Rational(1, 4) * exp(-nu * x**2 /2),
18
+ 1: (nu/pi)**Rational(1, 4) * sqrt(2*nu) * x * exp(-nu * x**2 /2),
19
+ 2: (nu/pi)**Rational(1, 4) * (2 * nu * x**2 - 1)/sqrt(2) * exp(-nu * x**2 /2),
20
+ 3: (nu/pi)**Rational(1, 4) * sqrt(nu/3) * (2 * nu * x**3 - 3 * x) * exp(-nu * x**2 /2)
21
+ }
22
+ for n in Psi:
23
+ assert simplify(psi_n(n, x, m, omega) - Psi[n]) == 0
24
+
25
+
26
+ def test_norm(n=1):
27
+ # Maximum "n" which is tested:
28
+ for i in range(n + 1):
29
+ assert integrate(psi_n(i, x, 1, 1)**2, (x, -oo, oo)) == 1
30
+
31
+
32
+ def test_orthogonality(n=1):
33
+ # Maximum "n" which is tested:
34
+ for i in range(n + 1):
35
+ for j in range(i + 1, n + 1):
36
+ assert integrate(
37
+ psi_n(i, x, 1, 1)*psi_n(j, x, 1, 1), (x, -oo, oo)) == 0
38
+
39
+
40
+ def test_energies(n=1):
41
+ # Maximum "n" which is tested:
42
+ for i in range(n + 1):
43
+ assert E_n(i, omega) == hbar * omega * (i + S.Half)
44
+
45
+ def test_coherent_state(n=10):
46
+ # Maximum "n" which is tested:
47
+ # test whether coherent state is the eigenstate of annihilation operator
48
+ alpha = Symbol("alpha")
49
+ for i in range(n + 1):
50
+ assert simplify(sqrt(n + 1) * coherent_state(n + 1, alpha)) == simplify(alpha * coherent_state(n, alpha))
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py ADDED
@@ -0,0 +1,1280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.physics.secondquant import (
2
+ Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis,
3
+ matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta,
4
+ AnnihilateBoson, CreateBoson, BosonicOperator,
5
+ F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion,
6
+ evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks,
7
+ PermutationOperator, simplify_index_permutations,
8
+ _sort_anticommuting_fermions, _get_ordered_dummies,
9
+ substitute_dummies, FockStateBosonKet,
10
+ ContractionAppliesOnlyToFermions
11
+ )
12
+
13
+ from sympy.concrete.summations import Sum
14
+ from sympy.core.function import (Function, expand)
15
+ from sympy.core.numbers import (I, Rational)
16
+ from sympy.core.singleton import S
17
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
18
+ from sympy.functions.elementary.miscellaneous import sqrt
19
+ from sympy.printing.repr import srepr
20
+ from sympy.simplify.simplify import simplify
21
+
22
+ from sympy.testing.pytest import slow, raises
23
+ from sympy.printing.latex import latex
24
+
25
+
26
+ def test_PermutationOperator():
27
+ p, q, r, s = symbols('p,q,r,s')
28
+ f, g, h, i = map(Function, 'fghi')
29
+ P = PermutationOperator
30
+ assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p)
31
+ assert P(p, q).get_permuted(f(p, q)) == -f(q, p)
32
+ assert P(p, q).get_permuted(f(p)) == f(p)
33
+ expr = (f(p)*g(q)*h(r)*i(s)
34
+ - f(q)*g(p)*h(r)*i(s)
35
+ - f(p)*g(q)*h(s)*i(r)
36
+ + f(q)*g(p)*h(s)*i(r))
37
+ perms = [P(p, q), P(r, s)]
38
+ assert (simplify_index_permutations(expr, perms) ==
39
+ P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s))
40
+ assert latex(P(p, q)) == 'P(pq)'
41
+
42
+
43
+ def test_index_permutations_with_dummies():
44
+ a, b, c, d = symbols('a b c d')
45
+ p, q, r, s = symbols('p q r s', cls=Dummy)
46
+ f, g = map(Function, 'fg')
47
+ P = PermutationOperator
48
+
49
+ # No dummy substitution necessary
50
+ expr = f(a, b, p, q) - f(b, a, p, q)
51
+ assert simplify_index_permutations(
52
+ expr, [P(a, b)]) == P(a, b)*f(a, b, p, q)
53
+
54
+ # Cases where dummy substitution is needed
55
+ expected = P(a, b)*substitute_dummies(f(a, b, p, q))
56
+
57
+ expr = f(a, b, p, q) - f(b, a, q, p)
58
+ result = simplify_index_permutations(expr, [P(a, b)])
59
+ assert expected == substitute_dummies(result)
60
+
61
+ expr = f(a, b, q, p) - f(b, a, p, q)
62
+ result = simplify_index_permutations(expr, [P(a, b)])
63
+ assert expected == substitute_dummies(result)
64
+
65
+ # A case where nothing can be done
66
+ expr = f(a, b, q, p) - g(b, a, p, q)
67
+ result = simplify_index_permutations(expr, [P(a, b)])
68
+ assert expr == result
69
+
70
+
71
+ def test_dagger():
72
+ i, j, n, m = symbols('i,j,n,m')
73
+ assert Dagger(1) == 1
74
+ assert Dagger(1.0) == 1.0
75
+ assert Dagger(2*I) == -2*I
76
+ assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0
77
+ assert Dagger(BKet([n])) == BBra([n])
78
+ assert Dagger(B(0)) == Bd(0)
79
+ assert Dagger(Bd(0)) == B(0)
80
+ assert Dagger(B(n)) == Bd(n)
81
+ assert Dagger(Bd(n)) == B(n)
82
+ assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1)
83
+ assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute
84
+ assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n)
85
+ assert Dagger(B(n)**10) == Dagger(B(n))**10
86
+ assert Dagger('a') == Dagger(Symbol('a'))
87
+ assert Dagger(Dagger('a')) == Symbol('a')
88
+
89
+
90
+ def test_operator():
91
+ i, j = symbols('i,j')
92
+ o = BosonicOperator(i)
93
+ assert o.state == i
94
+ assert o.is_symbolic
95
+ o = BosonicOperator(1)
96
+ assert o.state == 1
97
+ assert not o.is_symbolic
98
+
99
+
100
+ def test_create():
101
+ i, j, n, m = symbols('i,j,n,m')
102
+ o = Bd(i)
103
+ assert latex(o) == "{b^\\dagger_{i}}"
104
+ assert isinstance(o, CreateBoson)
105
+ o = o.subs(i, j)
106
+ assert o.atoms(Symbol) == {j}
107
+ o = Bd(0)
108
+ assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
109
+ o = Bd(n)
110
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
111
+
112
+
113
+ def test_annihilate():
114
+ i, j, n, m = symbols('i,j,n,m')
115
+ o = B(i)
116
+ assert latex(o) == "b_{i}"
117
+ assert isinstance(o, AnnihilateBoson)
118
+ o = o.subs(i, j)
119
+ assert o.atoms(Symbol) == {j}
120
+ o = B(0)
121
+ assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1])
122
+ o = B(n)
123
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
124
+
125
+
126
+ def test_basic_state():
127
+ i, j, n, m = symbols('i,j,n,m')
128
+ s = BosonState([0, 1, 2, 3, 4])
129
+ assert len(s) == 5
130
+ assert s.args[0] == tuple(range(5))
131
+ assert s.up(0) == BosonState([1, 1, 2, 3, 4])
132
+ assert s.down(4) == BosonState([0, 1, 2, 3, 3])
133
+ for i in range(5):
134
+ assert s.up(i).down(i) == s
135
+ assert s.down(0) == 0
136
+ for i in range(5):
137
+ assert s[i] == i
138
+ s = BosonState([n, m])
139
+ assert s.down(0) == BosonState([n - 1, m])
140
+ assert s.up(0) == BosonState([n + 1, m])
141
+
142
+
143
+ def test_basic_apply():
144
+ n = symbols("n")
145
+ e = B(0)*BKet([n])
146
+ assert apply_operators(e) == sqrt(n)*BKet([n - 1])
147
+ e = Bd(0)*BKet([n])
148
+ assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1])
149
+
150
+
151
+ def test_complex_apply():
152
+ n, m = symbols("n,m")
153
+ o = Bd(0)*B(0)*Bd(1)*B(0)
154
+ e = apply_operators(o*BKet([n, m]))
155
+ answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m])
156
+ assert expand(e) == expand(answer)
157
+
158
+
159
+ def test_number_operator():
160
+ n = symbols("n")
161
+ o = Bd(0)*B(0)
162
+ e = apply_operators(o*BKet([n]))
163
+ assert e == n*BKet([n])
164
+
165
+
166
+ def test_inner_product():
167
+ i, j, k, l = symbols('i,j,k,l')
168
+ s1 = BBra([0])
169
+ s2 = BKet([1])
170
+ assert InnerProduct(s1, Dagger(s1)) == 1
171
+ assert InnerProduct(s1, s2) == 0
172
+ s1 = BBra([i, j])
173
+ s2 = BKet([k, l])
174
+ r = InnerProduct(s1, s2)
175
+ assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l)
176
+
177
+
178
+ def test_symbolic_matrix_elements():
179
+ n, m = symbols('n,m')
180
+ s1 = BBra([n])
181
+ s2 = BKet([m])
182
+ o = B(0)
183
+ e = apply_operators(s1*o*s2)
184
+ assert e == sqrt(m)*KroneckerDelta(n, m - 1)
185
+
186
+
187
+ def test_matrix_elements():
188
+ b = VarBosonicBasis(5)
189
+ o = B(0)
190
+ m = matrix_rep(o, b)
191
+ for i in range(4):
192
+ assert m[i, i + 1] == sqrt(i + 1)
193
+ o = Bd(0)
194
+ m = matrix_rep(o, b)
195
+ for i in range(4):
196
+ assert m[i + 1, i] == sqrt(i + 1)
197
+
198
+
199
+ def test_fixed_bosonic_basis():
200
+ b = FixedBosonicBasis(2, 2)
201
+ # assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]
202
+ state = b.state(1)
203
+ assert state == FockStateBosonKet((1, 1))
204
+ assert b.index(state) == 1
205
+ assert b.state(1) == b[1]
206
+ assert len(b) == 3
207
+ assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
208
+ assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
209
+ assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]'
210
+
211
+
212
+ @slow
213
+ def test_sho():
214
+ n, m = symbols('n,m')
215
+ h_n = Bd(n)*B(n)*(n + S.Half)
216
+ H = Sum(h_n, (n, 0, 5))
217
+ o = H.doit(deep=False)
218
+ b = FixedBosonicBasis(2, 6)
219
+ m = matrix_rep(o, b)
220
+ # We need to double check these energy values to make sure that they
221
+ # are correct and have the proper degeneracies!
222
+ diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11]
223
+ for i in range(len(diag)):
224
+ assert diag[i] == m[i, i]
225
+
226
+
227
+ def test_commutation():
228
+ n, m = symbols("n,m", above_fermi=True)
229
+ c = Commutator(B(0), Bd(0))
230
+ assert c == 1
231
+ c = Commutator(Bd(0), B(0))
232
+ assert c == -1
233
+ c = Commutator(B(n), Bd(0))
234
+ assert c == KroneckerDelta(n, 0)
235
+ c = Commutator(B(0), B(0))
236
+ assert c == 0
237
+ c = Commutator(B(0), Bd(0))
238
+ e = simplify(apply_operators(c*BKet([n])))
239
+ assert e == BKet([n])
240
+ c = Commutator(B(0), B(1))
241
+ e = simplify(apply_operators(c*BKet([n, m])))
242
+ assert e == 0
243
+
244
+ c = Commutator(F(m), Fd(m))
245
+ assert c == +1 - 2*NO(Fd(m)*F(m))
246
+ c = Commutator(Fd(m), F(m))
247
+ assert c.expand() == -1 + 2*NO(Fd(m)*F(m))
248
+
249
+ C = Commutator
250
+ X, Y, Z = symbols('X,Y,Z', commutative=False)
251
+ assert C(C(X, Y), Z) != 0
252
+ assert C(C(X, Z), Y) != 0
253
+ assert C(Y, C(X, Z)) != 0
254
+
255
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
256
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
257
+ p, q, r, s = symbols('p,q,r,s')
258
+ D = KroneckerDelta
259
+
260
+ assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a))
261
+ assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a)
262
+ assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0
263
+
264
+ c1 = Commutator(F(a), Fd(a))
265
+ assert Commutator.eval(c1, c1) == 0
266
+ c = Commutator(Fd(a)*F(i),Fd(b)*F(j))
267
+ assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]'
268
+ assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))'
269
+ assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]'
270
+
271
+
272
+ def test_create_f():
273
+ i, j, n, m = symbols('i,j,n,m')
274
+ o = Fd(i)
275
+ assert isinstance(o, CreateFermion)
276
+ o = o.subs(i, j)
277
+ assert o.atoms(Symbol) == {j}
278
+ o = Fd(1)
279
+ assert o.apply_operator(FKet([n])) == FKet([1, n])
280
+ assert o.apply_operator(FKet([n])) == -FKet([n, 1])
281
+ o = Fd(n)
282
+ assert o.apply_operator(FKet([])) == FKet([n])
283
+
284
+ vacuum = FKet([], fermi_level=4)
285
+ assert vacuum == FKet([], fermi_level=4)
286
+
287
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
288
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
289
+ p, q, r, s = symbols('p,q,r,s')
290
+
291
+ assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4)
292
+ assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4)
293
+
294
+ assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p)
295
+ assert repr(Fd(p)) == 'CreateFermion(p)'
296
+ assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))"
297
+ assert latex(Fd(p)) == r'{a^\dagger_{p}}'
298
+
299
+
300
+ def test_annihilate_f():
301
+ i, j, n, m = symbols('i,j,n,m')
302
+ o = F(i)
303
+ assert isinstance(o, AnnihilateFermion)
304
+ o = o.subs(i, j)
305
+ assert o.atoms(Symbol) == {j}
306
+ o = F(1)
307
+ assert o.apply_operator(FKet([1, n])) == FKet([n])
308
+ assert o.apply_operator(FKet([n, 1])) == -FKet([n])
309
+ o = F(n)
310
+ assert o.apply_operator(FKet([n])) == FKet([])
311
+
312
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
313
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
314
+ p, q, r, s = symbols('p,q,r,s')
315
+ assert F(i).apply_operator(FKet([i, j, k], 4)) == 0
316
+ assert F(a).apply_operator(FKet([i, b, k], 4)) == 0
317
+ assert F(l).apply_operator(FKet([i, j, k], 3)) == 0
318
+ assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4)
319
+ assert str(F(p)) == 'f(p)'
320
+ assert repr(F(p)) == 'AnnihilateFermion(p)'
321
+ assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))"
322
+ assert latex(F(p)) == 'a_{p}'
323
+
324
+
325
+ def test_create_b():
326
+ i, j, n, m = symbols('i,j,n,m')
327
+ o = Bd(i)
328
+ assert isinstance(o, CreateBoson)
329
+ o = o.subs(i, j)
330
+ assert o.atoms(Symbol) == {j}
331
+ o = Bd(0)
332
+ assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1])
333
+ o = Bd(n)
334
+ assert o.apply_operator(BKet([n])) == o*BKet([n])
335
+
336
+
337
+ def test_annihilate_b():
338
+ i, j, n, m = symbols('i,j,n,m')
339
+ o = B(i)
340
+ assert isinstance(o, AnnihilateBoson)
341
+ o = o.subs(i, j)
342
+ assert o.atoms(Symbol) == {j}
343
+ o = B(0)
344
+
345
+
346
+ def test_wicks():
347
+ p, q, r, s = symbols('p,q,r,s', above_fermi=True)
348
+
349
+ # Testing for particles only
350
+
351
+ str = F(p)*Fd(q)
352
+ assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q)
353
+ str = Fd(p)*F(q)
354
+ assert wicks(str) == NO(Fd(p)*F(q))
355
+
356
+ str = F(p)*Fd(q)*F(r)*Fd(s)
357
+ nstr = wicks(str)
358
+ fasit = NO(
359
+ KroneckerDelta(p, q)*KroneckerDelta(r, s)
360
+ + KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s)
361
+ + KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q)
362
+ - KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q)
363
+ - AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s))
364
+ assert nstr == fasit
365
+
366
+ assert (p*q*nstr).expand() == wicks(p*q*str)
367
+ assert (nstr*p*q*2).expand() == wicks(str*p*q*2)
368
+
369
+ # Testing CC equations particles and holes
370
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
371
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
372
+ p, q, r, s = symbols('p q r s', cls=Dummy)
373
+
374
+ assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) ==
375
+ NO(F(a)*F(i)*F(j)*Fd(b)) +
376
+ KroneckerDelta(a, b)*NO(F(i)*F(j)))
377
+ assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) ==
378
+ NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) -
379
+ KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k)))
380
+
381
+ expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l))
382
+ assert (expr ==
383
+ -KroneckerDelta(i, k)*NO(Fd(j)*F(l)) -
384
+ KroneckerDelta(j, l)*NO(Fd(i)*F(k)) -
385
+ KroneckerDelta(i, k)*KroneckerDelta(j, l) +
386
+ KroneckerDelta(i, l)*NO(Fd(j)*F(k)) +
387
+ NO(Fd(i)*Fd(j)*F(k)*F(l)))
388
+ expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d))
389
+ assert (expr ==
390
+ -KroneckerDelta(a, c)*NO(F(b)*Fd(d)) -
391
+ KroneckerDelta(b, d)*NO(F(a)*Fd(c)) -
392
+ KroneckerDelta(a, c)*KroneckerDelta(b, d) +
393
+ KroneckerDelta(a, d)*NO(F(b)*Fd(c)) +
394
+ NO(F(a)*F(b)*Fd(c)*Fd(d)))
395
+
396
+
397
+ def test_NO():
398
+ i, j, k, l = symbols('i j k l', below_fermi=True)
399
+ a, b, c, d = symbols('a b c d', above_fermi=True)
400
+ p, q, r, s = symbols('p q r s', cls=Dummy)
401
+
402
+ assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) ==
403
+ NO(Fd(p)*F(q)) + NO(Fd(a)*F(b)))
404
+ assert (NO(Fd(i)*NO(F(j)*Fd(a))) ==
405
+ NO(Fd(i)*F(j)*Fd(a)))
406
+ assert NO(1) == 1
407
+ assert NO(i) == i
408
+ assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) ==
409
+ NO(Fd(a)*Fd(b)*F(c)) +
410
+ NO(Fd(a)*Fd(b)*F(d)))
411
+
412
+ assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b)
413
+ assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i)
414
+
415
+ assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) ==
416
+ NO(Fd(a)*F(q)) + NO(Fd(i)*F(q)))
417
+ assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) ==
418
+ NO(Fd(p)*F(a)) + NO(Fd(p)*F(i)))
419
+
420
+ expr = NO(Fd(p)*F(q))._remove_brackets()
421
+ assert wicks(expr) == NO(expr)
422
+
423
+ assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a))
424
+
425
+ no = NO(Fd(a)*F(i)*F(b)*Fd(j))
426
+ l1 = list(no.iter_q_creators())
427
+ assert l1 == [0, 1]
428
+ l2 = list(no.iter_q_annihilators())
429
+ assert l2 == [3, 2]
430
+ no = NO(Fd(a)*Fd(i))
431
+ assert no.has_q_creators == 1
432
+ assert no.has_q_annihilators == -1
433
+ assert str(no) == ':CreateFermion(a)*CreateFermion(i):'
434
+ assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))'
435
+ assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}'
436
+ raises(NotImplementedError, lambda: NO(Bd(p)*F(q)))
437
+
438
+
439
+ def test_sorting():
440
+ i, j = symbols('i,j', below_fermi=True)
441
+ a, b = symbols('a,b', above_fermi=True)
442
+ p, q = symbols('p,q')
443
+
444
+ # p, q
445
+ assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0)
446
+ assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1)
447
+
448
+ # i, p
449
+ assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0)
450
+ assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1)
451
+ assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0)
452
+ assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1)
453
+ assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1)
454
+ assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0)
455
+ assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1)
456
+ assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0)
457
+
458
+ # a, p
459
+ assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1)
460
+ assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0)
461
+ assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1)
462
+ assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0)
463
+ assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0)
464
+ assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1)
465
+ assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0)
466
+ assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1)
467
+
468
+ # i, a
469
+ assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0)
470
+ assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1)
471
+ assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0)
472
+ assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1)
473
+ assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1)
474
+ assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0)
475
+
476
+
477
+ def test_contraction():
478
+ i, j, k, l = symbols('i,j,k,l', below_fermi=True)
479
+ a, b, c, d = symbols('a,b,c,d', above_fermi=True)
480
+ p, q, r, s = symbols('p,q,r,s')
481
+ assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j)
482
+ assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b)
483
+ assert contraction(F(a), Fd(i)) == 0
484
+ assert contraction(Fd(a), F(i)) == 0
485
+ assert contraction(F(i), Fd(a)) == 0
486
+ assert contraction(Fd(i), F(a)) == 0
487
+ assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p)
488
+ restr = evaluate_deltas(contraction(Fd(p), F(q)))
489
+ assert restr.is_only_below_fermi
490
+ restr = evaluate_deltas(contraction(F(p), Fd(q)))
491
+ assert restr.is_only_above_fermi
492
+ raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b)))
493
+
494
+
495
+ def test_evaluate_deltas():
496
+ i, j, k = symbols('i,j,k')
497
+
498
+ r = KroneckerDelta(i, j) * KroneckerDelta(j, k)
499
+ assert evaluate_deltas(r) == KroneckerDelta(i, k)
500
+
501
+ r = KroneckerDelta(i, 0) * KroneckerDelta(j, k)
502
+ assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k)
503
+
504
+ r = KroneckerDelta(1, j) * KroneckerDelta(j, k)
505
+ assert evaluate_deltas(r) == KroneckerDelta(1, k)
506
+
507
+ r = KroneckerDelta(j, 2) * KroneckerDelta(k, j)
508
+ assert evaluate_deltas(r) == KroneckerDelta(2, k)
509
+
510
+ r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1)
511
+ assert evaluate_deltas(r) == 0
512
+
513
+ r = (KroneckerDelta(0, i) * KroneckerDelta(0, j)
514
+ * KroneckerDelta(1, j) * KroneckerDelta(1, j))
515
+ assert evaluate_deltas(r) == 0
516
+
517
+
518
+ def test_Tensors():
519
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
520
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
521
+ p, q, r, s = symbols('p q r s')
522
+
523
+ AT = AntiSymmetricTensor
524
+ assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j))
525
+ assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i))
526
+ assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i))
527
+ assert AT('t', (a, a), (i, j)) == 0
528
+ assert AT('t', (a, b), (i, i)) == 0
529
+ assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j))
530
+ assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j))
531
+
532
+ tabij = AT('t', (a, b), (i, j))
533
+ assert tabij.has(a)
534
+ assert tabij.has(b)
535
+ assert tabij.has(i)
536
+ assert tabij.has(j)
537
+ assert tabij.subs(b, c) == AT('t', (a, c), (i, j))
538
+ assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j))
539
+ assert tabij.symbol == Symbol('t')
540
+ assert latex(tabij) == '{t^{ab}_{ij}}'
541
+ assert str(tabij) == 't((_a, _b),(_i, _j))'
542
+
543
+ assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j))
544
+ assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j))
545
+
546
+
547
+ def test_fully_contracted():
548
+ i, j, k, l = symbols('i j k l', below_fermi=True)
549
+ a, b, c, d = symbols('a b c d', above_fermi=True)
550
+ p, q, r, s = symbols('p q r s', cls=Dummy)
551
+
552
+ Fock = (AntiSymmetricTensor('f', (p,), (q,))*
553
+ NO(Fd(p)*F(q)))
554
+ V = (AntiSymmetricTensor('v', (p, q), (r, s))*
555
+ NO(Fd(p)*Fd(q)*F(s)*F(r)))/4
556
+
557
+ Fai = wicks(NO(Fd(i)*F(a))*Fock,
558
+ keep_only_fully_contracted=True,
559
+ simplify_kronecker_deltas=True)
560
+ assert Fai == AntiSymmetricTensor('f', (a,), (i,))
561
+ Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V,
562
+ keep_only_fully_contracted=True,
563
+ simplify_kronecker_deltas=True)
564
+ assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j))
565
+
566
+
567
+ def test_substitute_dummies_without_dummies():
568
+ i, j = symbols('i,j')
569
+ assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2
570
+ assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1
571
+
572
+
573
+ def test_substitute_dummies_NO_operator():
574
+ i, j = symbols('i j', cls=Dummy)
575
+ assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j))
576
+ - att(j, i)*NO(Fd(j)*F(i))) == 0
577
+
578
+
579
+ def test_substitute_dummies_SQ_operator():
580
+ i, j = symbols('i j', cls=Dummy)
581
+ assert substitute_dummies(att(i, j)*Fd(i)*F(j)
582
+ - att(j, i)*Fd(j)*F(i)) == 0
583
+
584
+
585
+ def test_substitute_dummies_new_indices():
586
+ i, j = symbols('i j', below_fermi=True, cls=Dummy)
587
+ a, b = symbols('a b', above_fermi=True, cls=Dummy)
588
+ p, q = symbols('p q', cls=Dummy)
589
+ f = Function('f')
590
+ assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0
591
+
592
+
593
+ def test_substitute_dummies_substitution_order():
594
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
595
+ f = Function('f')
596
+ from sympy.utilities.iterables import variations
597
+ for permut in variations([i, j, k, l], 4):
598
+ assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0
599
+
600
+
601
+ def test_dummy_order_inner_outer_lines_VT1T1T1():
602
+ ii = symbols('i', below_fermi=True)
603
+ aa = symbols('a', above_fermi=True)
604
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
605
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
606
+
607
+ v = Function('v')
608
+ t = Function('t')
609
+ dums = _get_ordered_dummies
610
+
611
+ # Coupled-Cluster T1 terms with V*T1*T1*T1
612
+ # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
613
+ exprs = [
614
+ # permut v and t <=> swapping internal lines, equivalent
615
+ # irrespective of symmetries in v
616
+ v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k),
617
+ v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l),
618
+ v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k),
619
+ v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l),
620
+ ]
621
+ for permut in exprs[1:]:
622
+ assert dums(exprs[0]) != dums(permut)
623
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
624
+
625
+
626
+ def test_dummy_order_inner_outer_lines_VT1T1T1T1():
627
+ ii, jj = symbols('i j', below_fermi=True)
628
+ aa, bb = symbols('a b', above_fermi=True)
629
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
630
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
631
+
632
+ v = Function('v')
633
+ t = Function('t')
634
+ dums = _get_ordered_dummies
635
+
636
+ # Coupled-Cluster T2 terms with V*T1*T1*T1*T1
637
+ exprs = [
638
+ # permut t <=> swapping external lines, not equivalent
639
+ # except if v has certain symmetries.
640
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
641
+ v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
642
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
643
+ v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
644
+ ]
645
+ for permut in exprs[1:]:
646
+ assert dums(exprs[0]) != dums(permut)
647
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
648
+ exprs = [
649
+ # permut v <=> swapping external lines, not equivalent
650
+ # except if v has certain symmetries.
651
+ #
652
+ # Note that in contrast to above, these permutations have identical
653
+ # dummy order. That is because the proximity to external indices
654
+ # has higher influence on the canonical dummy ordering than the
655
+ # position of a dummy on the factors. In fact, the terms here are
656
+ # similar in structure as the result of the dummy substitutions above.
657
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
658
+ v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
659
+ v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
660
+ v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
661
+ ]
662
+ for permut in exprs[1:]:
663
+ assert dums(exprs[0]) == dums(permut)
664
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
665
+ exprs = [
666
+ # permut t and v <=> swapping internal lines, equivalent.
667
+ # Canonical dummy order is different, and a consistent
668
+ # substitution reveals the equivalence.
669
+ v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l),
670
+ v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l),
671
+ v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l),
672
+ v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l),
673
+ ]
674
+ for permut in exprs[1:]:
675
+ assert dums(exprs[0]) != dums(permut)
676
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
677
+
678
+
679
+ def test_get_subNO():
680
+ p, q, r = symbols('p,q,r')
681
+ assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r))
682
+ assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r))
683
+ assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q))
684
+
685
+
686
+ def test_equivalent_internal_lines_VT1T1():
687
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
688
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
689
+
690
+ v = Function('v')
691
+ t = Function('t')
692
+ dums = _get_ordered_dummies
693
+
694
+ exprs = [ # permute v. Different dummy order. Not equivalent.
695
+ v(i, j, a, b)*t(a, i)*t(b, j),
696
+ v(j, i, a, b)*t(a, i)*t(b, j),
697
+ v(i, j, b, a)*t(a, i)*t(b, j),
698
+ ]
699
+ for permut in exprs[1:]:
700
+ assert dums(exprs[0]) != dums(permut)
701
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
702
+
703
+ exprs = [ # permute v. Different dummy order. Equivalent
704
+ v(i, j, a, b)*t(a, i)*t(b, j),
705
+ v(j, i, b, a)*t(a, i)*t(b, j),
706
+ ]
707
+ for permut in exprs[1:]:
708
+ assert dums(exprs[0]) != dums(permut)
709
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
710
+
711
+ exprs = [ # permute t. Same dummy order, not equivalent.
712
+ v(i, j, a, b)*t(a, i)*t(b, j),
713
+ v(i, j, a, b)*t(b, i)*t(a, j),
714
+ ]
715
+ for permut in exprs[1:]:
716
+ assert dums(exprs[0]) == dums(permut)
717
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
718
+
719
+ exprs = [ # permute v and t. Different dummy order, equivalent
720
+ v(i, j, a, b)*t(a, i)*t(b, j),
721
+ v(j, i, a, b)*t(a, j)*t(b, i),
722
+ v(i, j, b, a)*t(b, i)*t(a, j),
723
+ v(j, i, b, a)*t(b, j)*t(a, i),
724
+ ]
725
+ for permut in exprs[1:]:
726
+ assert dums(exprs[0]) != dums(permut)
727
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
728
+
729
+
730
+ def test_equivalent_internal_lines_VT2conjT2():
731
+ # this diagram requires special handling in TCE
732
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
733
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
734
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
735
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
736
+
737
+ from sympy.utilities.iterables import variations
738
+
739
+ v = Function('v')
740
+ t = Function('t')
741
+ dums = _get_ordered_dummies
742
+
743
+ # v(abcd)t(abij)t(ijcd)
744
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4)
745
+ permutator = variations([a, b, c, d], 4)
746
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
747
+ for permut in permutator:
748
+ subslist = zip([p1, p2, p3, p4], permut)
749
+ expr = template.subs(subslist)
750
+ assert dums(base) != dums(expr)
751
+ assert substitute_dummies(expr) == substitute_dummies(base)
752
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4)
753
+ permutator = variations([a, b, c, d], 4)
754
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
755
+ for permut in permutator:
756
+ subslist = zip([p1, p2, p3, p4], permut)
757
+ expr = template.subs(subslist)
758
+ assert dums(base) != dums(expr)
759
+ assert substitute_dummies(expr) == substitute_dummies(base)
760
+
761
+ # v(abcd)t(abij)t(jicd)
762
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4)
763
+ permutator = variations([a, b, c, d], 4)
764
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
765
+ for permut in permutator:
766
+ subslist = zip([p1, p2, p3, p4], permut)
767
+ expr = template.subs(subslist)
768
+ assert dums(base) != dums(expr)
769
+ assert substitute_dummies(expr) == substitute_dummies(base)
770
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4)
771
+ permutator = variations([a, b, c, d], 4)
772
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
773
+ for permut in permutator:
774
+ subslist = zip([p1, p2, p3, p4], permut)
775
+ expr = template.subs(subslist)
776
+ assert dums(base) != dums(expr)
777
+ assert substitute_dummies(expr) == substitute_dummies(base)
778
+
779
+
780
+ def test_equivalent_internal_lines_VT2conjT2_ambiguous_order():
781
+ # These diagrams invokes _determine_ambiguous() because the
782
+ # dummies can not be ordered unambiguously by the key alone
783
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
784
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
785
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
786
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
787
+
788
+ from sympy.utilities.iterables import variations
789
+
790
+ v = Function('v')
791
+ t = Function('t')
792
+ dums = _get_ordered_dummies
793
+
794
+ # v(abcd)t(abij)t(cdij)
795
+ template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j)
796
+ permutator = variations([a, b, c, d], 4)
797
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
798
+ for permut in permutator:
799
+ subslist = zip([p1, p2, p3, p4], permut)
800
+ expr = template.subs(subslist)
801
+ assert dums(base) != dums(expr)
802
+ assert substitute_dummies(expr) == substitute_dummies(base)
803
+ template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j)
804
+ permutator = variations([a, b, c, d], 4)
805
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
806
+ for permut in permutator:
807
+ subslist = zip([p1, p2, p3, p4], permut)
808
+ expr = template.subs(subslist)
809
+ assert dums(base) != dums(expr)
810
+ assert substitute_dummies(expr) == substitute_dummies(base)
811
+
812
+
813
+ def test_equivalent_internal_lines_VT2():
814
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
815
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
816
+
817
+ v = Function('v')
818
+ t = Function('t')
819
+ dums = _get_ordered_dummies
820
+ exprs = [
821
+ # permute v. Same dummy order, not equivalent.
822
+ #
823
+ # This test show that the dummy order may not be sensitive to all
824
+ # index permutations. The following expressions have identical
825
+ # structure as the resulting terms from of the dummy substitutions
826
+ # in the test above. Here, all expressions have the same dummy
827
+ # order, so they cannot be simplified by means of dummy
828
+ # substitution. In order to simplify further, it is necessary to
829
+ # exploit symmetries in the objects, for instance if t or v is
830
+ # antisymmetric.
831
+ v(i, j, a, b)*t(a, b, i, j),
832
+ v(j, i, a, b)*t(a, b, i, j),
833
+ v(i, j, b, a)*t(a, b, i, j),
834
+ v(j, i, b, a)*t(a, b, i, j),
835
+ ]
836
+ for permut in exprs[1:]:
837
+ assert dums(exprs[0]) == dums(permut)
838
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
839
+
840
+ exprs = [
841
+ # permute t.
842
+ v(i, j, a, b)*t(a, b, i, j),
843
+ v(i, j, a, b)*t(b, a, i, j),
844
+ v(i, j, a, b)*t(a, b, j, i),
845
+ v(i, j, a, b)*t(b, a, j, i),
846
+ ]
847
+ for permut in exprs[1:]:
848
+ assert dums(exprs[0]) != dums(permut)
849
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
850
+
851
+ exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
852
+ v(i, j, a, b)*t(a, b, i, j),
853
+ v(j, i, a, b)*t(a, b, j, i),
854
+ v(i, j, b, a)*t(b, a, i, j),
855
+ v(j, i, b, a)*t(b, a, j, i),
856
+ ]
857
+ for permut in exprs[1:]:
858
+ assert dums(exprs[0]) != dums(permut)
859
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
860
+
861
+
862
+ def test_internal_external_VT2T2():
863
+ ii, jj = symbols('i j', below_fermi=True)
864
+ aa, bb = symbols('a b', above_fermi=True)
865
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
866
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
867
+
868
+ v = Function('v')
869
+ t = Function('t')
870
+ dums = _get_ordered_dummies
871
+
872
+ exprs = [
873
+ v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
874
+ v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
875
+ v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
876
+ v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
877
+ ]
878
+ for permut in exprs[1:]:
879
+ assert dums(exprs[0]) != dums(permut)
880
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
881
+ exprs = [
882
+ v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l),
883
+ v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k),
884
+ v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l),
885
+ v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k),
886
+ ]
887
+ for permut in exprs[1:]:
888
+ assert dums(exprs[0]) != dums(permut)
889
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
890
+ exprs = [
891
+ v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l),
892
+ v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k),
893
+ v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l),
894
+ v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k),
895
+ ]
896
+ for permut in exprs[1:]:
897
+ assert dums(exprs[0]) != dums(permut)
898
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
899
+
900
+
901
+ def test_internal_external_pqrs():
902
+ ii, jj = symbols('i j')
903
+ aa, bb = symbols('a b')
904
+ k, l = symbols('k l', cls=Dummy)
905
+ c, d = symbols('c d', cls=Dummy)
906
+
907
+ v = Function('v')
908
+ t = Function('t')
909
+ dums = _get_ordered_dummies
910
+
911
+ exprs = [
912
+ v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l),
913
+ v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k),
914
+ v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l),
915
+ v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k),
916
+ ]
917
+ for permut in exprs[1:]:
918
+ assert dums(exprs[0]) != dums(permut)
919
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
920
+
921
+
922
+ def test_dummy_order_well_defined():
923
+ aa, bb = symbols('a b', above_fermi=True)
924
+ k, l, m = symbols('k l m', below_fermi=True, cls=Dummy)
925
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
926
+ p, q = symbols('p q', cls=Dummy)
927
+
928
+ A = Function('A')
929
+ B = Function('B')
930
+ C = Function('C')
931
+ dums = _get_ordered_dummies
932
+
933
+ # We go through all key components in the order of increasing priority,
934
+ # and consider only fully orderable expressions. Non-orderable expressions
935
+ # are tested elsewhere.
936
+
937
+ # pos in first factor determines sort order
938
+ assert dums(A(k, l)*B(l, k)) == [k, l]
939
+ assert dums(A(l, k)*B(l, k)) == [l, k]
940
+ assert dums(A(k, l)*B(k, l)) == [k, l]
941
+ assert dums(A(l, k)*B(k, l)) == [l, k]
942
+
943
+ # factors involving the index
944
+ assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m]
945
+ assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m]
946
+ assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m]
947
+ assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m]
948
+ assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m]
949
+ assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m]
950
+ assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m]
951
+ assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m]
952
+
953
+ # same, but with factor order determined by non-dummies
954
+ assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
955
+ assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
956
+ assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
957
+ assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
958
+ assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m]
959
+ assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m]
960
+ assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m]
961
+ assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m]
962
+
963
+ # index range
964
+ assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p]
965
+ assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p]
966
+ assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p]
967
+ assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p]
968
+ assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p]
969
+ assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p]
970
+ assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p]
971
+ assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p]
972
+ assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p]
973
+ assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p]
974
+ assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p]
975
+ assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p]
976
+
977
+
978
+ def test_dummy_order_ambiguous():
979
+ aa, bb = symbols('a b', above_fermi=True)
980
+ i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy)
981
+ a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy)
982
+ p, q = symbols('p q', cls=Dummy)
983
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
984
+ p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy)
985
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
986
+ h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy)
987
+
988
+ A = Function('A')
989
+ B = Function('B')
990
+
991
+ from sympy.utilities.iterables import variations
992
+
993
+ # A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest
994
+ template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4)
995
+ permutator = variations([a, b, c, d, e], 5)
996
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
997
+ for permut in permutator:
998
+ subslist = zip([p1, p2, p3, p4, p5], permut)
999
+ expr = template.subs(subslist)
1000
+ assert substitute_dummies(expr) == substitute_dummies(base)
1001
+
1002
+ # A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out
1003
+ template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4)
1004
+ permutator = variations([a, b, c, d, e], 5)
1005
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
1006
+ for permut in permutator:
1007
+ subslist = zip([p1, p2, p3, p4, p5], permut)
1008
+ expr = template.subs(subslist)
1009
+ assert substitute_dummies(expr) == substitute_dummies(base)
1010
+
1011
+ # A*A*A -- ordering of p5 and p4 is used to figure out the rest
1012
+ template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4)
1013
+ permutator = variations([a, b, c, d, e], 5)
1014
+ base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator)))
1015
+ for permut in permutator:
1016
+ subslist = zip([p1, p2, p3, p4, p5], permut)
1017
+ expr = template.subs(subslist)
1018
+ assert substitute_dummies(expr) == substitute_dummies(base)
1019
+
1020
+
1021
+ def atv(*args):
1022
+ return AntiSymmetricTensor('v', args[:2], args[2:] )
1023
+
1024
+
1025
+ def att(*args):
1026
+ if len(args) == 4:
1027
+ return AntiSymmetricTensor('t', args[:2], args[2:] )
1028
+ elif len(args) == 2:
1029
+ return AntiSymmetricTensor('t', (args[0],), (args[1],))
1030
+
1031
+
1032
+ def test_dummy_order_inner_outer_lines_VT1T1T1_AT():
1033
+ ii = symbols('i', below_fermi=True)
1034
+ aa = symbols('a', above_fermi=True)
1035
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1036
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1037
+
1038
+ # Coupled-Cluster T1 terms with V*T1*T1*T1
1039
+ # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc}
1040
+ exprs = [
1041
+ # permut v and t <=> swapping internal lines, equivalent
1042
+ # irrespective of symmetries in v
1043
+ atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k),
1044
+ atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l),
1045
+ atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k),
1046
+ atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l),
1047
+ ]
1048
+ for permut in exprs[1:]:
1049
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1050
+
1051
+
1052
+ def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT():
1053
+ ii, jj = symbols('i j', below_fermi=True)
1054
+ aa, bb = symbols('a b', above_fermi=True)
1055
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1056
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1057
+
1058
+ # Coupled-Cluster T2 terms with V*T1*T1*T1*T1
1059
+ # non-equivalent substitutions (change of sign)
1060
+ exprs = [
1061
+ # permut t <=> swapping external lines
1062
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
1063
+ atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l),
1064
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l),
1065
+ ]
1066
+ for permut in exprs[1:]:
1067
+ assert substitute_dummies(exprs[0]) == -substitute_dummies(permut)
1068
+
1069
+ # equivalent substitutions
1070
+ exprs = [
1071
+ atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l),
1072
+ # permut t <=> swapping external lines
1073
+ atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l),
1074
+ ]
1075
+ for permut in exprs[1:]:
1076
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1077
+
1078
+
1079
+ def test_equivalent_internal_lines_VT1T1_AT():
1080
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
1081
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
1082
+
1083
+ exprs = [ # permute v. Different dummy order. Not equivalent.
1084
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1085
+ atv(j, i, a, b)*att(a, i)*att(b, j),
1086
+ atv(i, j, b, a)*att(a, i)*att(b, j),
1087
+ ]
1088
+ for permut in exprs[1:]:
1089
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1090
+
1091
+ exprs = [ # permute v. Different dummy order. Equivalent
1092
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1093
+ atv(j, i, b, a)*att(a, i)*att(b, j),
1094
+ ]
1095
+ for permut in exprs[1:]:
1096
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1097
+
1098
+ exprs = [ # permute t. Same dummy order, not equivalent.
1099
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1100
+ atv(i, j, a, b)*att(b, i)*att(a, j),
1101
+ ]
1102
+ for permut in exprs[1:]:
1103
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1104
+
1105
+ exprs = [ # permute v and t. Different dummy order, equivalent
1106
+ atv(i, j, a, b)*att(a, i)*att(b, j),
1107
+ atv(j, i, a, b)*att(a, j)*att(b, i),
1108
+ atv(i, j, b, a)*att(b, i)*att(a, j),
1109
+ atv(j, i, b, a)*att(b, j)*att(a, i),
1110
+ ]
1111
+ for permut in exprs[1:]:
1112
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1113
+
1114
+
1115
+ def test_equivalent_internal_lines_VT2conjT2_AT():
1116
+ # this diagram requires special handling in TCE
1117
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
1118
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
1119
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
1120
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
1121
+
1122
+ from sympy.utilities.iterables import variations
1123
+
1124
+ # atv(abcd)att(abij)att(ijcd)
1125
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4)
1126
+ permutator = variations([a, b, c, d], 4)
1127
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1128
+ for permut in permutator:
1129
+ subslist = zip([p1, p2, p3, p4], permut)
1130
+ expr = template.subs(subslist)
1131
+ assert substitute_dummies(expr) == substitute_dummies(base)
1132
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4)
1133
+ permutator = variations([a, b, c, d], 4)
1134
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1135
+ for permut in permutator:
1136
+ subslist = zip([p1, p2, p3, p4], permut)
1137
+ expr = template.subs(subslist)
1138
+ assert substitute_dummies(expr) == substitute_dummies(base)
1139
+
1140
+ # atv(abcd)att(abij)att(jicd)
1141
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4)
1142
+ permutator = variations([a, b, c, d], 4)
1143
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1144
+ for permut in permutator:
1145
+ subslist = zip([p1, p2, p3, p4], permut)
1146
+ expr = template.subs(subslist)
1147
+ assert substitute_dummies(expr) == substitute_dummies(base)
1148
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4)
1149
+ permutator = variations([a, b, c, d], 4)
1150
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1151
+ for permut in permutator:
1152
+ subslist = zip([p1, p2, p3, p4], permut)
1153
+ expr = template.subs(subslist)
1154
+ assert substitute_dummies(expr) == substitute_dummies(base)
1155
+
1156
+
1157
+ def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT():
1158
+ # These diagrams invokes _determine_ambiguous() because the
1159
+ # dummies can not be ordered unambiguously by the key alone
1160
+ i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy)
1161
+ a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy)
1162
+ p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy)
1163
+ h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy)
1164
+
1165
+ from sympy.utilities.iterables import variations
1166
+
1167
+ # atv(abcd)att(abij)att(cdij)
1168
+ template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j)
1169
+ permutator = variations([a, b, c, d], 4)
1170
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1171
+ for permut in permutator:
1172
+ subslist = zip([p1, p2, p3, p4], permut)
1173
+ expr = template.subs(subslist)
1174
+ assert substitute_dummies(expr) == substitute_dummies(base)
1175
+ template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j)
1176
+ permutator = variations([a, b, c, d], 4)
1177
+ base = template.subs(zip([p1, p2, p3, p4], next(permutator)))
1178
+ for permut in permutator:
1179
+ subslist = zip([p1, p2, p3, p4], permut)
1180
+ expr = template.subs(subslist)
1181
+ assert substitute_dummies(expr) == substitute_dummies(base)
1182
+
1183
+
1184
+ def test_equivalent_internal_lines_VT2_AT():
1185
+ i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy)
1186
+ a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy)
1187
+
1188
+ exprs = [
1189
+ # permute v. Same dummy order, not equivalent.
1190
+ atv(i, j, a, b)*att(a, b, i, j),
1191
+ atv(j, i, a, b)*att(a, b, i, j),
1192
+ atv(i, j, b, a)*att(a, b, i, j),
1193
+ ]
1194
+ for permut in exprs[1:]:
1195
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1196
+
1197
+ exprs = [
1198
+ # permute t.
1199
+ atv(i, j, a, b)*att(a, b, i, j),
1200
+ atv(i, j, a, b)*att(b, a, i, j),
1201
+ atv(i, j, a, b)*att(a, b, j, i),
1202
+ ]
1203
+ for permut in exprs[1:]:
1204
+ assert substitute_dummies(exprs[0]) != substitute_dummies(permut)
1205
+
1206
+ exprs = [ # permute v and t. Relabelling of dummies should be equivalent.
1207
+ atv(i, j, a, b)*att(a, b, i, j),
1208
+ atv(j, i, a, b)*att(a, b, j, i),
1209
+ atv(i, j, b, a)*att(b, a, i, j),
1210
+ atv(j, i, b, a)*att(b, a, j, i),
1211
+ ]
1212
+ for permut in exprs[1:]:
1213
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1214
+
1215
+
1216
+ def test_internal_external_VT2T2_AT():
1217
+ ii, jj = symbols('i j', below_fermi=True)
1218
+ aa, bb = symbols('a b', above_fermi=True)
1219
+ k, l = symbols('k l', below_fermi=True, cls=Dummy)
1220
+ c, d = symbols('c d', above_fermi=True, cls=Dummy)
1221
+
1222
+ exprs = [
1223
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
1224
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
1225
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
1226
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
1227
+ ]
1228
+ for permut in exprs[1:]:
1229
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1230
+ exprs = [
1231
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l),
1232
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k),
1233
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l),
1234
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k),
1235
+ ]
1236
+ for permut in exprs[1:]:
1237
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1238
+ exprs = [
1239
+ atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l),
1240
+ atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k),
1241
+ atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l),
1242
+ atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k),
1243
+ ]
1244
+ for permut in exprs[1:]:
1245
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1246
+
1247
+
1248
+ def test_internal_external_pqrs_AT():
1249
+ ii, jj = symbols('i j')
1250
+ aa, bb = symbols('a b')
1251
+ k, l = symbols('k l', cls=Dummy)
1252
+ c, d = symbols('c d', cls=Dummy)
1253
+
1254
+ exprs = [
1255
+ atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l),
1256
+ atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k),
1257
+ atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l),
1258
+ atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k),
1259
+ ]
1260
+ for permut in exprs[1:]:
1261
+ assert substitute_dummies(exprs[0]) == substitute_dummies(permut)
1262
+
1263
+
1264
+ def test_issue_19661():
1265
+ a = Symbol('0')
1266
+ assert latex(Commutator(Bd(a)**2, B(a))
1267
+ ) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]'
1268
+
1269
+
1270
+ def test_canonical_ordering_AntiSymmetricTensor():
1271
+ v = symbols("v")
1272
+
1273
+ c, d = symbols(('c','d'), above_fermi=True,
1274
+ cls=Dummy)
1275
+ k, l = symbols(('k','l'), below_fermi=True,
1276
+ cls=Dummy)
1277
+
1278
+ # formerly, the left gave either the left or the right
1279
+ assert AntiSymmetricTensor(v, (k, l), (d, c)
1280
+ ) == -AntiSymmetricTensor(v, (l, k), (d, c))
llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_sho.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols, Rational, Function, diff
2
+ from sympy.physics.sho import R_nl, E_nl
3
+ from sympy.simplify.simplify import simplify
4
+
5
+
6
+ def test_sho_R_nl():
7
+ omega, r = symbols('omega r')
8
+ l = symbols('l', integer=True)
9
+ u = Function('u')
10
+
11
+ # check that it obeys the Schrodinger equation
12
+ for n in range(5):
13
+ schreq = ( -diff(u(r), r, 2)/2 + ((l*(l + 1))/(2*r**2)
14
+ + omega**2*r**2/2 - E_nl(n, l, omega))*u(r) )
15
+ result = schreq.subs(u(r), r*R_nl(n, l, omega/2, r))
16
+ assert simplify(result.doit()) == 0
17
+
18
+
19
+ def test_energy():
20
+ n, l, hw = symbols('n l hw')
21
+ assert simplify(E_nl(n, l, hw) - (2*n + l + Rational(3, 2))*hw) == 0