diff --git a/llmeval-env/lib/python3.10/site-packages/jinja2-3.1.4.dist-info/entry_points.txt b/llmeval-env/lib/python3.10/site-packages/jinja2-3.1.4.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..abc3eae3b3bc573957cf7401711948799b3465c0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/jinja2-3.1.4.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91e1a325dc7ba81076b523ec4f283b8247f6c122 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/__init__.py @@ -0,0 +1,535 @@ +""" +SymPy is a Python library for symbolic mathematics. It aims to become a +full-featured computer algebra system (CAS) while keeping the code as simple +as possible in order to be comprehensible and easily extensible. SymPy is +written entirely in Python. It depends on mpmath, and other external libraries +may be optionally for things like plotting support. + +See the webpage for more information and documentation: + + https://sympy.org + +""" + + +import sys +if sys.version_info < (3, 8): + raise ImportError("Python version 3.8 or above is required for SymPy.") +del sys + + +try: + import mpmath +except ImportError: + raise ImportError("SymPy now depends on mpmath as an external library. " + "See https://docs.sympy.org/latest/install.html#mpmath for more information.") + +del mpmath + +from sympy.release import __version__ +from sympy.core.cache import lazy_function + +if 'dev' in __version__: + def enable_warnings(): + import warnings + warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') + del warnings + enable_warnings() + del enable_warnings + + +def __sympy_debug(): + # helper function so we don't import os globally + import os + debug_str = os.getenv('SYMPY_DEBUG', 'False') + if debug_str in ('True', 'False'): + return eval(debug_str) + else: + raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % + debug_str) +SYMPY_DEBUG = __sympy_debug() # type: bool + +from .core import (sympify, SympifyError, cacheit, Basic, Atom, + preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, + Wild, Dummy, symbols, var, Number, Float, Rational, Integer, + NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, + AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, + Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, + GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, + vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, + Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, + expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, + expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, + evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, + Catalan, EulerGamma, GoldenRatio, TribonacciConstant, bottom_up, use, + postorder_traversal, default_sort_key, ordered) + +from .logic import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, + Implies, Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, + true, false, satisfiable) + +from .assumptions import (AppliedPredicate, Predicate, AssumptionsContext, + assuming, Q, ask, register_handler, remove_handler, refine) + +from .polys import (Poly, PurePoly, poly_from_expr, parallel_poly_from_expr, + degree, total_degree, degree_list, LC, LM, LT, pdiv, prem, pquo, + pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, + subresultants, resultant, discriminant, cofactors, gcd_list, gcd, + lcm_list, lcm, terms_gcd, trunc, monic, content, primitive, compose, + decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, + factor_list, factor, intervals, refine_root, count_roots, real_roots, + nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, + is_zero_dimensional, GroebnerBasis, poly, symmetrize, horner, + interpolate, rational_interpolate, viete, together, + BasePolynomialError, ExactQuotientFailed, PolynomialDivisionFailed, + OperationNotSupported, HeuristicGCDFailed, HomomorphismFailed, + IsomorphismFailed, ExtraneousFactors, EvaluationFailed, + RefinementFailed, CoercionFailed, NotInvertible, NotReversible, + NotAlgebraic, DomainError, PolynomialError, UnificationFailed, + GeneratorsError, GeneratorsNeeded, ComputationFailed, + UnivariatePolynomialError, MultivariatePolynomialError, + PolificationFailed, OptionError, FlagError, minpoly, + minimal_polynomial, primitive_element, field_isomorphism, + to_number_field, isolate, round_two, prime_decomp, prime_valuation, + galois_group, itermonomials, Monomial, lex, grlex, + grevlex, ilex, igrlex, igrevlex, CRootOf, rootof, RootOf, + ComplexRootOf, RootSum, roots, Domain, FiniteField, IntegerRing, + RationalField, RealField, ComplexField, PythonFiniteField, + GMPYFiniteField, PythonIntegerRing, GMPYIntegerRing, PythonRational, + GMPYRationalField, AlgebraicField, PolynomialRing, FractionField, + ExpressionDomain, FF_python, FF_gmpy, ZZ_python, ZZ_gmpy, QQ_python, + QQ_gmpy, GF, FF, ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX, EXRAW, + construct_domain, swinnerton_dyer_poly, cyclotomic_poly, + symmetric_poly, random_poly, interpolating_poly, jacobi_poly, + chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly, + legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, + Options, ring, xring, vring, sring, field, xfield, vfield, sfield) + +from .series import (Order, O, limit, Limit, gruntz, series, approximants, + residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, + fourier_series, fps, difference_delta, limit_seq) + +from .functions import (factorial, factorial2, rf, ff, binomial, + RisingFactorial, FallingFactorial, subfactorial, carmichael, + fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, + catalan, genocchi, andre, partition, sqrt, root, Min, Max, Id, + real_root, Rem, cbrt, re, im, sign, Abs, conjugate, arg, polar_lift, + periodic_argument, unbranched_argument, principal_branch, transpose, + adjoint, polarify, unpolarify, sin, cos, tan, sec, csc, cot, sinc, + asin, acos, atan, asec, acsc, acot, atan2, exp_polar, exp, ln, log, + LambertW, sinh, cosh, tanh, coth, sech, csch, asinh, acosh, atanh, + acoth, asech, acsch, floor, ceiling, frac, Piecewise, piecewise_fold, + piecewise_exclusive, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, + Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, + lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, + multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, + LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, + bspline_basis, bspline_basis_set, interpolating_spline, besselj, + bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, + hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, + meijerg, appellf1, legendre, assoc_legendre, hermite, hermite_prob, + chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, + assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, + Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, + mathieuc, mathieusprime, mathieucprime, riemann_xi, betainc, betainc_regularized) + +from .ntheory import (nextprime, prevprime, prime, primepi, primerange, + randprime, Sieve, sieve, primorial, cycle_length, composite, + compositepi, isprime, divisors, proper_divisors, factorint, + multiplicity, perfect_power, pollard_pm1, pollard_rho, primefactors, + totient, trailing, divisor_count, proper_divisor_count, divisor_sigma, + factorrat, reduced_totient, primenu, primeomega, + mersenne_prime_exponent, is_perfect, is_mersenne_prime, is_abundant, + is_deficient, is_amicable, abundance, npartitions, is_primitive_root, + is_quad_residue, legendre_symbol, jacobi_symbol, n_order, sqrt_mod, + quadratic_residues, primitive_root, nthroot_mod, is_nthpow_residue, + sqrt_mod_iter, mobius, discrete_log, quadratic_congruence, + binomial_coefficients, binomial_coefficients_list, + multinomial_coefficients, continued_fraction_periodic, + continued_fraction_iterator, continued_fraction_reduce, + continued_fraction_convergents, continued_fraction, egyptian_fraction) + +from .concrete import product, Product, summation, Sum + +from .discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, + inverse_mobius_transform, convolution, covering_product, + intersecting_product) + +from .simplify import (simplify, hypersimp, hypersimilar, logcombine, + separatevars, posify, besselsimp, kroneckersimp, signsimp, + nsimplify, FU, fu, sqrtdenest, cse, epath, EPath, hyperexpand, + collect, rcollect, radsimp, collect_const, fraction, numer, denom, + trigsimp, exptrigsimp, powsimp, powdenest, combsimp, gammasimp, + ratsimp, ratsimpmodprime) + +from .sets import (Set, Interval, Union, EmptySet, FiniteSet, ProductSet, + Intersection, DisjointUnion, imageset, Complement, SymmetricDifference, ImageSet, + Range, ComplexRegion, Complexes, Reals, Contains, ConditionSet, Ordinal, + OmegaPower, ord0, PowerSet, Naturals, Naturals0, UniversalSet, + Integers, Rationals) + +from .solvers import (solve, solve_linear_system, solve_linear_system_LU, + solve_undetermined_coeffs, nsolve, solve_linear, checksol, det_quick, + inv_quick, check_assumptions, failing_assumptions, diophantine, + rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper, checkodesol, + classify_ode, dsolve, homogeneous_order, solve_poly_system, + solve_triangulated, pde_separate, pde_separate_add, pde_separate_mul, + pdsolve, classify_pde, checkpdesol, ode_order, reduce_inequalities, + reduce_abs_inequality, reduce_abs_inequalities, solve_poly_inequality, + solve_rational_inequalities, solve_univariate_inequality, decompogen, + solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution) + +from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, + casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, + matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, + rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, + DeferredVector, MatrixBase, Matrix, MutableMatrix, + MutableSparseMatrix, banded, ImmutableDenseMatrix, + ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, + BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, + MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, + ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, + Adjoint, hadamard_product, HadamardProduct, HadamardPower, + Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, + DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, + PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1, + rot_ccw_axis2, rot_ccw_axis3, rot_givens) + +from .geometry import (Point, Point2D, Point3D, Line, Ray, Segment, Line2D, + Segment2D, Ray2D, Line3D, Segment3D, Ray3D, Plane, Ellipse, Circle, + Polygon, RegularPolygon, Triangle, rad, deg, are_similar, centroid, + convex_hull, idiff, intersection, closest_points, farthest_points, + GeometryError, Curve, Parabola) + +from .utilities import (flatten, group, take, subsets, variations, + numbered_symbols, cartes, capture, dict_merge, prefixes, postfixes, + sift, topological_sort, unflatten, has_dups, has_variety, reshape, + rotations, filldedent, lambdify, + threaded, xthreaded, public, memoize_property, timed) + +from .integrals import (integrate, Integral, line_integrate, mellin_transform, + inverse_mellin_transform, MellinTransform, InverseMellinTransform, + laplace_transform, inverse_laplace_transform, LaplaceTransform, + InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, + FourierTransform, InverseFourierTransform, sine_transform, + inverse_sine_transform, SineTransform, InverseSineTransform, + cosine_transform, inverse_cosine_transform, CosineTransform, + InverseCosineTransform, hankel_transform, inverse_hankel_transform, + HankelTransform, InverseHankelTransform, singularityintegrate) + +from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, + get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, + MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, + tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, + permutedims, Array, DenseNDimArray, SparseNDimArray) + +from .parsing import parse_expr + +from .calculus import (euler_equations, singularities, is_increasing, + is_strictly_increasing, is_decreasing, is_strictly_decreasing, + is_monotonic, finite_diff_weights, apply_finite_diff, + differentiate_finite, periodicity, not_empty_in, AccumBounds, + is_convex, stationary_points, minimum, maximum) + +from .algebras import Quaternion + +from .printing import (pager_print, pretty, pretty_print, pprint, + pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, + multiline_latex, mathml, print_mathml, python, print_python, pycode, + ccode, print_ccode, smtlib_code, glsl_code, print_glsl, cxxcode, fcode, + print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, + mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, + print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, + maple_code, print_maple_code) + +test = lazy_function('sympy.testing.runtests', 'test') +doctest = lazy_function('sympy.testing.runtests', 'doctest') + +# This module causes conflicts with other modules: +# from .stats import * +# Adds about .04-.05 seconds of import time +# from combinatorics import * +# This module is slow to import: +#from physics import units +from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric +from .interactive import init_session, init_printing, interactive_traversal + +evalf._create_evalf_table() + +__all__ = [ + '__version__', + + # sympy.core + 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', + 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', + 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', + 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', + 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', + 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod', + 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', + 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', + 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', + 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', + 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', + 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', + 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', + 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', + 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', 'bottom_up', 'use', + 'postorder_traversal', 'default_sort_key', 'ordered', + + # sympy.logic + 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor', + 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic', + 'bool_map', 'true', 'false', 'satisfiable', + + # sympy.assumptions + 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'Q', + 'ask', 'register_handler', 'remove_handler', 'refine', + + # sympy.polys + 'Poly', 'PurePoly', 'poly_from_expr', 'parallel_poly_from_expr', 'degree', + 'total_degree', 'degree_list', 'LC', 'LM', 'LT', 'pdiv', 'prem', 'pquo', + 'pexquo', 'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex', 'invert', + 'subresultants', 'resultant', 'discriminant', 'cofactors', 'gcd_list', + 'gcd', 'lcm_list', 'lcm', 'terms_gcd', 'trunc', 'monic', 'content', + 'primitive', 'compose', 'decompose', 'sturm', 'gff_list', 'gff', + 'sqf_norm', 'sqf_part', 'sqf_list', 'sqf', 'factor_list', 'factor', + 'intervals', 'refine_root', 'count_roots', 'real_roots', 'nroots', + 'ground_roots', 'nth_power_roots_poly', 'cancel', 'reduced', 'groebner', + 'is_zero_dimensional', 'GroebnerBasis', 'poly', 'symmetrize', 'horner', + 'interpolate', 'rational_interpolate', 'viete', 'together', + 'BasePolynomialError', 'ExactQuotientFailed', 'PolynomialDivisionFailed', + 'OperationNotSupported', 'HeuristicGCDFailed', 'HomomorphismFailed', + 'IsomorphismFailed', 'ExtraneousFactors', 'EvaluationFailed', + 'RefinementFailed', 'CoercionFailed', 'NotInvertible', 'NotReversible', + 'NotAlgebraic', 'DomainError', 'PolynomialError', 'UnificationFailed', + 'GeneratorsError', 'GeneratorsNeeded', 'ComputationFailed', + 'UnivariatePolynomialError', 'MultivariatePolynomialError', + 'PolificationFailed', 'OptionError', 'FlagError', 'minpoly', + 'minimal_polynomial', 'primitive_element', 'field_isomorphism', + 'to_number_field', 'isolate', 'round_two', 'prime_decomp', + 'prime_valuation', 'galois_group', 'itermonomials', 'Monomial', 'lex', 'grlex', + 'grevlex', 'ilex', 'igrlex', 'igrevlex', 'CRootOf', 'rootof', 'RootOf', + 'ComplexRootOf', 'RootSum', 'roots', 'Domain', 'FiniteField', + 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', + 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', + 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', + 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', + 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', + 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', + 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', + 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', + 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly', + 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', + 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', + 'sfield', + + # sympy.series + 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', + 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', + 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', + + # sympy.functions + 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', + 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', + 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', + 'genocchi', 'andre', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', + 'Rem', 'cbrt', 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift', + 'periodic_argument', 'unbranched_argument', 'principal_branch', + 'transpose', 'adjoint', 'polarify', 'unpolarify', 'sin', 'cos', 'tan', + 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan', 'asec', 'acsc', + 'acot', 'atan2', 'exp_polar', 'exp', 'ln', 'log', 'LambertW', 'sinh', + 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh', + 'acoth', 'asech', 'acsch', 'floor', 'ceiling', 'frac', 'Piecewise', + 'piecewise_fold', 'piecewise_exclusive', 'erf', 'erfc', 'erfi', 'erf2', + 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', + 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', + 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', + 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', + 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', + 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', + 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', + 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', + 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', + 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt', 'chebyshevu', + 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', + 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', + 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', + 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', 'riemann_xi','betainc', + 'betainc_regularized', + + # sympy.ntheory + 'nextprime', 'prevprime', 'prime', 'primepi', 'primerange', 'randprime', + 'Sieve', 'sieve', 'primorial', 'cycle_length', 'composite', 'compositepi', + 'isprime', 'divisors', 'proper_divisors', 'factorint', 'multiplicity', + 'perfect_power', 'pollard_pm1', 'pollard_rho', 'primefactors', 'totient', + 'trailing', 'divisor_count', 'proper_divisor_count', 'divisor_sigma', + 'factorrat', 'reduced_totient', 'primenu', 'primeomega', + 'mersenne_prime_exponent', 'is_perfect', 'is_mersenne_prime', + 'is_abundant', 'is_deficient', 'is_amicable', 'abundance', 'npartitions', + 'is_primitive_root', 'is_quad_residue', 'legendre_symbol', + 'jacobi_symbol', 'n_order', 'sqrt_mod', 'quadratic_residues', + 'primitive_root', 'nthroot_mod', 'is_nthpow_residue', 'sqrt_mod_iter', + 'mobius', 'discrete_log', 'quadratic_congruence', 'binomial_coefficients', + 'binomial_coefficients_list', 'multinomial_coefficients', + 'continued_fraction_periodic', 'continued_fraction_iterator', + 'continued_fraction_reduce', 'continued_fraction_convergents', + 'continued_fraction', 'egyptian_fraction', + + # sympy.concrete + 'product', 'Product', 'summation', 'Sum', + + # sympy.discrete + 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform', + 'inverse_mobius_transform', 'convolution', 'covering_product', + 'intersecting_product', + + # sympy.simplify + 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars', + 'posify', 'besselsimp', 'kroneckersimp', 'signsimp', + 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', 'epath', 'EPath', + 'hyperexpand', 'collect', 'rcollect', 'radsimp', 'collect_const', + 'fraction', 'numer', 'denom', 'trigsimp', 'exptrigsimp', 'powsimp', + 'powdenest', 'combsimp', 'gammasimp', 'ratsimp', 'ratsimpmodprime', + + # sympy.sets + 'Set', 'Interval', 'Union', 'EmptySet', 'FiniteSet', 'ProductSet', + 'Intersection', 'imageset', 'DisjointUnion', 'Complement', 'SymmetricDifference', + 'ImageSet', 'Range', 'ComplexRegion', 'Reals', 'Contains', 'ConditionSet', + 'Ordinal', 'OmegaPower', 'ord0', 'PowerSet', 'Naturals', + 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes', + + # sympy.solvers + 'solve', 'solve_linear_system', 'solve_linear_system_LU', + 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol', + 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions', + 'diophantine', 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper', + 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order', + 'solve_poly_system', 'solve_triangulated', 'pde_separate', + 'pde_separate_add', 'pde_separate_mul', 'pdsolve', 'classify_pde', + 'checkpdesol', 'ode_order', 'reduce_inequalities', + 'reduce_abs_inequality', 'reduce_abs_inequalities', + 'solve_poly_inequality', 'solve_rational_inequalities', + 'solve_univariate_inequality', 'decompogen', 'solveset', 'linsolve', + 'linear_eq_to_matrix', 'nonlinsolve', 'substitution', + + # sympy.matrices + 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', + 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', + 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', + 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', + 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', + 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', + 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', + 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', + 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', + 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', + 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', + 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', + 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', + 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', + 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2', + 'rot_ccw_axis3', 'rot_givens', + + # sympy.geometry + 'Point', 'Point2D', 'Point3D', 'Line', 'Ray', 'Segment', 'Line2D', + 'Segment2D', 'Ray2D', 'Line3D', 'Segment3D', 'Ray3D', 'Plane', 'Ellipse', + 'Circle', 'Polygon', 'RegularPolygon', 'Triangle', 'rad', 'deg', + 'are_similar', 'centroid', 'convex_hull', 'idiff', 'intersection', + 'closest_points', 'farthest_points', 'GeometryError', 'Curve', 'Parabola', + + # sympy.utilities + 'flatten', 'group', 'take', 'subsets', 'variations', 'numbered_symbols', + 'cartes', 'capture', 'dict_merge', 'prefixes', 'postfixes', 'sift', + 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', + 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded', + 'public', 'memoize_property', 'timed', + + # sympy.integrals + 'integrate', 'Integral', 'line_integrate', 'mellin_transform', + 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', + 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', + 'InverseLaplaceTransform', 'fourier_transform', + 'inverse_fourier_transform', 'FourierTransform', + 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', + 'SineTransform', 'InverseSineTransform', 'cosine_transform', + 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', + 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', + 'InverseHankelTransform', 'singularityintegrate', + + # sympy.tensor + 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', + 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', + 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', + 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', + 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', + + # sympy.parsing + 'parse_expr', + + # sympy.calculus + 'euler_equations', 'singularities', 'is_increasing', + 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', + 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', + 'differentiate_finite', 'periodicity', 'not_empty_in', + 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', + + # sympy.algebras + 'Quaternion', + + # sympy.printing + 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', + 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', + 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', + 'print_ccode', 'smtlib_code', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', + 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', + 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', + 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', + 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', + + # sympy.plotting + 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', + + # sympy.interactive + 'init_session', 'init_printing', 'interactive_traversal', + + # sympy.testing + 'test', 'doctest', +] + + +#===========================================================================# +# # +# XXX: The names below were importable before SymPy 1.6 using # +# # +# from sympy import * # +# # +# This happened implicitly because there was no __all__ defined in this # +# __init__.py file. Not every package is imported. The list matches what # +# would have been imported before. It is possible that these packages will # +# not be imported by a star-import from sympy in future. # +# # +#===========================================================================# + + +__all__.extend(( + 'algebras', + 'assumptions', + 'calculus', + 'concrete', + 'discrete', + 'external', + 'functions', + 'geometry', + 'interactive', + 'multipledispatch', + 'ntheory', + 'parsing', + 'plotting', + 'polys', + 'printing', + 'release', + 'strategies', + 'tensor', + 'utilities', +)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/abc.py b/llmeval-env/lib/python3.10/site-packages/sympy/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..177e8902e78dd6c23f2a5a4970098a27503f683a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/abc.py @@ -0,0 +1,111 @@ +""" +This module exports all latin and greek letters as Symbols, so you can +conveniently do + + >>> from sympy.abc import x, y + +instead of the slightly more clunky-looking + + >>> from sympy import symbols + >>> x, y = symbols('x y') + +Caveats +======= + +1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``, +``E``, and ``Q`` are colliding with names defined in SymPy. If you import them +from both ``sympy.abc`` and ``sympy``, the second import will "win". +This is an issue only for * imports, which should only be used for short-lived +code such as interactive sessions and throwaway scripts that do not survive +until the next SymPy upgrade, where ``sympy`` may contain a different set of +names. + +2. This module does not define symbol names on demand, i.e. +``from sympy.abc import foo`` will be reported as an error because +``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``, +you still need to use ``Symbol('foo')`` or ``symbols('foo')``. +You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though +sticking with one and only one way to get the symbols does tend to make the code +more readable. + +The module also defines some special names to help detect which names clash +with the default SymPy namespace. + +``_clash1`` defines all the single letter variables that clash with +SymPy objects; ``_clash2`` defines the multi-letter clashing symbols; +and ``_clash`` is the union of both. These can be passed for ``locals`` +during sympification if one desires Symbols rather than the non-Symbol +objects for those names. + +Examples +======== + +>>> from sympy import S +>>> from sympy.abc import _clash1, _clash2, _clash +>>> S("Q & C", locals=_clash1) +C & Q +>>> S('pi(x)', locals=_clash2) +pi(x) +>>> S('pi(C, Q)', locals=_clash) +pi(C, Q) + +""" + +from typing import Any, Dict as tDict + +import string + +from .core import Symbol, symbols +from .core.alphabets import greeks +from sympy.parsing.sympy_parser import null + +##### Symbol definitions ##### + +# Implementation note: The easiest way to avoid typos in the symbols() +# parameter is to copy it from the left-hand side of the assignment. + +a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j') +k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t') +u, v, w, x, y, z = symbols('u, v, w, x, y, z') + +A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J') +K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T') +U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z') + +alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta') +epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta') +iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu') +nu, xi, omicron, pi = symbols('nu, xi, omicron, pi') +rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon') +phi, chi, psi, omega = symbols('phi, chi, psi, omega') + + +##### Clashing-symbols diagnostics ##### + +# We want to know which names in SymPy collide with those in here. +# This is mostly for diagnosing SymPy's namespace during SymPy development. + +_latin = list(string.ascii_letters) +# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too +_greek = list(greeks) # make a copy, so we can mutate it +# Note: We import lamda since lambda is a reserved keyword in Python +_greek.remove("lambda") +_greek.append("lamda") + +ns: tDict[str, Any] = {} +exec('from sympy import *', ns) +_clash1: tDict[str, Any] = {} +_clash2: tDict[str, Any] = {} +while ns: + _k, _ = ns.popitem() + if _k in _greek: + _clash2[_k] = null + _greek.remove(_k) + elif _k in _latin: + _clash1[_k] = null + _latin.remove(_k) +_clash = {} +_clash.update(_clash1) +_clash.update(_clash2) + +del _latin, _greek, Symbol, _k, null diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/conftest.py b/llmeval-env/lib/python3.10/site-packages/sympy/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..7deb7c548c41f6fe64a361b34d6a9e9c0c1e0724 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/conftest.py @@ -0,0 +1,74 @@ +import sys +sys._running_pytest = True # type: ignore +from sympy.external.importtools import version_tuple + +import pytest +from sympy.core.cache import clear_cache, USE_CACHE +from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY +from sympy.utilities.misc import ARCH +import re + +sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') + +def process_split(config, items): + split = config.getoption("--split") + if not split: + return + m = sp.match(split) + if not m: + raise ValueError("split must be a string of the form a/b " + "where a and b are ints.") + i, t = map(int, m.groups()) + start, end = (i-1)*len(items)//t, i*len(items)//t + + if i < t: + # remove elements from end of list first + del items[end:] + del items[:start] + + +def pytest_report_header(config): + s = "architecture: %s\n" % ARCH + s += "cache: %s\n" % USE_CACHE + version = '' + if GROUND_TYPES =='gmpy': + if HAS_GMPY == 1: + import gmpy + elif HAS_GMPY == 2: + import gmpy2 as gmpy + version = gmpy.version() + s += "ground types: %s %s\n" % (GROUND_TYPES, version) + return s + + +def pytest_terminal_summary(terminalreporter): + if (terminalreporter.stats.get('error', None) or + terminalreporter.stats.get('failed', None)): + terminalreporter.write_sep( + ' ', 'DO *NOT* COMMIT!', red=True, bold=True) + + +def pytest_addoption(parser): + parser.addoption("--split", action="store", default="", + help="split tests") + + +def pytest_collection_modifyitems(config, items): + """ pytest hook. """ + # handle splits + process_split(config, items) + + +@pytest.fixture(autouse=True, scope='module') +def file_clear_cache(): + clear_cache() + +@pytest.fixture(autouse=True, scope='module') +def check_disabled(request): + if getattr(request.module, 'disabled', False): + pytest.skip("test requirements not met.") + elif getattr(request.module, 'ipython', False): + # need to check version and options for ipython tests + if (version_tuple(pytest.__version__) < version_tuple('2.6.3') and + pytest.config.getvalue('-s') != 'no'): + pytest.skip("run py.test with -s or upgrade to newer version.") diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/galgebra.py b/llmeval-env/lib/python3.10/site-packages/sympy/galgebra.py new file mode 100644 index 0000000000000000000000000000000000000000..be812bfcbcece834c86d7b55eb846286acd0ac08 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/galgebra.py @@ -0,0 +1 @@ +raise ImportError("""As of SymPy 1.0 the galgebra module is maintained separately at https://github.com/pygae/galgebra""") diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/hydrogen.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/hydrogen.py new file mode 100644 index 0000000000000000000000000000000000000000..a3bac274c66a2cf97d4238d9e3951e39df820931 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/hydrogen.py @@ -0,0 +1,265 @@ +from sympy.core.numbers import Float +from sympy.core.singleton import S +from sympy.functions.combinatorial.factorials import factorial +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.special.polynomials import assoc_laguerre +from sympy.functions.special.spherical_harmonics import Ynm + + +def R_nl(n, l, r, Z=1): + """ + Returns the Hydrogen radial wavefunction R_{nl}. + + Parameters + ========== + + n : integer + Principal Quantum Number which is + an integer with possible values as 1, 2, 3, 4,... + l : integer + ``l`` is the Angular Momentum Quantum Number with + values ranging from 0 to ``n-1``. + r : + Radial coordinate. + Z : + Atomic number (1 for Hydrogen, 2 for Helium, ...) + + Everything is in Hartree atomic units. + + Examples + ======== + + >>> from sympy.physics.hydrogen import R_nl + >>> from sympy.abc import r, Z + >>> R_nl(1, 0, r, Z) + 2*sqrt(Z**3)*exp(-Z*r) + >>> R_nl(2, 0, r, Z) + sqrt(2)*(-Z*r + 2)*sqrt(Z**3)*exp(-Z*r/2)/4 + >>> R_nl(2, 1, r, Z) + sqrt(6)*Z*r*sqrt(Z**3)*exp(-Z*r/2)/12 + + For Hydrogen atom, you can just use the default value of Z=1: + + >>> R_nl(1, 0, r) + 2*exp(-r) + >>> R_nl(2, 0, r) + sqrt(2)*(2 - r)*exp(-r/2)/4 + >>> R_nl(3, 0, r) + 2*sqrt(3)*(2*r**2/9 - 2*r + 3)*exp(-r/3)/27 + + For Silver atom, you would use Z=47: + + >>> R_nl(1, 0, r, Z=47) + 94*sqrt(47)*exp(-47*r) + >>> R_nl(2, 0, r, Z=47) + 47*sqrt(94)*(2 - 47*r)*exp(-47*r/2)/4 + >>> R_nl(3, 0, r, Z=47) + 94*sqrt(141)*(4418*r**2/9 - 94*r + 3)*exp(-47*r/3)/27 + + The normalization of the radial wavefunction is: + + >>> from sympy import integrate, oo + >>> integrate(R_nl(1, 0, r)**2 * r**2, (r, 0, oo)) + 1 + >>> integrate(R_nl(2, 0, r)**2 * r**2, (r, 0, oo)) + 1 + >>> integrate(R_nl(2, 1, r)**2 * r**2, (r, 0, oo)) + 1 + + It holds for any atomic number: + + >>> integrate(R_nl(1, 0, r, Z=2)**2 * r**2, (r, 0, oo)) + 1 + >>> integrate(R_nl(2, 0, r, Z=3)**2 * r**2, (r, 0, oo)) + 1 + >>> integrate(R_nl(2, 1, r, Z=4)**2 * r**2, (r, 0, oo)) + 1 + + """ + # sympify arguments + n, l, r, Z = map(S, [n, l, r, Z]) + # radial quantum number + n_r = n - l - 1 + # rescaled "r" + a = 1/Z # Bohr radius + r0 = 2 * r / (n * a) + # normalization coefficient + C = sqrt((S(2)/(n*a))**3 * factorial(n_r) / (2*n*factorial(n + l))) + # This is an equivalent normalization coefficient, that can be found in + # some books. Both coefficients seem to be the same fast: + # C = S(2)/n**2 * sqrt(1/a**3 * factorial(n_r) / (factorial(n+l))) + return C * r0**l * assoc_laguerre(n_r, 2*l + 1, r0).expand() * exp(-r0/2) + + +def Psi_nlm(n, l, m, r, phi, theta, Z=1): + """ + Returns the Hydrogen wave function psi_{nlm}. It's the product of + the radial wavefunction R_{nl} and the spherical harmonic Y_{l}^{m}. + + Parameters + ========== + + n : integer + Principal Quantum Number which is + an integer with possible values as 1, 2, 3, 4,... + l : integer + ``l`` is the Angular Momentum Quantum Number with + values ranging from 0 to ``n-1``. + m : integer + ``m`` is the Magnetic Quantum Number with values + ranging from ``-l`` to ``l``. + r : + radial coordinate + phi : + azimuthal angle + theta : + polar angle + Z : + atomic number (1 for Hydrogen, 2 for Helium, ...) + + Everything is in Hartree atomic units. + + Examples + ======== + + >>> from sympy.physics.hydrogen import Psi_nlm + >>> from sympy import Symbol + >>> r=Symbol("r", positive=True) + >>> phi=Symbol("phi", real=True) + >>> theta=Symbol("theta", real=True) + >>> Z=Symbol("Z", positive=True, integer=True, nonzero=True) + >>> Psi_nlm(1,0,0,r,phi,theta,Z) + Z**(3/2)*exp(-Z*r)/sqrt(pi) + >>> Psi_nlm(2,1,1,r,phi,theta,Z) + -Z**(5/2)*r*exp(I*phi)*exp(-Z*r/2)*sin(theta)/(8*sqrt(pi)) + + Integrating the absolute square of a hydrogen wavefunction psi_{nlm} + over the whole space leads 1. + + The normalization of the hydrogen wavefunctions Psi_nlm is: + + >>> from sympy import integrate, conjugate, pi, oo, sin + >>> wf=Psi_nlm(2,1,1,r,phi,theta,Z) + >>> abs_sqrd=wf*conjugate(wf) + >>> jacobi=r**2*sin(theta) + >>> integrate(abs_sqrd*jacobi, (r,0,oo), (phi,0,2*pi), (theta,0,pi)) + 1 + """ + + # sympify arguments + n, l, m, r, phi, theta, Z = map(S, [n, l, m, r, phi, theta, Z]) + # check if values for n,l,m make physically sense + if n.is_integer and n < 1: + raise ValueError("'n' must be positive integer") + if l.is_integer and not (n > l): + raise ValueError("'n' must be greater than 'l'") + if m.is_integer and not (abs(m) <= l): + raise ValueError("|'m'| must be less or equal 'l'") + # return the hydrogen wave function + return R_nl(n, l, r, Z)*Ynm(l, m, theta, phi).expand(func=True) + + +def E_nl(n, Z=1): + """ + Returns the energy of the state (n, l) in Hartree atomic units. + + The energy does not depend on "l". + + Parameters + ========== + + n : integer + Principal Quantum Number which is + an integer with possible values as 1, 2, 3, 4,... + Z : + Atomic number (1 for Hydrogen, 2 for Helium, ...) + + Examples + ======== + + >>> from sympy.physics.hydrogen import E_nl + >>> from sympy.abc import n, Z + >>> E_nl(n, Z) + -Z**2/(2*n**2) + >>> E_nl(1) + -1/2 + >>> E_nl(2) + -1/8 + >>> E_nl(3) + -1/18 + >>> E_nl(3, 47) + -2209/18 + + """ + n, Z = S(n), S(Z) + if n.is_integer and (n < 1): + raise ValueError("'n' must be positive integer") + return -Z**2/(2*n**2) + + +def E_nl_dirac(n, l, spin_up=True, Z=1, c=Float("137.035999037")): + """ + Returns the relativistic energy of the state (n, l, spin) in Hartree atomic + units. + + The energy is calculated from the Dirac equation. The rest mass energy is + *not* included. + + Parameters + ========== + + n : integer + Principal Quantum Number which is + an integer with possible values as 1, 2, 3, 4,... + l : integer + ``l`` is the Angular Momentum Quantum Number with + values ranging from 0 to ``n-1``. + spin_up : + True if the electron spin is up (default), otherwise down + Z : + Atomic number (1 for Hydrogen, 2 for Helium, ...) + c : + Speed of light in atomic units. Default value is 137.035999037, + taken from https://arxiv.org/abs/1012.3627 + + Examples + ======== + + >>> from sympy.physics.hydrogen import E_nl_dirac + >>> E_nl_dirac(1, 0) + -0.500006656595360 + + >>> E_nl_dirac(2, 0) + -0.125002080189006 + >>> E_nl_dirac(2, 1) + -0.125000416028342 + >>> E_nl_dirac(2, 1, False) + -0.125002080189006 + + >>> E_nl_dirac(3, 0) + -0.0555562951740285 + >>> E_nl_dirac(3, 1) + -0.0555558020932949 + >>> E_nl_dirac(3, 1, False) + -0.0555562951740285 + >>> E_nl_dirac(3, 2) + -0.0555556377366884 + >>> E_nl_dirac(3, 2, False) + -0.0555558020932949 + + """ + n, l, Z, c = map(S, [n, l, Z, c]) + if not (l >= 0): + raise ValueError("'l' must be positive or zero") + if not (n > l): + raise ValueError("'n' must be greater than 'l'") + if (l == 0 and spin_up is False): + raise ValueError("Spin must be up for l==0.") + # skappa is sign*kappa, where sign contains the correct sign + if spin_up: + skappa = -l - 1 + else: + skappa = -l + beta = sqrt(skappa**2 - Z**2/c**2) + return c**2/sqrt(1 + Z**2/(n + skappa + beta)**2/c**2) - c**2 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..613983f2383ba6aeddb4f0d4aeedfdace5100c74 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/__init__.py @@ -0,0 +1,66 @@ +__all__ = [ + 'vector', + + 'CoordinateSym', 'ReferenceFrame', 'Dyadic', 'Vector', 'Point', 'cross', + 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations', + 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint', + 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting', 'curl', + 'divergence', 'gradient', 'is_conservative', 'is_solenoidal', + 'scalar_potential', 'scalar_potential_difference', + + 'KanesMethod', + + 'RigidBody', + + 'inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', + 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', + 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols', + + 'Particle', + + 'LagrangesMethod', + + 'Linearizer', + + 'Body', + + 'SymbolicSystem', + + 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', 'PlanarJoint', + 'SphericalJoint', 'WeldJoint', + + 'JointsMethod' +] + +from sympy.physics import vector + +from sympy.physics.vector import (CoordinateSym, ReferenceFrame, Dyadic, Vector, Point, + cross, dot, express, time_derivative, outer, kinematic_equations, + get_motion_params, partial_velocity, dynamicsymbols, vprint, + vsstrrepr, vsprint, vpprint, vlatex, init_vprinting, curl, divergence, + gradient, is_conservative, is_solenoidal, scalar_potential, + scalar_potential_difference) + +from .kane import KanesMethod + +from .rigidbody import RigidBody + +from .functions import (inertia, inertia_of_point_mass, linear_momentum, + angular_momentum, kinetic_energy, potential_energy, Lagrangian, + mechanics_printing, mprint, msprint, mpprint, mlatex, msubs, + find_dynamicsymbols) + +from .particle import Particle + +from .lagrange import LagrangesMethod + +from .linearize import Linearizer + +from .body import Body + +from .system import SymbolicSystem + +from .jointsmethod import JointsMethod + +from .joint import (PinJoint, PrismaticJoint, CylindricalJoint, PlanarJoint, + SphericalJoint, WeldJoint) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/body.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/body.py new file mode 100644 index 0000000000000000000000000000000000000000..2e032e74c963d7cd61721f7ac19acce986554eca --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/body.py @@ -0,0 +1,611 @@ +from sympy.core.backend import Symbol +from sympy.physics.vector import Point, Vector, ReferenceFrame, Dyadic +from sympy.physics.mechanics import RigidBody, Particle, inertia + +__all__ = ['Body'] + + +# XXX: We use type:ignore because the classes RigidBody and Particle have +# inconsistent parallel axis methods that take different numbers of arguments. +class Body(RigidBody, Particle): # type: ignore + """ + Body is a common representation of either a RigidBody or a Particle SymPy + object depending on what is passed in during initialization. If a mass is + passed in and central_inertia is left as None, the Particle object is + created. Otherwise a RigidBody object will be created. + + Explanation + =========== + + The attributes that Body possesses will be the same as a Particle instance + or a Rigid Body instance depending on which was created. Additional + attributes are listed below. + + Attributes + ========== + + name : string + The body's name + masscenter : Point + The point which represents the center of mass of the rigid body + frame : ReferenceFrame + The reference frame which the body is fixed in + mass : Sympifyable + The body's mass + inertia : (Dyadic, Point) + The body's inertia around its center of mass. This attribute is specific + to the rigid body form of Body and is left undefined for the Particle + form + loads : iterable + This list contains information on the different loads acting on the + Body. Forces are listed as a (point, vector) tuple and torques are + listed as (reference frame, vector) tuples. + + Parameters + ========== + + name : String + Defines the name of the body. It is used as the base for defining + body specific properties. + masscenter : Point, optional + A point that represents the center of mass of the body or particle. + If no point is given, a point is generated. + mass : Sympifyable, optional + A Sympifyable object which represents the mass of the body. If no + mass is passed, one is generated. + frame : ReferenceFrame, optional + The ReferenceFrame that represents the reference frame of the body. + If no frame is given, a frame is generated. + central_inertia : Dyadic, optional + Central inertia dyadic of the body. If none is passed while creating + RigidBody, a default inertia is generated. + + Examples + ======== + + Default behaviour. This results in the creation of a RigidBody object for + which the mass, mass center, frame and inertia attributes are given default + values. :: + + >>> from sympy.physics.mechanics import Body + >>> body = Body('name_of_body') + + This next example demonstrates the code required to specify all of the + values of the Body object. Note this will also create a RigidBody version of + the Body object. :: + + >>> from sympy import Symbol + >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia + >>> from sympy.physics.mechanics import Body + >>> mass = Symbol('mass') + >>> masscenter = Point('masscenter') + >>> frame = ReferenceFrame('frame') + >>> ixx = Symbol('ixx') + >>> body_inertia = inertia(frame, ixx, 0, 0) + >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) + + The minimal code required to create a Particle version of the Body object + involves simply passing in a name and a mass. :: + + >>> from sympy import Symbol + >>> from sympy.physics.mechanics import Body + >>> mass = Symbol('mass') + >>> body = Body('name_of_body', mass=mass) + + The Particle version of the Body object can also receive a masscenter point + and a reference frame, just not an inertia. + """ + + def __init__(self, name, masscenter=None, mass=None, frame=None, + central_inertia=None): + + self.name = name + self._loads = [] + + if frame is None: + frame = ReferenceFrame(name + '_frame') + + if masscenter is None: + masscenter = Point(name + '_masscenter') + + if central_inertia is None and mass is None: + ixx = Symbol(name + '_ixx') + iyy = Symbol(name + '_iyy') + izz = Symbol(name + '_izz') + izx = Symbol(name + '_izx') + ixy = Symbol(name + '_ixy') + iyz = Symbol(name + '_iyz') + _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), + masscenter) + else: + _inertia = (central_inertia, masscenter) + + if mass is None: + _mass = Symbol(name + '_mass') + else: + _mass = mass + + masscenter.set_vel(frame, 0) + + # If user passes masscenter and mass then a particle is created + # otherwise a rigidbody. As a result a body may or may not have inertia. + if central_inertia is None and mass is not None: + self.frame = frame + self.masscenter = masscenter + Particle.__init__(self, name, masscenter, _mass) + self._central_inertia = Dyadic(0) + else: + RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) + + @property + def loads(self): + return self._loads + + @property + def x(self): + """The basis Vector for the Body, in the x direction.""" + return self.frame.x + + @property + def y(self): + """The basis Vector for the Body, in the y direction.""" + return self.frame.y + + @property + def z(self): + """The basis Vector for the Body, in the z direction.""" + return self.frame.z + + @property + def inertia(self): + """The body's inertia about a point; stored as (Dyadic, Point).""" + if self.is_rigidbody: + return RigidBody.inertia.fget(self) + return (self.central_inertia, self.masscenter) + + @inertia.setter + def inertia(self, I): + RigidBody.inertia.fset(self, I) + + @property + def is_rigidbody(self): + if hasattr(self, '_inertia'): + return True + return False + + def kinetic_energy(self, frame): + """Kinetic energy of the body. + + Parameters + ========== + + frame : ReferenceFrame or Body + The Body's angular velocity and the velocity of it's mass + center are typically defined with respect to an inertial frame but + any relevant frame in which the velocities are known can be supplied. + + Examples + ======== + + >>> from sympy.physics.mechanics import Body, ReferenceFrame, Point + >>> from sympy import symbols + >>> m, v, r, omega = symbols('m v r omega') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> P = Body('P', masscenter=O, mass=m) + >>> P.masscenter.set_vel(N, v * N.y) + >>> P.kinetic_energy(N) + m*v**2/2 + + >>> N = ReferenceFrame('N') + >>> b = ReferenceFrame('b') + >>> b.set_ang_vel(N, omega * b.x) + >>> P = Point('P') + >>> P.set_vel(N, v * N.x) + >>> B = Body('B', masscenter=P, frame=b) + >>> B.kinetic_energy(N) + B_ixx*omega**2/2 + B_mass*v**2/2 + + See Also + ======== + + sympy.physics.mechanics : Particle, RigidBody + + """ + if isinstance(frame, Body): + frame = Body.frame + if self.is_rigidbody: + return RigidBody(self.name, self.masscenter, self.frame, self.mass, + (self.central_inertia, self.masscenter)).kinetic_energy(frame) + return Particle(self.name, self.masscenter, self.mass).kinetic_energy(frame) + + def apply_force(self, force, point=None, reaction_body=None, reaction_point=None): + """Add force to the body(s). + + Explanation + =========== + + Applies the force on self or equal and oppposite forces on + self and other body if both are given on the desried point on the bodies. + The force applied on other body is taken opposite of self, i.e, -force. + + Parameters + ========== + + force: Vector + The force to be applied. + point: Point, optional + The point on self on which force is applied. + By default self's masscenter. + reaction_body: Body, optional + Second body on which equal and opposite force + is to be applied. + reaction_point : Point, optional + The point on other body on which equal and opposite + force is applied. By default masscenter of other body. + + Example + ======= + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, Point, dynamicsymbols + >>> m, g = symbols('m g') + >>> B = Body('B') + >>> force1 = m*g*B.z + >>> B.apply_force(force1) #Applying force on B's masscenter + >>> B.loads + [(B_masscenter, g*m*B_frame.z)] + + We can also remove some part of force from any point on the body by + adding the opposite force to the body on that point. + + >>> f1, f2 = dynamicsymbols('f1 f2') + >>> P = Point('P') #Considering point P on body B + >>> B.apply_force(f1*B.x + f2*B.y, P) + >>> B.loads + [(B_masscenter, g*m*B_frame.z), (P, f1(t)*B_frame.x + f2(t)*B_frame.y)] + + Let's remove f1 from point P on body B. + + >>> B.apply_force(-f1*B.x, P) + >>> B.loads + [(B_masscenter, g*m*B_frame.z), (P, f2(t)*B_frame.y)] + + To further demonstrate the use of ``apply_force`` attribute, + consider two bodies connected through a spring. + + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> N = Body('N') #Newtonion Frame + >>> x = dynamicsymbols('x') + >>> B1 = Body('B1') + >>> B2 = Body('B2') + >>> spring_force = x*N.x + + Now let's apply equal and opposite spring force to the bodies. + + >>> P1 = Point('P1') + >>> P2 = Point('P2') + >>> B1.apply_force(spring_force, point=P1, reaction_body=B2, reaction_point=P2) + + We can check the loads(forces) applied to bodies now. + + >>> B1.loads + [(P1, x(t)*N_frame.x)] + >>> B2.loads + [(P2, - x(t)*N_frame.x)] + + Notes + ===== + + If a new force is applied to a body on a point which already has some + force applied on it, then the new force is added to the already applied + force on that point. + + """ + + if not isinstance(point, Point): + if point is None: + point = self.masscenter # masscenter + else: + raise TypeError("Force must be applied to a point on the body.") + if not isinstance(force, Vector): + raise TypeError("Force must be a vector.") + + if reaction_body is not None: + reaction_body.apply_force(-force, point=reaction_point) + + for load in self._loads: + if point in load: + force += load[1] + self._loads.remove(load) + break + + self._loads.append((point, force)) + + def apply_torque(self, torque, reaction_body=None): + """Add torque to the body(s). + + Explanation + =========== + + Applies the torque on self or equal and oppposite torquess on + self and other body if both are given. + The torque applied on other body is taken opposite of self, + i.e, -torque. + + Parameters + ========== + + torque: Vector + The torque to be applied. + reaction_body: Body, optional + Second body on which equal and opposite torque + is to be applied. + + Example + ======= + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> t = symbols('t') + >>> B = Body('B') + >>> torque1 = t*B.z + >>> B.apply_torque(torque1) + >>> B.loads + [(B_frame, t*B_frame.z)] + + We can also remove some part of torque from the body by + adding the opposite torque to the body. + + >>> t1, t2 = dynamicsymbols('t1 t2') + >>> B.apply_torque(t1*B.x + t2*B.y) + >>> B.loads + [(B_frame, t1(t)*B_frame.x + t2(t)*B_frame.y + t*B_frame.z)] + + Let's remove t1 from Body B. + + >>> B.apply_torque(-t1*B.x) + >>> B.loads + [(B_frame, t2(t)*B_frame.y + t*B_frame.z)] + + To further demonstrate the use, let us consider two bodies such that + a torque `T` is acting on one body, and `-T` on the other. + + >>> from sympy.physics.mechanics import Body, dynamicsymbols + >>> N = Body('N') #Newtonion frame + >>> B1 = Body('B1') + >>> B2 = Body('B2') + >>> v = dynamicsymbols('v') + >>> T = v*N.y #Torque + + Now let's apply equal and opposite torque to the bodies. + + >>> B1.apply_torque(T, B2) + + We can check the loads (torques) applied to bodies now. + + >>> B1.loads + [(B1_frame, v(t)*N_frame.y)] + >>> B2.loads + [(B2_frame, - v(t)*N_frame.y)] + + Notes + ===== + + If a new torque is applied on body which already has some torque applied on it, + then the new torque is added to the previous torque about the body's frame. + + """ + + if not isinstance(torque, Vector): + raise TypeError("A Vector must be supplied to add torque.") + + if reaction_body is not None: + reaction_body.apply_torque(-torque) + + for load in self._loads: + if self.frame in load: + torque += load[1] + self._loads.remove(load) + break + self._loads.append((self.frame, torque)) + + def clear_loads(self): + """ + Clears the Body's loads list. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> B = Body('B') + >>> force = B.x + B.y + >>> B.apply_force(force) + >>> B.loads + [(B_masscenter, B_frame.x + B_frame.y)] + >>> B.clear_loads() + >>> B.loads + [] + + """ + + self._loads = [] + + def remove_load(self, about=None): + """ + Remove load about a point or frame. + + Parameters + ========== + + about : Point or ReferenceFrame, optional + The point about which force is applied, + and is to be removed. + If about is None, then the torque about + self's frame is removed. + + Example + ======= + + >>> from sympy.physics.mechanics import Body, Point + >>> B = Body('B') + >>> P = Point('P') + >>> f1 = B.x + >>> f2 = B.y + >>> B.apply_force(f1) + >>> B.apply_force(f2, P) + >>> B.loads + [(B_masscenter, B_frame.x), (P, B_frame.y)] + + >>> B.remove_load(P) + >>> B.loads + [(B_masscenter, B_frame.x)] + + """ + + if about is not None: + if not isinstance(about, Point): + raise TypeError('Load is applied about Point or ReferenceFrame.') + else: + about = self.frame + + for load in self._loads: + if about in load: + self._loads.remove(load) + break + + def masscenter_vel(self, body): + """ + Returns the velocity of the mass center with respect to the provided + rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the velocity in. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> B = Body('B') + >>> A.masscenter.set_vel(B.frame, 5*B.frame.x) + >>> A.masscenter_vel(B) + 5*B_frame.x + >>> A.masscenter_vel(B.frame) + 5*B_frame.x + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.masscenter.vel(frame) + + def ang_vel_in(self, body): + """ + Returns this body's angular velocity with respect to the provided + rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the angular velocity in. + + Example + ======= + + >>> from sympy.physics.mechanics import Body, ReferenceFrame + >>> A = Body('A') + >>> N = ReferenceFrame('N') + >>> B = Body('B', frame=N) + >>> A.frame.set_ang_vel(N, 5*N.x) + >>> A.ang_vel_in(B) + 5*N.x + >>> A.ang_vel_in(N) + 5*N.x + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.frame.ang_vel_in(frame) + + def dcm(self, body): + """ + Returns the direction cosine matrix of this body relative to the + provided rigid body or reference frame. + + Parameters + ========== + + body: Body or ReferenceFrame + The rigid body or reference frame to calculate the dcm. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> B = Body('B') + >>> A.frame.orient_axis(B.frame, B.frame.x, 5) + >>> A.dcm(B) + Matrix([ + [1, 0, 0], + [0, cos(5), sin(5)], + [0, -sin(5), cos(5)]]) + >>> A.dcm(B.frame) + Matrix([ + [1, 0, 0], + [0, cos(5), sin(5)], + [0, -sin(5), cos(5)]]) + + """ + + if isinstance(body, ReferenceFrame): + frame=body + elif isinstance(body, Body): + frame = body.frame + return self.frame.dcm(frame) + + def parallel_axis(self, point, frame=None): + """Returns the inertia dyadic of the body with respect to another + point. + + Parameters + ========== + + point : sympy.physics.vector.Point + The point to express the inertia dyadic about. + frame : sympy.physics.vector.ReferenceFrame + The reference frame used to construct the dyadic. + + Returns + ======= + + inertia : sympy.physics.vector.Dyadic + The inertia dyadic of the rigid body expressed about the provided + point. + + Example + ======= + + >>> from sympy.physics.mechanics import Body + >>> A = Body('A') + >>> P = A.masscenter.locatenew('point', 3 * A.x + 5 * A.y) + >>> A.parallel_axis(P).to_matrix(A.frame) + Matrix([ + [A_ixx + 25*A_mass, A_ixy - 15*A_mass, A_izx], + [A_ixy - 15*A_mass, A_iyy + 9*A_mass, A_iyz], + [ A_izx, A_iyz, A_izz + 34*A_mass]]) + + """ + if self.is_rigidbody: + return RigidBody.parallel_axis(self, point, frame) + return Particle.parallel_axis(self, point, frame) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..33aa89d5c90a1348e4aec7de3e55933d0b498082 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/functions.py @@ -0,0 +1,779 @@ +from sympy.utilities import dict_merge +from sympy.utilities.iterables import iterable +from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, + Point, dynamicsymbols) +from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, + init_vprinting) +from sympy.physics.mechanics.particle import Particle +from sympy.physics.mechanics.rigidbody import RigidBody +from sympy.simplify.simplify import simplify +from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, + tan, AppliedUndef, S) + +__all__ = ['inertia', + 'inertia_of_point_mass', + 'linear_momentum', + 'angular_momentum', + 'kinetic_energy', + 'potential_energy', + 'Lagrangian', + 'mechanics_printing', + 'mprint', + 'msprint', + 'mpprint', + 'mlatex', + 'msubs', + 'find_dynamicsymbols'] + +# These are functions that we've moved and renamed during extracting the +# basic vector calculus code from the mechanics packages. + +mprint = vprint +msprint = vsprint +mpprint = vpprint +mlatex = vlatex + + +def mechanics_printing(**kwargs): + """ + Initializes time derivative printing for all SymPy objects in + mechanics module. + """ + + init_vprinting(**kwargs) + +mechanics_printing.__doc__ = init_vprinting.__doc__ + + +def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): + """Simple way to create inertia Dyadic object. + + Explanation + =========== + + If you do not know what a Dyadic is, just treat this like the inertia + tensor. Then, do the easy thing and define it in a body-fixed frame. + + Parameters + ========== + + frame : ReferenceFrame + The frame the inertia is defined in + ixx : Sympifyable + the xx element in the inertia dyadic + iyy : Sympifyable + the yy element in the inertia dyadic + izz : Sympifyable + the zz element in the inertia dyadic + ixy : Sympifyable + the xy element in the inertia dyadic + iyz : Sympifyable + the yz element in the inertia dyadic + izx : Sympifyable + the zx element in the inertia dyadic + + Examples + ======== + + >>> from sympy.physics.mechanics import ReferenceFrame, inertia + >>> N = ReferenceFrame('N') + >>> inertia(N, 1, 2, 3) + (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) + + """ + + if not isinstance(frame, ReferenceFrame): + raise TypeError('Need to define the inertia in a frame') + ixx = sympify(ixx) + ixy = sympify(ixy) + iyy = sympify(iyy) + iyz = sympify(iyz) + izx = sympify(izx) + izz = sympify(izz) + ol = ixx * (frame.x | frame.x) + ol += ixy * (frame.x | frame.y) + ol += izx * (frame.x | frame.z) + ol += ixy * (frame.y | frame.x) + ol += iyy * (frame.y | frame.y) + ol += iyz * (frame.y | frame.z) + ol += izx * (frame.z | frame.x) + ol += iyz * (frame.z | frame.y) + ol += izz * (frame.z | frame.z) + return ol + + +def inertia_of_point_mass(mass, pos_vec, frame): + """Inertia dyadic of a point mass relative to point O. + + Parameters + ========== + + mass : Sympifyable + Mass of the point mass + pos_vec : Vector + Position from point O to point mass + frame : ReferenceFrame + Reference frame to express the dyadic in + + Examples + ======== + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass + >>> N = ReferenceFrame('N') + >>> r, m = symbols('r m') + >>> px = r * N.x + >>> inertia_of_point_mass(m, px, N) + m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) + + """ + + return mass * (((frame.x | frame.x) + (frame.y | frame.y) + + (frame.z | frame.z)) * (pos_vec & pos_vec) - + (pos_vec | pos_vec)) + + +def linear_momentum(frame, *body): + """Linear momentum of the system. + + Explanation + =========== + + This function returns the linear momentum of a system of Particle's and/or + RigidBody's. The linear momentum of a system is equal to the vector sum of + the linear momentum of its constituents. Consider a system, S, comprised of + a rigid body, A, and a particle, P. The linear momentum of the system, L, + is equal to the vector sum of the linear momentum of the particle, L1, and + the linear momentum of the rigid body, L2, i.e. + + L = L1 + L2 + + Parameters + ========== + + frame : ReferenceFrame + The frame in which linear momentum is desired. + body1, body2, body3... : Particle and/or RigidBody + The body (or bodies) whose linear momentum is required. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame + >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum + >>> N = ReferenceFrame('N') + >>> P = Point('P') + >>> P.set_vel(N, 10 * N.x) + >>> Pa = Particle('Pa', P, 1) + >>> Ac = Point('Ac') + >>> Ac.set_vel(N, 25 * N.y) + >>> I = outer(N.x, N.x) + >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) + >>> linear_momentum(N, A, Pa) + 10*N.x + 500*N.y + + """ + + if not isinstance(frame, ReferenceFrame): + raise TypeError('Please specify a valid ReferenceFrame') + else: + linear_momentum_sys = Vector(0) + for e in body: + if isinstance(e, (RigidBody, Particle)): + linear_momentum_sys += e.linear_momentum(frame) + else: + raise TypeError('*body must have only Particle or RigidBody') + return linear_momentum_sys + + +def angular_momentum(point, frame, *body): + """Angular momentum of a system. + + Explanation + =========== + + This function returns the angular momentum of a system of Particle's and/or + RigidBody's. The angular momentum of such a system is equal to the vector + sum of the angular momentum of its constituents. Consider a system, S, + comprised of a rigid body, A, and a particle, P. The angular momentum of + the system, H, is equal to the vector sum of the angular momentum of the + particle, H1, and the angular momentum of the rigid body, H2, i.e. + + H = H1 + H2 + + Parameters + ========== + + point : Point + The point about which angular momentum of the system is desired. + frame : ReferenceFrame + The frame in which angular momentum is desired. + body1, body2, body3... : Particle and/or RigidBody + The body (or bodies) whose angular momentum is required. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame + >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> O.set_vel(N, 0 * N.x) + >>> P = O.locatenew('P', 1 * N.x) + >>> P.set_vel(N, 10 * N.x) + >>> Pa = Particle('Pa', P, 1) + >>> Ac = O.locatenew('Ac', 2 * N.y) + >>> Ac.set_vel(N, 5 * N.y) + >>> a = ReferenceFrame('a') + >>> a.set_ang_vel(N, 10 * N.z) + >>> I = outer(N.z, N.z) + >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) + >>> angular_momentum(O, N, Pa, A) + 10*N.z + + """ + + if not isinstance(frame, ReferenceFrame): + raise TypeError('Please enter a valid ReferenceFrame') + if not isinstance(point, Point): + raise TypeError('Please specify a valid Point') + else: + angular_momentum_sys = Vector(0) + for e in body: + if isinstance(e, (RigidBody, Particle)): + angular_momentum_sys += e.angular_momentum(point, frame) + else: + raise TypeError('*body must have only Particle or RigidBody') + return angular_momentum_sys + + +def kinetic_energy(frame, *body): + """Kinetic energy of a multibody system. + + Explanation + =========== + + This function returns the kinetic energy of a system of Particle's and/or + RigidBody's. The kinetic energy of such a system is equal to the sum of + the kinetic energies of its constituents. Consider a system, S, comprising + a rigid body, A, and a particle, P. The kinetic energy of the system, T, + is equal to the vector sum of the kinetic energy of the particle, T1, and + the kinetic energy of the rigid body, T2, i.e. + + T = T1 + T2 + + Kinetic energy is a scalar. + + Parameters + ========== + + frame : ReferenceFrame + The frame in which the velocity or angular velocity of the body is + defined. + body1, body2, body3... : Particle and/or RigidBody + The body (or bodies) whose kinetic energy is required. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame + >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> O.set_vel(N, 0 * N.x) + >>> P = O.locatenew('P', 1 * N.x) + >>> P.set_vel(N, 10 * N.x) + >>> Pa = Particle('Pa', P, 1) + >>> Ac = O.locatenew('Ac', 2 * N.y) + >>> Ac.set_vel(N, 5 * N.y) + >>> a = ReferenceFrame('a') + >>> a.set_ang_vel(N, 10 * N.z) + >>> I = outer(N.z, N.z) + >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) + >>> kinetic_energy(N, Pa, A) + 350 + + """ + + if not isinstance(frame, ReferenceFrame): + raise TypeError('Please enter a valid ReferenceFrame') + ke_sys = S.Zero + for e in body: + if isinstance(e, (RigidBody, Particle)): + ke_sys += e.kinetic_energy(frame) + else: + raise TypeError('*body must have only Particle or RigidBody') + return ke_sys + + +def potential_energy(*body): + """Potential energy of a multibody system. + + Explanation + =========== + + This function returns the potential energy of a system of Particle's and/or + RigidBody's. The potential energy of such a system is equal to the sum of + the potential energy of its constituents. Consider a system, S, comprising + a rigid body, A, and a particle, P. The potential energy of the system, V, + is equal to the vector sum of the potential energy of the particle, V1, and + the potential energy of the rigid body, V2, i.e. + + V = V1 + V2 + + Potential energy is a scalar. + + Parameters + ========== + + body1, body2, body3... : Particle and/or RigidBody + The body (or bodies) whose potential energy is required. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame + >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy + >>> from sympy import symbols + >>> M, m, g, h = symbols('M m g h') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> O.set_vel(N, 0 * N.x) + >>> P = O.locatenew('P', 1 * N.x) + >>> Pa = Particle('Pa', P, m) + >>> Ac = O.locatenew('Ac', 2 * N.y) + >>> a = ReferenceFrame('a') + >>> I = outer(N.z, N.z) + >>> A = RigidBody('A', Ac, a, M, (I, Ac)) + >>> Pa.potential_energy = m * g * h + >>> A.potential_energy = M * g * h + >>> potential_energy(Pa, A) + M*g*h + g*h*m + + """ + + pe_sys = S.Zero + for e in body: + if isinstance(e, (RigidBody, Particle)): + pe_sys += e.potential_energy + else: + raise TypeError('*body must have only Particle or RigidBody') + return pe_sys + + +def gravity(acceleration, *bodies): + """ + Returns a list of gravity forces given the acceleration + due to gravity and any number of particles or rigidbodies. + + Example + ======= + + >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody + >>> from sympy.physics.mechanics.functions import gravity + >>> from sympy import symbols + >>> N = ReferenceFrame('N') + >>> m, M, g = symbols('m M g') + >>> F1, F2 = symbols('F1 F2') + >>> po = Point('po') + >>> pa = Particle('pa', po, m) + >>> A = ReferenceFrame('A') + >>> P = Point('P') + >>> I = outer(A.x, A.x) + >>> B = RigidBody('B', P, A, M, (I, P)) + >>> forceList = [(po, F1), (P, F2)] + >>> forceList.extend(gravity(g*N.y, pa, B)) + >>> forceList + [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)] + + """ + + gravity_force = [] + if not bodies: + raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") + + for e in bodies: + point = getattr(e, 'masscenter', None) + if point is None: + point = e.point + + gravity_force.append((point, e.mass*acceleration)) + + return gravity_force + + +def center_of_mass(point, *bodies): + """ + Returns the position vector from the given point to the center of mass + of the given bodies(particles or rigidbodies). + + Example + ======= + + >>> from sympy import symbols, S + >>> from sympy.physics.vector import Point + >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer + >>> from sympy.physics.mechanics.functions import center_of_mass + >>> a = ReferenceFrame('a') + >>> m = symbols('m', real=True) + >>> p1 = Particle('p1', Point('p1_pt'), S(1)) + >>> p2 = Particle('p2', Point('p2_pt'), S(2)) + >>> p3 = Particle('p3', Point('p3_pt'), S(3)) + >>> p4 = Particle('p4', Point('p4_pt'), m) + >>> b_f = ReferenceFrame('b_f') + >>> b_cm = Point('b_cm') + >>> mb = symbols('mb') + >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) + >>> p2.point.set_pos(p1.point, a.x) + >>> p3.point.set_pos(p1.point, a.x + a.y) + >>> p4.point.set_pos(p1.point, a.y) + >>> b.masscenter.set_pos(p1.point, a.y + a.z) + >>> point_o=Point('o') + >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) + >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z + >>> point_o.pos_from(p1.point) + 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z + + """ + if not bodies: + raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") + + total_mass = 0 + vec = Vector(0) + for i in bodies: + total_mass += i.mass + + masscenter = getattr(i, 'masscenter', None) + if masscenter is None: + masscenter = i.point + vec += i.mass*masscenter.pos_from(point) + + return vec/total_mass + + +def Lagrangian(frame, *body): + """Lagrangian of a multibody system. + + Explanation + =========== + + This function returns the Lagrangian of a system of Particle's and/or + RigidBody's. The Lagrangian of such a system is equal to the difference + between the kinetic energies and potential energies of its constituents. If + T and V are the kinetic and potential energies of a system then it's + Lagrangian, L, is defined as + + L = T - V + + The Lagrangian is a scalar. + + Parameters + ========== + + frame : ReferenceFrame + The frame in which the velocity or angular velocity of the body is + defined to determine the kinetic energy. + + body1, body2, body3... : Particle and/or RigidBody + The body (or bodies) whose Lagrangian is required. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame + >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian + >>> from sympy import symbols + >>> M, m, g, h = symbols('M m g h') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> O.set_vel(N, 0 * N.x) + >>> P = O.locatenew('P', 1 * N.x) + >>> P.set_vel(N, 10 * N.x) + >>> Pa = Particle('Pa', P, 1) + >>> Ac = O.locatenew('Ac', 2 * N.y) + >>> Ac.set_vel(N, 5 * N.y) + >>> a = ReferenceFrame('a') + >>> a.set_ang_vel(N, 10 * N.z) + >>> I = outer(N.z, N.z) + >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) + >>> Pa.potential_energy = m * g * h + >>> A.potential_energy = M * g * h + >>> Lagrangian(N, Pa, A) + -M*g*h - g*h*m + 350 + + """ + + if not isinstance(frame, ReferenceFrame): + raise TypeError('Please supply a valid ReferenceFrame') + for e in body: + if not isinstance(e, (RigidBody, Particle)): + raise TypeError('*body must have only Particle or RigidBody') + return kinetic_energy(frame, *body) - potential_energy(*body) + + +def find_dynamicsymbols(expression, exclude=None, reference_frame=None): + """Find all dynamicsymbols in expression. + + Explanation + =========== + + If the optional ``exclude`` kwarg is used, only dynamicsymbols + not in the iterable ``exclude`` are returned. + If we intend to apply this function on a vector, the optional + ``reference_frame`` is also used to inform about the corresponding frame + with respect to which the dynamic symbols of the given vector is to be + determined. + + Parameters + ========== + + expression : SymPy expression + + exclude : iterable of dynamicsymbols, optional + + reference_frame : ReferenceFrame, optional + The frame with respect to which the dynamic symbols of the + given vector is to be determined. + + Examples + ======== + + >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols + >>> from sympy.physics.mechanics import ReferenceFrame + >>> x, y = dynamicsymbols('x, y') + >>> expr = x + x.diff()*y + >>> find_dynamicsymbols(expr) + {x(t), y(t), Derivative(x(t), t)} + >>> find_dynamicsymbols(expr, exclude=[x, y]) + {Derivative(x(t), t)} + >>> a, b, c = dynamicsymbols('a, b, c') + >>> A = ReferenceFrame('A') + >>> v = a * A.x + b * A.y + c * A.z + >>> find_dynamicsymbols(v, reference_frame=A) + {a(t), b(t), c(t)} + + """ + t_set = {dynamicsymbols._t} + if exclude: + if iterable(exclude): + exclude_set = set(exclude) + else: + raise TypeError("exclude kwarg must be iterable") + else: + exclude_set = set() + if isinstance(expression, Vector): + if reference_frame is None: + raise ValueError("You must provide reference_frame when passing a " + "vector expression, got %s." % reference_frame) + else: + expression = expression.to_matrix(reference_frame) + return {i for i in expression.atoms(AppliedUndef, Derivative) if + i.free_symbols == t_set} - exclude_set + + +def msubs(expr, *sub_dicts, smart=False, **kwargs): + """A custom subs for use on expressions derived in physics.mechanics. + + Traverses the expression tree once, performing the subs found in sub_dicts. + Terms inside ``Derivative`` expressions are ignored: + + Examples + ======== + + >>> from sympy.physics.mechanics import dynamicsymbols, msubs + >>> x = dynamicsymbols('x') + >>> msubs(x.diff() + x, {x: 1}) + Derivative(x(t), t) + 1 + + Note that sub_dicts can be a single dictionary, or several dictionaries: + + >>> x, y, z = dynamicsymbols('x, y, z') + >>> sub1 = {x: 1, y: 2} + >>> sub2 = {z: 3, x.diff(): 4} + >>> msubs(x.diff() + x + y + z, sub1, sub2) + 10 + + If smart=True (default False), also checks for conditions that may result + in ``nan``, but if simplified would yield a valid expression. For example: + + >>> from sympy import sin, tan + >>> (sin(x)/tan(x)).subs(x, 0) + nan + >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) + 1 + + It does this by first replacing all ``tan`` with ``sin/cos``. Then each + node is traversed. If the node is a fraction, subs is first evaluated on + the denominator. If this results in 0, simplification of the entire + fraction is attempted. Using this selective simplification, only + subexpressions that result in 1/0 are targeted, resulting in faster + performance. + + """ + + sub_dict = dict_merge(*sub_dicts) + if smart: + func = _smart_subs + elif hasattr(expr, 'msubs'): + return expr.msubs(sub_dict) + else: + func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) + if isinstance(expr, (Matrix, Vector, Dyadic)): + return expr.applyfunc(lambda x: func(x, sub_dict)) + else: + return func(expr, sub_dict) + + +def _crawl(expr, func, *args, **kwargs): + """Crawl the expression tree, and apply func to every node.""" + val = func(expr, *args, **kwargs) + if val is not None: + return val + new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) + return expr.func(*new_args) + + +def _sub_func(expr, sub_dict): + """Perform direct matching substitution, ignoring derivatives.""" + if expr in sub_dict: + return sub_dict[expr] + elif not expr.args or expr.is_Derivative: + return expr + + +def _tan_repl_func(expr): + """Replace tan with sin/cos.""" + if isinstance(expr, tan): + return sin(*expr.args) / cos(*expr.args) + elif not expr.args or expr.is_Derivative: + return expr + + +def _smart_subs(expr, sub_dict): + """Performs subs, checking for conditions that may result in `nan` or + `oo`, and attempts to simplify them out. + + The expression tree is traversed twice, and the following steps are + performed on each expression node: + - First traverse: + Replace all `tan` with `sin/cos`. + - Second traverse: + If node is a fraction, check if the denominator evaluates to 0. + If so, attempt to simplify it out. Then if node is in sub_dict, + sub in the corresponding value. + + """ + expr = _crawl(expr, _tan_repl_func) + + def _recurser(expr, sub_dict): + # Decompose the expression into num, den + num, den = _fraction_decomp(expr) + if den != 1: + # If there is a non trivial denominator, we need to handle it + denom_subbed = _recurser(den, sub_dict) + if denom_subbed.evalf() == 0: + # If denom is 0 after this, attempt to simplify the bad expr + expr = simplify(expr) + else: + # Expression won't result in nan, find numerator + num_subbed = _recurser(num, sub_dict) + return num_subbed / denom_subbed + # We have to crawl the tree manually, because `expr` may have been + # modified in the simplify step. First, perform subs as normal: + val = _sub_func(expr, sub_dict) + if val is not None: + return val + new_args = (_recurser(arg, sub_dict) for arg in expr.args) + return expr.func(*new_args) + return _recurser(expr, sub_dict) + + +def _fraction_decomp(expr): + """Return num, den such that expr = num/den.""" + if not isinstance(expr, Mul): + return expr, 1 + num = [] + den = [] + for a in expr.args: + if a.is_Pow and a.args[1] < 0: + den.append(1 / a) + else: + num.append(a) + if not den: + return expr, 1 + num = Mul(*num) + den = Mul(*den) + return num, den + + +def _f_list_parser(fl, ref_frame): + """Parses the provided forcelist composed of items + of the form (obj, force). + Returns a tuple containing: + vel_list: The velocity (ang_vel for Frames, vel for Points) in + the provided reference frame. + f_list: The forces. + + Used internally in the KanesMethod and LagrangesMethod classes. + + """ + def flist_iter(): + for pair in fl: + obj, force = pair + if isinstance(obj, ReferenceFrame): + yield obj.ang_vel_in(ref_frame), force + elif isinstance(obj, Point): + yield obj.vel(ref_frame), force + else: + raise TypeError('First entry in each forcelist pair must ' + 'be a point or frame.') + + if not fl: + vel_list, f_list = (), () + else: + unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] + vel_list, f_list = unzip(list(flist_iter())) + return vel_list, f_list + + +def _validate_coordinates(coordinates=None, speeds=None, check_duplicates=True, + is_dynamicsymbols=True): + t_set = {dynamicsymbols._t} + # Convert input to iterables + if coordinates is None: + coordinates = [] + elif not iterable(coordinates): + coordinates = [coordinates] + if speeds is None: + speeds = [] + elif not iterable(speeds): + speeds = [speeds] + + if check_duplicates: # Check for duplicates + seen = set() + coord_duplicates = {x for x in coordinates if x in seen or seen.add(x)} + seen = set() + speed_duplicates = {x for x in speeds if x in seen or seen.add(x)} + overlap = set(coordinates).intersection(speeds) + if coord_duplicates: + raise ValueError(f'The generalized coordinates {coord_duplicates} ' + f'are duplicated, all generalized coordinates ' + f'should be unique.') + if speed_duplicates: + raise ValueError(f'The generalized speeds {speed_duplicates} are ' + f'duplicated, all generalized speeds should be ' + f'unique.') + if overlap: + raise ValueError(f'{overlap} are defined as both generalized ' + f'coordinates and generalized speeds.') + if is_dynamicsymbols: # Check whether all coordinates are dynamicsymbols + for coordinate in coordinates: + if not (isinstance(coordinate, (AppliedUndef, Derivative)) and + coordinate.free_symbols == t_set): + raise ValueError(f'Generalized coordinate "{coordinate}" is not' + f' a dynamicsymbol.') + for speed in speeds: + if not (isinstance(speed, (AppliedUndef, Derivative)) and + speed.free_symbols == t_set): + raise ValueError(f'Generalized speed "{speed}" is not a ' + f'dynamicsymbol.') diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py new file mode 100644 index 0000000000000000000000000000000000000000..946a628cbfb1a086e22d71783732c24bb49e7e70 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/joint.py @@ -0,0 +1,2163 @@ +# coding=utf-8 + +from abc import ABC, abstractmethod + +from sympy.core.backend import pi, AppliedUndef, Derivative, Matrix +from sympy.physics.mechanics.body import Body +from sympy.physics.mechanics.functions import _validate_coordinates +from sympy.physics.vector import (Vector, dynamicsymbols, cross, Point, + ReferenceFrame) +from sympy.utilities.iterables import iterable +from sympy.utilities.exceptions import sympy_deprecation_warning + +__all__ = ['Joint', 'PinJoint', 'PrismaticJoint', 'CylindricalJoint', + 'PlanarJoint', 'SphericalJoint', 'WeldJoint'] + + +class Joint(ABC): + """Abstract base class for all specific joints. + + Explanation + =========== + + A joint subtracts degrees of freedom from a body. This is the base class + for all specific joints and holds all common methods acting as an interface + for all joints. Custom joint can be created by inheriting Joint class and + defining all abstract functions. + + The abstract methods are: + + - ``_generate_coordinates`` + - ``_generate_speeds`` + - ``_orient_frames`` + - ``_set_angular_velocity`` + - ``_set_linear_velocity`` + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + coordinates : iterable of dynamicsymbols, optional + Generalized coordinates of the joint. + speeds : iterable of dynamicsymbols, optional + Generalized speeds of joint. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the parent body which aligns with an axis fixed in the + child body. The default is the x axis of parent's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + child_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the child body which aligns with an axis fixed in the + parent body. The default is the x axis of child's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + parent_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by parent_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + child_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by child_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + coordinates : Matrix + Matrix of the joint's generalized coordinates. + speeds : Matrix + Matrix of the joint's generalized speeds. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_axis : Vector + The axis fixed in the parent frame that represents the joint. + child_axis : Vector + The axis fixed in the child frame that represents the joint. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + + Notes + ===== + + When providing a vector as the intermediate frame, a new intermediate frame + is created which aligns its X axis with the provided vector. This is done + with a single fixed rotation about a rotation axis. This rotation axis is + determined by taking the cross product of the ``body.x`` axis with the + provided vector. In the case where the provided vector is in the ``-body.x`` + direction, the rotation is done about the ``body.y`` axis. + + """ + + def __init__(self, name, parent, child, coordinates=None, speeds=None, + parent_point=None, child_point=None, parent_axis=None, + child_axis=None, parent_interframe=None, child_interframe=None, + parent_joint_pos=None, child_joint_pos=None): + + if not isinstance(name, str): + raise TypeError('Supply a valid name.') + self._name = name + + if not isinstance(parent, Body): + raise TypeError('Parent must be an instance of Body.') + self._parent = parent + + if not isinstance(child, Body): + raise TypeError('Parent must be an instance of Body.') + self._child = child + + self._coordinates = self._generate_coordinates(coordinates) + self._speeds = self._generate_speeds(speeds) + _validate_coordinates(self.coordinates, self.speeds) + self._kdes = self._generate_kdes() + + self._parent_axis = self._axis(parent_axis, parent.frame) + self._child_axis = self._axis(child_axis, child.frame) + + if parent_joint_pos is not None or child_joint_pos is not None: + sympy_deprecation_warning( + """ + The parent_joint_pos and child_joint_pos arguments for the Joint + classes are deprecated. Instead use parent_point and child_point. + """, + deprecated_since_version="1.12", + active_deprecations_target="deprecated-mechanics-joint-pos", + stacklevel=4 + ) + if parent_point is None: + parent_point = parent_joint_pos + if child_point is None: + child_point = child_joint_pos + self._parent_point = self._locate_joint_pos(parent, parent_point) + self._child_point = self._locate_joint_pos(child, child_point) + if parent_axis is not None or child_axis is not None: + sympy_deprecation_warning( + """ + The parent_axis and child_axis arguments for the Joint classes + are deprecated. Instead use parent_interframe, child_interframe. + """, + deprecated_since_version="1.12", + active_deprecations_target="deprecated-mechanics-joint-axis", + stacklevel=4 + ) + if parent_interframe is None: + parent_interframe = parent_axis + if child_interframe is None: + child_interframe = child_axis + self._parent_interframe = self._locate_joint_frame(parent, + parent_interframe) + self._child_interframe = self._locate_joint_frame(child, + child_interframe) + + self._orient_frames() + self._set_angular_velocity() + self._set_linear_velocity() + + def __str__(self): + return self.name + + def __repr__(self): + return self.__str__() + + @property + def name(self): + """Name of the joint.""" + return self._name + + @property + def parent(self): + """Parent body of Joint.""" + return self._parent + + @property + def child(self): + """Child body of Joint.""" + return self._child + + @property + def coordinates(self): + """Matrix of the joint's generalized coordinates.""" + return self._coordinates + + @property + def speeds(self): + """Matrix of the joint's generalized speeds.""" + return self._speeds + + @property + def kdes(self): + """Kinematical differential equations of the joint.""" + return self._kdes + + @property + def parent_axis(self): + """The axis of parent frame.""" + # Will be removed with `deprecated-mechanics-joint-axis` + return self._parent_axis + + @property + def child_axis(self): + """The axis of child frame.""" + # Will be removed with `deprecated-mechanics-joint-axis` + return self._child_axis + + @property + def parent_point(self): + """Attachment point where the joint is fixed to the parent body.""" + return self._parent_point + + @property + def child_point(self): + """Attachment point where the joint is fixed to the child body.""" + return self._child_point + + @property + def parent_interframe(self): + return self._parent_interframe + + @property + def child_interframe(self): + return self._child_interframe + + @abstractmethod + def _generate_coordinates(self, coordinates): + """Generate Matrix of the joint's generalized coordinates.""" + pass + + @abstractmethod + def _generate_speeds(self, speeds): + """Generate Matrix of the joint's generalized speeds.""" + pass + + @abstractmethod + def _orient_frames(self): + """Orient frames as per the joint.""" + pass + + @abstractmethod + def _set_angular_velocity(self): + """Set angular velocity of the joint related frames.""" + pass + + @abstractmethod + def _set_linear_velocity(self): + """Set velocity of related points to the joint.""" + pass + + @staticmethod + def _to_vector(matrix, frame): + """Converts a matrix to a vector in the given frame.""" + return Vector([(matrix, frame)]) + + @staticmethod + def _axis(ax, *frames): + """Check whether an axis is fixed in one of the frames.""" + if ax is None: + ax = frames[0].x + return ax + if not isinstance(ax, Vector): + raise TypeError("Axis must be a Vector.") + ref_frame = None # Find a body in which the axis can be expressed + for frame in frames: + try: + ax.to_matrix(frame) + except ValueError: + pass + else: + ref_frame = frame + break + if ref_frame is None: + raise ValueError("Axis cannot be expressed in one of the body's " + "frames.") + if not ax.dt(ref_frame) == 0: + raise ValueError('Axis cannot be time-varying when viewed from the ' + 'associated body.') + return ax + + @staticmethod + def _choose_rotation_axis(frame, axis): + components = axis.to_matrix(frame) + x, y, z = components[0], components[1], components[2] + + if x != 0: + if y != 0: + if z != 0: + return cross(axis, frame.x) + if z != 0: + return frame.y + return frame.z + else: + if y != 0: + return frame.x + return frame.y + + @staticmethod + def _create_aligned_interframe(frame, align_axis, frame_axis=None, + frame_name=None): + """ + Returns an intermediate frame, where the ``frame_axis`` defined in + ``frame`` is aligned with ``axis``. By default this means that the X + axis will be aligned with ``axis``. + + Parameters + ========== + + frame : Body or ReferenceFrame + The body or reference frame with respect to which the intermediate + frame is oriented. + align_axis : Vector + The vector with respect to which the intermediate frame will be + aligned. + frame_axis : Vector + The vector of the frame which should get aligned with ``axis``. The + default is the X axis of the frame. + frame_name : string + Name of the to be created intermediate frame. The default adds + "_int_frame" to the name of ``frame``. + + Example + ======= + + An intermediate frame, where the X axis of the parent becomes aligned + with ``parent.y + parent.z`` can be created as follows: + + >>> from sympy.physics.mechanics.joint import Joint + >>> from sympy.physics.mechanics import Body + >>> parent = Body('parent') + >>> parent_interframe = Joint._create_aligned_interframe( + ... parent, parent.y + parent.z) + >>> parent_interframe + parent_int_frame + >>> parent.dcm(parent_interframe) + Matrix([ + [ 0, -sqrt(2)/2, -sqrt(2)/2], + [sqrt(2)/2, 1/2, -1/2], + [sqrt(2)/2, -1/2, 1/2]]) + >>> (parent.y + parent.z).express(parent_interframe) + sqrt(2)*parent_int_frame.x + + Notes + ===== + + The direction cosine matrix between the given frame and intermediate + frame is formed using a simple rotation about an axis that is normal to + both ``align_axis`` and ``frame_axis``. In general, the normal axis is + formed by crossing the ``frame_axis`` with the ``align_axis``. The + exception is if the axes are parallel with opposite directions, in which + case the rotation vector is chosen using the rules in the following + table with the vectors expressed in the given frame: + + .. list-table:: + :header-rows: 1 + + * - ``align_axis`` + - ``frame_axis`` + - ``rotation_axis`` + * - ``-x`` + - ``x`` + - ``z`` + * - ``-y`` + - ``y`` + - ``x`` + * - ``-z`` + - ``z`` + - ``y`` + * - ``-x-y`` + - ``x+y`` + - ``z`` + * - ``-y-z`` + - ``y+z`` + - ``x`` + * - ``-x-z`` + - ``x+z`` + - ``y`` + * - ``-x-y-z`` + - ``x+y+z`` + - ``(x+y+z) × x`` + + """ + if isinstance(frame, Body): + frame = frame.frame + if frame_axis is None: + frame_axis = frame.x + if frame_name is None: + if frame.name[-6:] == '_frame': + frame_name = f'{frame.name[:-6]}_int_frame' + else: + frame_name = f'{frame.name}_int_frame' + angle = frame_axis.angle_between(align_axis) + rotation_axis = cross(frame_axis, align_axis) + if rotation_axis == Vector(0) and angle == 0: + return frame + if angle == pi: + rotation_axis = Joint._choose_rotation_axis(frame, align_axis) + + int_frame = ReferenceFrame(frame_name) + int_frame.orient_axis(frame, rotation_axis, angle) + int_frame.set_ang_vel(frame, 0 * rotation_axis) + return int_frame + + def _generate_kdes(self): + """Generate kinematical differential equations.""" + kdes = [] + t = dynamicsymbols._t + for i in range(len(self.coordinates)): + kdes.append(-self.coordinates[i].diff(t) + self.speeds[i]) + return Matrix(kdes) + + def _locate_joint_pos(self, body, joint_pos): + """Returns the attachment point of a body.""" + if joint_pos is None: + return body.masscenter + if not isinstance(joint_pos, (Point, Vector)): + raise TypeError('Attachment point must be a Point or Vector.') + if isinstance(joint_pos, Vector): + point_name = f'{self.name}_{body.name}_joint' + joint_pos = body.masscenter.locatenew(point_name, joint_pos) + if not joint_pos.pos_from(body.masscenter).dt(body.frame) == 0: + raise ValueError('Attachment point must be fixed to the associated ' + 'body.') + return joint_pos + + def _locate_joint_frame(self, body, interframe): + """Returns the attachment frame of a body.""" + if interframe is None: + return body.frame + if isinstance(interframe, Vector): + interframe = Joint._create_aligned_interframe( + body, interframe, + frame_name=f'{self.name}_{body.name}_int_frame') + elif not isinstance(interframe, ReferenceFrame): + raise TypeError('Interframe must be a ReferenceFrame.') + if not interframe.ang_vel_in(body.frame) == 0: + raise ValueError(f'Interframe {interframe} is not fixed to body ' + f'{body}.') + body.masscenter.set_vel(interframe, 0) # Fixate interframe to body + return interframe + + def _fill_coordinate_list(self, coordinates, n_coords, label='q', offset=0, + number_single=False): + """Helper method for _generate_coordinates and _generate_speeds. + + Parameters + ========== + + coordinates : iterable + Iterable of coordinates or speeds that have been provided. + n_coords : Integer + Number of coordinates that should be returned. + label : String, optional + Coordinate type either 'q' (coordinates) or 'u' (speeds). The + Default is 'q'. + offset : Integer + Count offset when creating new dynamicsymbols. The default is 0. + number_single : Boolean + Boolean whether if n_coords == 1, number should still be used. The + default is False. + + """ + + def create_symbol(number): + if n_coords == 1 and not number_single: + return dynamicsymbols(f'{label}_{self.name}') + return dynamicsymbols(f'{label}{number}_{self.name}') + + name = 'generalized coordinate' if label == 'q' else 'generalized speed' + generated_coordinates = [] + if coordinates is None: + coordinates = [] + elif not iterable(coordinates): + coordinates = [coordinates] + if not (len(coordinates) == 0 or len(coordinates) == n_coords): + raise ValueError(f'Expected {n_coords} {name}s, instead got ' + f'{len(coordinates)} {name}s.') + # Supports more iterables, also Matrix + for i, coord in enumerate(coordinates): + if coord is None: + generated_coordinates.append(create_symbol(i + offset)) + elif isinstance(coord, (AppliedUndef, Derivative)): + generated_coordinates.append(coord) + else: + raise TypeError(f'The {name} {coord} should have been a ' + f'dynamicsymbol.') + for i in range(len(coordinates) + offset, n_coords + offset): + generated_coordinates.append(create_symbol(i)) + return Matrix(generated_coordinates) + + +class PinJoint(Joint): + """Pin (Revolute) Joint. + + .. image:: PinJoint.svg + + Explanation + =========== + + A pin joint is defined such that the joint rotation axis is fixed in both + the child and parent and the location of the joint is relative to the mass + center of each body. The child rotates an angle, θ, from the parent about + the rotation axis and has a simple angular speed, ω, relative to the + parent. The direction cosine matrix between the child interframe and + parent interframe is formed using a simple rotation about the joint axis. + The page on the joints framework gives a more detailed explanation of the + intermediate frames. + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + coordinates : dynamicsymbol, optional + Generalized coordinates of the joint. + speeds : dynamicsymbol, optional + Generalized speeds of joint. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the parent body which aligns with an axis fixed in the + child body. The default is the x axis of parent's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + child_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the child body which aligns with an axis fixed in the + parent body. The default is the x axis of child's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + joint_axis : Vector + The axis about which the rotation occurs. Note that the components + of this axis are the same in the parent_interframe and child_interframe. + parent_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by parent_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + child_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by child_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + coordinates : Matrix + Matrix of the joint's generalized coordinates. The default value is + ``dynamicsymbols(f'q_{joint.name}')``. + speeds : Matrix + Matrix of the joint's generalized speeds. The default value is + ``dynamicsymbols(f'u_{joint.name}')``. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_axis : Vector + The axis fixed in the parent frame that represents the joint. + child_axis : Vector + The axis fixed in the child frame that represents the joint. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + joint_axis : Vector + The axis about which the rotation occurs. Note that the components of + this axis are the same in the parent_interframe and child_interframe. + kdes : Matrix + Kinematical differential equations of the joint. + + Examples + ========= + + A single pin joint is created from two bodies and has the following basic + attributes: + + >>> from sympy.physics.mechanics import Body, PinJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = PinJoint('PC', parent, child) + >>> joint + PinJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.parent_axis + P_frame.x + >>> joint.child_axis + C_frame.x + >>> joint.coordinates + Matrix([[q_PC(t)]]) + >>> joint.speeds + Matrix([[u_PC(t)]]) + >>> joint.child.frame.ang_vel_in(joint.parent.frame) + u_PC(t)*P_frame.x + >>> joint.child.frame.dcm(joint.parent.frame) + Matrix([ + [1, 0, 0], + [0, cos(q_PC(t)), sin(q_PC(t))], + [0, -sin(q_PC(t)), cos(q_PC(t))]]) + >>> joint.child_point.pos_from(joint.parent_point) + 0 + + To further demonstrate the use of the pin joint, the kinematics of simple + double pendulum that rotates about the Z axis of each connected body can be + created as follows. + + >>> from sympy import symbols, trigsimp + >>> from sympy.physics.mechanics import Body, PinJoint + >>> l1, l2 = symbols('l1 l2') + + First create bodies to represent the fixed ceiling and one to represent + each pendulum bob. + + >>> ceiling = Body('C') + >>> upper_bob = Body('U') + >>> lower_bob = Body('L') + + The first joint will connect the upper bob to the ceiling by a distance of + ``l1`` and the joint axis will be about the Z axis for each body. + + >>> ceiling_joint = PinJoint('P1', ceiling, upper_bob, + ... child_point=-l1*upper_bob.frame.x, + ... joint_axis=ceiling.frame.z) + + The second joint will connect the lower bob to the upper bob by a distance + of ``l2`` and the joint axis will also be about the Z axis for each body. + + >>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob, + ... child_point=-l2*lower_bob.frame.x, + ... joint_axis=upper_bob.frame.z) + + Once the joints are established the kinematics of the connected bodies can + be accessed. First the direction cosine matrices of pendulum link relative + to the ceiling are found: + + >>> upper_bob.frame.dcm(ceiling.frame) + Matrix([ + [ cos(q_P1(t)), sin(q_P1(t)), 0], + [-sin(q_P1(t)), cos(q_P1(t)), 0], + [ 0, 0, 1]]) + >>> trigsimp(lower_bob.frame.dcm(ceiling.frame)) + Matrix([ + [ cos(q_P1(t) + q_P2(t)), sin(q_P1(t) + q_P2(t)), 0], + [-sin(q_P1(t) + q_P2(t)), cos(q_P1(t) + q_P2(t)), 0], + [ 0, 0, 1]]) + + The position of the lower bob's masscenter is found with: + + >>> lower_bob.masscenter.pos_from(ceiling.masscenter) + l1*U_frame.x + l2*L_frame.x + + The angular velocities of the two pendulum links can be computed with + respect to the ceiling. + + >>> upper_bob.frame.ang_vel_in(ceiling.frame) + u_P1(t)*C_frame.z + >>> lower_bob.frame.ang_vel_in(ceiling.frame) + u_P1(t)*C_frame.z + u_P2(t)*U_frame.z + + And finally, the linear velocities of the two pendulum bobs can be computed + with respect to the ceiling. + + >>> upper_bob.masscenter.vel(ceiling.frame) + l1*u_P1(t)*U_frame.y + >>> lower_bob.masscenter.vel(ceiling.frame) + l1*u_P1(t)*U_frame.y + l2*(u_P1(t) + u_P2(t))*L_frame.y + + """ + + def __init__(self, name, parent, child, coordinates=None, speeds=None, + parent_point=None, child_point=None, parent_axis=None, + child_axis=None, parent_interframe=None, child_interframe=None, + joint_axis=None, parent_joint_pos=None, child_joint_pos=None): + + self._joint_axis = joint_axis + super().__init__(name, parent, child, coordinates, speeds, parent_point, + child_point, parent_axis, child_axis, + parent_interframe, child_interframe, parent_joint_pos, + child_joint_pos) + + def __str__(self): + return (f'PinJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + @property + def joint_axis(self): + """Axis about which the child rotates with respect to the parent.""" + return self._joint_axis + + def _generate_coordinates(self, coordinate): + return self._fill_coordinate_list(coordinate, 1, 'q') + + def _generate_speeds(self, speed): + return self._fill_coordinate_list(speed, 1, 'u') + + def _orient_frames(self): + self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) + self.child_interframe.orient_axis( + self.parent_interframe, self.joint_axis, self.coordinates[0]) + + def _set_angular_velocity(self): + self.child_interframe.set_ang_vel(self.parent_interframe, self.speeds[ + 0] * self.joint_axis.normalize()) + + def _set_linear_velocity(self): + self.child_point.set_pos(self.parent_point, 0) + self.parent_point.set_vel(self.parent.frame, 0) + self.child_point.set_vel(self.child.frame, 0) + self.child.masscenter.v2pt_theory(self.parent_point, + self.parent.frame, self.child.frame) + + +class PrismaticJoint(Joint): + """Prismatic (Sliding) Joint. + + .. image:: PrismaticJoint.svg + + Explanation + =========== + + It is defined such that the child body translates with respect to the parent + body along the body-fixed joint axis. The location of the joint is defined + by two points, one in each body, which coincide when the generalized + coordinate is zero. The direction cosine matrix between the + parent_interframe and child_interframe is the identity matrix. Therefore, + the direction cosine matrix between the parent and child frames is fully + defined by the definition of the intermediate frames. The page on the joints + framework gives a more detailed explanation of the intermediate frames. + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + coordinates : dynamicsymbol, optional + Generalized coordinates of the joint. The default value is + ``dynamicsymbols(f'q_{joint.name}')``. + speeds : dynamicsymbol, optional + Generalized speeds of joint. The default value is + ``dynamicsymbols(f'u_{joint.name}')``. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the parent body which aligns with an axis fixed in the + child body. The default is the x axis of parent's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + child_axis : Vector, optional + .. deprecated:: 1.12 + Axis fixed in the child body which aligns with an axis fixed in the + parent body. The default is the x axis of child's reference frame. + For more information on this deprecation, see + :ref:`deprecated-mechanics-joint-axis`. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + joint_axis : Vector + The axis along which the translation occurs. Note that the components + of this axis are the same in the parent_interframe and child_interframe. + parent_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by parent_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + child_joint_pos : Point or Vector, optional + .. deprecated:: 1.12 + This argument is replaced by child_point and will be removed in a + future version. + See :ref:`deprecated-mechanics-joint-pos` for more information. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + coordinates : Matrix + Matrix of the joint's generalized coordinates. + speeds : Matrix + Matrix of the joint's generalized speeds. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_axis : Vector + The axis fixed in the parent frame that represents the joint. + child_axis : Vector + The axis fixed in the child frame that represents the joint. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + + Examples + ========= + + A single prismatic joint is created from two bodies and has the following + basic attributes: + + >>> from sympy.physics.mechanics import Body, PrismaticJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = PrismaticJoint('PC', parent, child) + >>> joint + PrismaticJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.parent_axis + P_frame.x + >>> joint.child_axis + C_frame.x + >>> joint.coordinates + Matrix([[q_PC(t)]]) + >>> joint.speeds + Matrix([[u_PC(t)]]) + >>> joint.child.frame.ang_vel_in(joint.parent.frame) + 0 + >>> joint.child.frame.dcm(joint.parent.frame) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> joint.child_point.pos_from(joint.parent_point) + q_PC(t)*P_frame.x + + To further demonstrate the use of the prismatic joint, the kinematics of two + masses sliding, one moving relative to a fixed body and the other relative + to the moving body. about the X axis of each connected body can be created + as follows. + + >>> from sympy.physics.mechanics import PrismaticJoint, Body + + First create bodies to represent the fixed ceiling and one to represent + a particle. + + >>> wall = Body('W') + >>> Part1 = Body('P1') + >>> Part2 = Body('P2') + + The first joint will connect the particle to the ceiling and the + joint axis will be about the X axis for each body. + + >>> J1 = PrismaticJoint('J1', wall, Part1) + + The second joint will connect the second particle to the first particle + and the joint axis will also be about the X axis for each body. + + >>> J2 = PrismaticJoint('J2', Part1, Part2) + + Once the joint is established the kinematics of the connected bodies can + be accessed. First the direction cosine matrices of Part relative + to the ceiling are found: + + >>> Part1.dcm(wall) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + >>> Part2.dcm(wall) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + + The position of the particles' masscenter is found with: + + >>> Part1.masscenter.pos_from(wall.masscenter) + q_J1(t)*W_frame.x + + >>> Part2.masscenter.pos_from(wall.masscenter) + q_J1(t)*W_frame.x + q_J2(t)*P1_frame.x + + The angular velocities of the two particle links can be computed with + respect to the ceiling. + + >>> Part1.ang_vel_in(wall) + 0 + + >>> Part2.ang_vel_in(wall) + 0 + + And finally, the linear velocities of the two particles can be computed + with respect to the ceiling. + + >>> Part1.masscenter_vel(wall) + u_J1(t)*W_frame.x + + >>> Part2.masscenter.vel(wall.frame) + u_J1(t)*W_frame.x + Derivative(q_J2(t), t)*P1_frame.x + + """ + + def __init__(self, name, parent, child, coordinates=None, speeds=None, + parent_point=None, child_point=None, parent_axis=None, + child_axis=None, parent_interframe=None, child_interframe=None, + joint_axis=None, parent_joint_pos=None, child_joint_pos=None): + + self._joint_axis = joint_axis + super().__init__(name, parent, child, coordinates, speeds, parent_point, + child_point, parent_axis, child_axis, + parent_interframe, child_interframe, parent_joint_pos, + child_joint_pos) + + def __str__(self): + return (f'PrismaticJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + @property + def joint_axis(self): + """Axis along which the child translates with respect to the parent.""" + return self._joint_axis + + def _generate_coordinates(self, coordinate): + return self._fill_coordinate_list(coordinate, 1, 'q') + + def _generate_speeds(self, speed): + return self._fill_coordinate_list(speed, 1, 'u') + + def _orient_frames(self): + self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) + self.child_interframe.orient_axis( + self.parent_interframe, self.joint_axis, 0) + + def _set_angular_velocity(self): + self.child_interframe.set_ang_vel(self.parent_interframe, 0) + + def _set_linear_velocity(self): + axis = self.joint_axis.normalize() + self.child_point.set_pos(self.parent_point, self.coordinates[0] * axis) + self.parent_point.set_vel(self.parent.frame, 0) + self.child_point.set_vel(self.child.frame, 0) + self.child_point.set_vel(self.parent.frame, self.speeds[0] * axis) + self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * axis) + + +class CylindricalJoint(Joint): + """Cylindrical Joint. + + .. image:: CylindricalJoint.svg + :align: center + :width: 600 + + Explanation + =========== + + A cylindrical joint is defined such that the child body both rotates about + and translates along the body-fixed joint axis with respect to the parent + body. The joint axis is both the rotation axis and translation axis. The + location of the joint is defined by two points, one in each body, which + coincide when the generalized coordinate corresponding to the translation is + zero. The direction cosine matrix between the child interframe and parent + interframe is formed using a simple rotation about the joint axis. The page + on the joints framework gives a more detailed explanation of the + intermediate frames. + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + rotation_coordinate : dynamicsymbol, optional + Generalized coordinate corresponding to the rotation angle. The default + value is ``dynamicsymbols(f'q0_{joint.name}')``. + translation_coordinate : dynamicsymbol, optional + Generalized coordinate corresponding to the translation distance. The + default value is ``dynamicsymbols(f'q1_{joint.name}')``. + rotation_speed : dynamicsymbol, optional + Generalized speed corresponding to the angular velocity. The default + value is ``dynamicsymbols(f'u0_{joint.name}')``. + translation_speed : dynamicsymbol, optional + Generalized speed corresponding to the translation velocity. The default + value is ``dynamicsymbols(f'u1_{joint.name}')``. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + joint_axis : Vector, optional + The rotation as well as translation axis. Note that the components of + this axis are the same in the parent_interframe and child_interframe. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + rotation_coordinate : dynamicsymbol + Generalized coordinate corresponding to the rotation angle. + translation_coordinate : dynamicsymbol + Generalized coordinate corresponding to the translation distance. + rotation_speed : dynamicsymbol + Generalized speed corresponding to the angular velocity. + translation_speed : dynamicsymbol + Generalized speed corresponding to the translation velocity. + coordinates : Matrix + Matrix of the joint's generalized coordinates. + speeds : Matrix + Matrix of the joint's generalized speeds. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + joint_axis : Vector + The axis of rotation and translation. + + Examples + ========= + + A single cylindrical joint is created between two bodies and has the + following basic attributes: + + >>> from sympy.physics.mechanics import Body, CylindricalJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = CylindricalJoint('PC', parent, child) + >>> joint + CylindricalJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.parent_axis + P_frame.x + >>> joint.child_axis + C_frame.x + >>> joint.coordinates + Matrix([ + [q0_PC(t)], + [q1_PC(t)]]) + >>> joint.speeds + Matrix([ + [u0_PC(t)], + [u1_PC(t)]]) + >>> joint.child.frame.ang_vel_in(joint.parent.frame) + u0_PC(t)*P_frame.x + >>> joint.child.frame.dcm(joint.parent.frame) + Matrix([ + [1, 0, 0], + [0, cos(q0_PC(t)), sin(q0_PC(t))], + [0, -sin(q0_PC(t)), cos(q0_PC(t))]]) + >>> joint.child_point.pos_from(joint.parent_point) + q1_PC(t)*P_frame.x + >>> child.masscenter.vel(parent.frame) + u1_PC(t)*P_frame.x + + To further demonstrate the use of the cylindrical joint, the kinematics of + two cylindrical joints perpendicular to each other can be created as follows. + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, CylindricalJoint + >>> r, l, w = symbols('r l w') + + First create bodies to represent the fixed floor with a fixed pole on it. + The second body represents a freely moving tube around that pole. The third + body represents a solid flag freely translating along and rotating around + the Y axis of the tube. + + >>> floor = Body('floor') + >>> tube = Body('tube') + >>> flag = Body('flag') + + The first joint will connect the first tube to the floor with it translating + along and rotating around the Z axis of both bodies. + + >>> floor_joint = CylindricalJoint('C1', floor, tube, joint_axis=floor.z) + + The second joint will connect the tube perpendicular to the flag along the Y + axis of both the tube and the flag, with the joint located at a distance + ``r`` from the tube's center of mass and a combination of the distances + ``l`` and ``w`` from the flag's center of mass. + + >>> flag_joint = CylindricalJoint('C2', tube, flag, + ... parent_point=r * tube.y, + ... child_point=-w * flag.y + l * flag.z, + ... joint_axis=tube.y) + + Once the joints are established the kinematics of the connected bodies can + be accessed. First the direction cosine matrices of both the body and the + flag relative to the floor are found: + + >>> tube.dcm(floor) + Matrix([ + [ cos(q0_C1(t)), sin(q0_C1(t)), 0], + [-sin(q0_C1(t)), cos(q0_C1(t)), 0], + [ 0, 0, 1]]) + >>> flag.dcm(floor) + Matrix([ + [cos(q0_C1(t))*cos(q0_C2(t)), sin(q0_C1(t))*cos(q0_C2(t)), -sin(q0_C2(t))], + [ -sin(q0_C1(t)), cos(q0_C1(t)), 0], + [sin(q0_C2(t))*cos(q0_C1(t)), sin(q0_C1(t))*sin(q0_C2(t)), cos(q0_C2(t))]]) + + The position of the flag's center of mass is found with: + + >>> flag.masscenter.pos_from(floor.masscenter) + q1_C1(t)*floor_frame.z + (r + q1_C2(t))*tube_frame.y + w*flag_frame.y - l*flag_frame.z + + The angular velocities of the two tubes can be computed with respect to the + floor. + + >>> tube.ang_vel_in(floor) + u0_C1(t)*floor_frame.z + >>> flag.ang_vel_in(floor) + u0_C1(t)*floor_frame.z + u0_C2(t)*tube_frame.y + + Finally, the linear velocities of the two tube centers of mass can be + computed with respect to the floor, while expressed in the tube's frame. + + >>> tube.masscenter.vel(floor.frame).to_matrix(tube.frame) + Matrix([ + [ 0], + [ 0], + [u1_C1(t)]]) + >>> flag.masscenter.vel(floor.frame).to_matrix(tube.frame).simplify() + Matrix([ + [-l*u0_C2(t)*cos(q0_C2(t)) - r*u0_C1(t) - w*u0_C1(t) - q1_C2(t)*u0_C1(t)], + [ -l*u0_C1(t)*sin(q0_C2(t)) + Derivative(q1_C2(t), t)], + [ l*u0_C2(t)*sin(q0_C2(t)) + u1_C1(t)]]) + + """ + + def __init__(self, name, parent, child, rotation_coordinate=None, + translation_coordinate=None, rotation_speed=None, + translation_speed=None, parent_point=None, child_point=None, + parent_interframe=None, child_interframe=None, + joint_axis=None): + self._joint_axis = joint_axis + coordinates = (rotation_coordinate, translation_coordinate) + speeds = (rotation_speed, translation_speed) + super().__init__(name, parent, child, coordinates, speeds, + parent_point, child_point, + parent_interframe=parent_interframe, + child_interframe=child_interframe) + + def __str__(self): + return (f'CylindricalJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + @property + def joint_axis(self): + """Axis about and along which the rotation and translation occurs.""" + return self._joint_axis + + @property + def rotation_coordinate(self): + """Generalized coordinate corresponding to the rotation angle.""" + return self.coordinates[0] + + @property + def translation_coordinate(self): + """Generalized coordinate corresponding to the translation distance.""" + return self.coordinates[1] + + @property + def rotation_speed(self): + """Generalized speed corresponding to the angular velocity.""" + return self.speeds[0] + + @property + def translation_speed(self): + """Generalized speed corresponding to the translation velocity.""" + return self.speeds[1] + + def _generate_coordinates(self, coordinates): + return self._fill_coordinate_list(coordinates, 2, 'q') + + def _generate_speeds(self, speeds): + return self._fill_coordinate_list(speeds, 2, 'u') + + def _orient_frames(self): + self._joint_axis = self._axis(self.joint_axis, self.parent_interframe) + self.child_interframe.orient_axis( + self.parent_interframe, self.joint_axis, self.rotation_coordinate) + + def _set_angular_velocity(self): + self.child_interframe.set_ang_vel( + self.parent_interframe, + self.rotation_speed * self.joint_axis.normalize()) + + def _set_linear_velocity(self): + self.child_point.set_pos( + self.parent_point, + self.translation_coordinate * self.joint_axis.normalize()) + self.parent_point.set_vel(self.parent.frame, 0) + self.child_point.set_vel(self.child.frame, 0) + self.child_point.set_vel( + self.parent.frame, + self.translation_speed * self.joint_axis.normalize()) + self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame, + self.child_interframe) + + +class PlanarJoint(Joint): + """Planar Joint. + + .. image:: PlanarJoint.svg + :align: center + :width: 800 + + Explanation + =========== + + A planar joint is defined such that the child body translates over a fixed + plane of the parent body as well as rotate about the rotation axis, which + is perpendicular to that plane. The origin of this plane is the + ``parent_point`` and the plane is spanned by two nonparallel planar vectors. + The location of the ``child_point`` is based on the planar vectors + ($\\vec{v}_1$, $\\vec{v}_2$) and generalized coordinates ($q_1$, $q_2$), + i.e. $\\vec{r} = q_1 \\hat{v}_1 + q_2 \\hat{v}_2$. The direction cosine + matrix between the ``child_interframe`` and ``parent_interframe`` is formed + using a simple rotation ($q_0$) about the rotation axis. + + In order to simplify the definition of the ``PlanarJoint``, the + ``rotation_axis`` and ``planar_vectors`` are set to be the unit vectors of + the ``parent_interframe`` according to the table below. This ensures that + you can only define these vectors by creating a separate frame and supplying + that as the interframe. If you however would only like to supply the normals + of the plane with respect to the parent and child bodies, then you can also + supply those to the ``parent_interframe`` and ``child_interframe`` + arguments. An example of both of these cases is in the examples section + below and the page on the joints framework provides a more detailed + explanation of the intermediate frames. + + .. list-table:: + + * - ``rotation_axis`` + - ``parent_interframe.x`` + * - ``planar_vectors[0]`` + - ``parent_interframe.y`` + * - ``planar_vectors[1]`` + - ``parent_interframe.z`` + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + rotation_coordinate : dynamicsymbol, optional + Generalized coordinate corresponding to the rotation angle. The default + value is ``dynamicsymbols(f'q0_{joint.name}')``. + planar_coordinates : iterable of dynamicsymbols, optional + Two generalized coordinates used for the planar translation. The default + value is ``dynamicsymbols(f'q1_{joint.name} q2_{joint.name}')``. + rotation_speed : dynamicsymbol, optional + Generalized speed corresponding to the angular velocity. The default + value is ``dynamicsymbols(f'u0_{joint.name}')``. + planar_speeds : dynamicsymbols, optional + Two generalized speeds used for the planar translation velocity. The + default value is ``dynamicsymbols(f'u1_{joint.name} u2_{joint.name}')``. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + rotation_coordinate : dynamicsymbol + Generalized coordinate corresponding to the rotation angle. + planar_coordinates : Matrix + Two generalized coordinates used for the planar translation. + rotation_speed : dynamicsymbol + Generalized speed corresponding to the angular velocity. + planar_speeds : Matrix + Two generalized speeds used for the planar translation velocity. + coordinates : Matrix + Matrix of the joint's generalized coordinates. + speeds : Matrix + Matrix of the joint's generalized speeds. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + rotation_axis : Vector + The axis about which the rotation occurs. + planar_vectors : list + The vectors that describe the planar translation directions. + + Examples + ========= + + A single planar joint is created between two bodies and has the following + basic attributes: + + >>> from sympy.physics.mechanics import Body, PlanarJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = PlanarJoint('PC', parent, child) + >>> joint + PlanarJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.rotation_axis + P_frame.x + >>> joint.planar_vectors + [P_frame.y, P_frame.z] + >>> joint.rotation_coordinate + q0_PC(t) + >>> joint.planar_coordinates + Matrix([ + [q1_PC(t)], + [q2_PC(t)]]) + >>> joint.coordinates + Matrix([ + [q0_PC(t)], + [q1_PC(t)], + [q2_PC(t)]]) + >>> joint.rotation_speed + u0_PC(t) + >>> joint.planar_speeds + Matrix([ + [u1_PC(t)], + [u2_PC(t)]]) + >>> joint.speeds + Matrix([ + [u0_PC(t)], + [u1_PC(t)], + [u2_PC(t)]]) + >>> joint.child.frame.ang_vel_in(joint.parent.frame) + u0_PC(t)*P_frame.x + >>> joint.child.frame.dcm(joint.parent.frame) + Matrix([ + [1, 0, 0], + [0, cos(q0_PC(t)), sin(q0_PC(t))], + [0, -sin(q0_PC(t)), cos(q0_PC(t))]]) + >>> joint.child_point.pos_from(joint.parent_point) + q1_PC(t)*P_frame.y + q2_PC(t)*P_frame.z + >>> child.masscenter.vel(parent.frame) + u1_PC(t)*P_frame.y + u2_PC(t)*P_frame.z + + To further demonstrate the use of the planar joint, the kinematics of a + block sliding on a slope, can be created as follows. + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import PlanarJoint, Body, ReferenceFrame + >>> a, d, h = symbols('a d h') + + First create bodies to represent the slope and the block. + + >>> ground = Body('G') + >>> block = Body('B') + + To define the slope you can either define the plane by specifying the + ``planar_vectors`` or/and the ``rotation_axis``. However it is advisable to + create a rotated intermediate frame, so that the ``parent_vectors`` and + ``rotation_axis`` will be the unit vectors of this intermediate frame. + + >>> slope = ReferenceFrame('A') + >>> slope.orient_axis(ground.frame, ground.y, a) + + The planar joint can be created using these bodies and intermediate frame. + We can specify the origin of the slope to be ``d`` above the slope's center + of mass and the block's center of mass to be a distance ``h`` above the + slope's surface. Note that we can specify the normal of the plane using the + rotation axis argument. + + >>> joint = PlanarJoint('PC', ground, block, parent_point=d * ground.x, + ... child_point=-h * block.x, parent_interframe=slope) + + Once the joint is established the kinematics of the bodies can be accessed. + First the ``rotation_axis``, which is normal to the plane and the + ``plane_vectors``, can be found. + + >>> joint.rotation_axis + A.x + >>> joint.planar_vectors + [A.y, A.z] + + The direction cosine matrix of the block with respect to the ground can be + found with: + + >>> block.dcm(ground) + Matrix([ + [ cos(a), 0, -sin(a)], + [sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)], + [sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]]) + + The angular velocity of the block can be computed with respect to the + ground. + + >>> block.ang_vel_in(ground) + u0_PC(t)*A.x + + The position of the block's center of mass can be found with: + + >>> block.masscenter.pos_from(ground.masscenter) + d*G_frame.x + h*B_frame.x + q1_PC(t)*A.y + q2_PC(t)*A.z + + Finally, the linear velocity of the block's center of mass can be + computed with respect to the ground. + + >>> block.masscenter.vel(ground.frame) + u1_PC(t)*A.y + u2_PC(t)*A.z + + In some cases it could be your preference to only define the normals of the + plane with respect to both bodies. This can most easily be done by supplying + vectors to the ``interframe`` arguments. What will happen in this case is + that an interframe will be created with its ``x`` axis aligned with the + provided vector. For a further explanation of how this is done see the notes + of the ``Joint`` class. In the code below, the above example (with the block + on the slope) is recreated by supplying vectors to the interframe arguments. + Note that the previously described option is however more computationally + efficient, because the algorithm now has to compute the rotation angle + between the provided vector and the 'x' axis. + + >>> from sympy import symbols, cos, sin + >>> from sympy.physics.mechanics import PlanarJoint, Body + >>> a, d, h = symbols('a d h') + >>> ground = Body('G') + >>> block = Body('B') + >>> joint = PlanarJoint( + ... 'PC', ground, block, parent_point=d * ground.x, + ... child_point=-h * block.x, child_interframe=block.x, + ... parent_interframe=cos(a) * ground.x + sin(a) * ground.z) + >>> block.dcm(ground).simplify() + Matrix([ + [ cos(a), 0, sin(a)], + [-sin(a)*sin(q0_PC(t)), cos(q0_PC(t)), sin(q0_PC(t))*cos(a)], + [-sin(a)*cos(q0_PC(t)), -sin(q0_PC(t)), cos(a)*cos(q0_PC(t))]]) + + """ + + def __init__(self, name, parent, child, rotation_coordinate=None, + planar_coordinates=None, rotation_speed=None, + planar_speeds=None, parent_point=None, child_point=None, + parent_interframe=None, child_interframe=None): + # A ready to merge implementation of setting the planar_vectors and + # rotation_axis was added and removed in PR #24046 + coordinates = (rotation_coordinate, planar_coordinates) + speeds = (rotation_speed, planar_speeds) + super().__init__(name, parent, child, coordinates, speeds, + parent_point, child_point, + parent_interframe=parent_interframe, + child_interframe=child_interframe) + + def __str__(self): + return (f'PlanarJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + @property + def rotation_coordinate(self): + """Generalized coordinate corresponding to the rotation angle.""" + return self.coordinates[0] + + @property + def planar_coordinates(self): + """Two generalized coordinates used for the planar translation.""" + return self.coordinates[1:, 0] + + @property + def rotation_speed(self): + """Generalized speed corresponding to the angular velocity.""" + return self.speeds[0] + + @property + def planar_speeds(self): + """Two generalized speeds used for the planar translation velocity.""" + return self.speeds[1:, 0] + + @property + def rotation_axis(self): + """The axis about which the rotation occurs.""" + return self.parent_interframe.x + + @property + def planar_vectors(self): + """The vectors that describe the planar translation directions.""" + return [self.parent_interframe.y, self.parent_interframe.z] + + def _generate_coordinates(self, coordinates): + rotation_speed = self._fill_coordinate_list(coordinates[0], 1, 'q', + number_single=True) + planar_speeds = self._fill_coordinate_list(coordinates[1], 2, 'q', 1) + return rotation_speed.col_join(planar_speeds) + + def _generate_speeds(self, speeds): + rotation_speed = self._fill_coordinate_list(speeds[0], 1, 'u', + number_single=True) + planar_speeds = self._fill_coordinate_list(speeds[1], 2, 'u', 1) + return rotation_speed.col_join(planar_speeds) + + def _orient_frames(self): + self.child_interframe.orient_axis( + self.parent_interframe, self.rotation_axis, + self.rotation_coordinate) + + def _set_angular_velocity(self): + self.child_interframe.set_ang_vel( + self.parent_interframe, + self.rotation_speed * self.rotation_axis) + + def _set_linear_velocity(self): + self.child_point.set_pos( + self.parent_point, + self.planar_coordinates[0] * self.planar_vectors[0] + + self.planar_coordinates[1] * self.planar_vectors[1]) + self.parent_point.set_vel(self.parent_interframe, 0) + self.child_point.set_vel(self.child_interframe, 0) + self.child_point.set_vel( + self.parent.frame, self.planar_speeds[0] * self.planar_vectors[0] + + self.planar_speeds[1] * self.planar_vectors[1]) + self.child.masscenter.v2pt_theory(self.child_point, self.parent.frame, + self.child.frame) + + +class SphericalJoint(Joint): + """Spherical (Ball-and-Socket) Joint. + + .. image:: SphericalJoint.svg + :align: center + :width: 600 + + Explanation + =========== + + A spherical joint is defined such that the child body is free to rotate in + any direction, without allowing a translation of the ``child_point``. As can + also be seen in the image, the ``parent_point`` and ``child_point`` are + fixed on top of each other, i.e. the ``joint_point``. This rotation is + defined using the :func:`parent_interframe.orient(child_interframe, + rot_type, amounts, rot_order) + ` method. The default + rotation consists of three relative rotations, i.e. body-fixed rotations. + Based on the direction cosine matrix following from these rotations, the + angular velocity is computed based on the generalized coordinates and + generalized speeds. + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + coordinates: iterable of dynamicsymbols, optional + Generalized coordinates of the joint. + speeds : iterable of dynamicsymbols, optional + Generalized speeds of joint. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + rot_type : str, optional + The method used to generate the direction cosine matrix. Supported + methods are: + + - ``'Body'``: three successive rotations about new intermediate axes, + also called "Euler and Tait-Bryan angles" + - ``'Space'``: three successive rotations about the parent frames' unit + vectors + + The default method is ``'Body'``. + amounts : + Expressions defining the rotation angles or direction cosine matrix. + These must match the ``rot_type``. See examples below for details. The + input types are: + + - ``'Body'``: 3-tuple of expressions, symbols, or functions + - ``'Space'``: 3-tuple of expressions, symbols, or functions + + The default amounts are the given ``coordinates``. + rot_order : str or int, optional + If applicable, the order of the successive of rotations. The string + ``'123'`` and integer ``123`` are equivalent, for example. Required for + ``'Body'`` and ``'Space'``. The default value is ``123``. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + coordinates : Matrix + Matrix of the joint's generalized coordinates. + speeds : Matrix + Matrix of the joint's generalized speeds. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + + Examples + ========= + + A single spherical joint is created from two bodies and has the following + basic attributes: + + >>> from sympy.physics.mechanics import Body, SphericalJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = SphericalJoint('PC', parent, child) + >>> joint + SphericalJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.parent_interframe + P_frame + >>> joint.child_interframe + C_frame + >>> joint.coordinates + Matrix([ + [q0_PC(t)], + [q1_PC(t)], + [q2_PC(t)]]) + >>> joint.speeds + Matrix([ + [u0_PC(t)], + [u1_PC(t)], + [u2_PC(t)]]) + >>> child.frame.ang_vel_in(parent.frame).to_matrix(child.frame) + Matrix([ + [ u0_PC(t)*cos(q1_PC(t))*cos(q2_PC(t)) + u1_PC(t)*sin(q2_PC(t))], + [-u0_PC(t)*sin(q2_PC(t))*cos(q1_PC(t)) + u1_PC(t)*cos(q2_PC(t))], + [ u0_PC(t)*sin(q1_PC(t)) + u2_PC(t)]]) + >>> child.frame.x.to_matrix(parent.frame) + Matrix([ + [ cos(q1_PC(t))*cos(q2_PC(t))], + [sin(q0_PC(t))*sin(q1_PC(t))*cos(q2_PC(t)) + sin(q2_PC(t))*cos(q0_PC(t))], + [sin(q0_PC(t))*sin(q2_PC(t)) - sin(q1_PC(t))*cos(q0_PC(t))*cos(q2_PC(t))]]) + >>> joint.child_point.pos_from(joint.parent_point) + 0 + + To further demonstrate the use of the spherical joint, the kinematics of a + spherical joint with a ZXZ rotation can be created as follows. + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, SphericalJoint + >>> l1 = symbols('l1') + + First create bodies to represent the fixed floor and a pendulum bob. + + >>> floor = Body('F') + >>> bob = Body('B') + + The joint will connect the bob to the floor, with the joint located at a + distance of ``l1`` from the child's center of mass and the rotation set to a + body-fixed ZXZ rotation. + + >>> joint = SphericalJoint('S', floor, bob, child_point=l1 * bob.y, + ... rot_type='body', rot_order='ZXZ') + + Now that the joint is established, the kinematics of the connected body can + be accessed. + + The position of the bob's masscenter is found with: + + >>> bob.masscenter.pos_from(floor.masscenter) + - l1*B_frame.y + + The angular velocities of the pendulum link can be computed with respect to + the floor. + + >>> bob.frame.ang_vel_in(floor.frame).to_matrix( + ... floor.frame).simplify() + Matrix([ + [u1_S(t)*cos(q0_S(t)) + u2_S(t)*sin(q0_S(t))*sin(q1_S(t))], + [u1_S(t)*sin(q0_S(t)) - u2_S(t)*sin(q1_S(t))*cos(q0_S(t))], + [ u0_S(t) + u2_S(t)*cos(q1_S(t))]]) + + Finally, the linear velocity of the bob's center of mass can be computed. + + >>> bob.masscenter.vel(floor.frame).to_matrix(bob.frame) + Matrix([ + [ l1*(u0_S(t)*cos(q1_S(t)) + u2_S(t))], + [ 0], + [-l1*(u0_S(t)*sin(q1_S(t))*sin(q2_S(t)) + u1_S(t)*cos(q2_S(t)))]]) + + """ + def __init__(self, name, parent, child, coordinates=None, speeds=None, + parent_point=None, child_point=None, parent_interframe=None, + child_interframe=None, rot_type='BODY', amounts=None, + rot_order=123): + self._rot_type = rot_type + self._amounts = amounts + self._rot_order = rot_order + super().__init__(name, parent, child, coordinates, speeds, + parent_point, child_point, + parent_interframe=parent_interframe, + child_interframe=child_interframe) + + def __str__(self): + return (f'SphericalJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + def _generate_coordinates(self, coordinates): + return self._fill_coordinate_list(coordinates, 3, 'q') + + def _generate_speeds(self, speeds): + return self._fill_coordinate_list(speeds, len(self.coordinates), 'u') + + def _orient_frames(self): + supported_rot_types = ('BODY', 'SPACE') + if self._rot_type.upper() not in supported_rot_types: + raise NotImplementedError( + f'Rotation type "{self._rot_type}" is not implemented. ' + f'Implemented rotation types are: {supported_rot_types}') + amounts = self.coordinates if self._amounts is None else self._amounts + self.child_interframe.orient(self.parent_interframe, self._rot_type, + amounts, self._rot_order) + + def _set_angular_velocity(self): + t = dynamicsymbols._t + vel = self.child_interframe.ang_vel_in(self.parent_interframe).xreplace( + {q.diff(t): u for q, u in zip(self.coordinates, self.speeds)} + ) + self.child_interframe.set_ang_vel(self.parent_interframe, vel) + + def _set_linear_velocity(self): + self.child_point.set_pos(self.parent_point, 0) + self.parent_point.set_vel(self.parent.frame, 0) + self.child_point.set_vel(self.child.frame, 0) + self.child.masscenter.v2pt_theory(self.parent_point, self.parent.frame, + self.child.frame) + + +class WeldJoint(Joint): + """Weld Joint. + + .. image:: WeldJoint.svg + :align: center + :width: 500 + + Explanation + =========== + + A weld joint is defined such that there is no relative motion between the + child and parent bodies. The direction cosine matrix between the attachment + frame (``parent_interframe`` and ``child_interframe``) is the identity + matrix and the attachment points (``parent_point`` and ``child_point``) are + coincident. The page on the joints framework gives a more detailed + explanation of the intermediate frames. + + Parameters + ========== + + name : string + A unique name for the joint. + parent : Body + The parent body of joint. + child : Body + The child body of joint. + parent_point : Point or Vector, optional + Attachment point where the joint is fixed to the parent body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the parent's mass + center. + child_point : Point or Vector, optional + Attachment point where the joint is fixed to the child body. If a + vector is provided, then the attachment point is computed by adding the + vector to the body's mass center. The default value is the child's mass + center. + parent_interframe : ReferenceFrame, optional + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the parent's own frame. + child_interframe : ReferenceFrame, optional + Intermediate frame of the child body with respect to which the joint + transformation is formulated. If a Vector is provided then an interframe + is created which aligns its X axis with the given vector. The default + value is the child's own frame. + + Attributes + ========== + + name : string + The joint's name. + parent : Body + The joint's parent body. + child : Body + The joint's child body. + coordinates : Matrix + Matrix of the joint's generalized coordinates. The default value is + ``dynamicsymbols(f'q_{joint.name}')``. + speeds : Matrix + Matrix of the joint's generalized speeds. The default value is + ``dynamicsymbols(f'u_{joint.name}')``. + parent_point : Point + Attachment point where the joint is fixed to the parent body. + child_point : Point + Attachment point where the joint is fixed to the child body. + parent_interframe : ReferenceFrame + Intermediate frame of the parent body with respect to which the joint + transformation is formulated. + child_interframe : ReferenceFrame + Intermediate frame of the child body with respect to which the joint + transformation is formulated. + kdes : Matrix + Kinematical differential equations of the joint. + + Examples + ========= + + A single weld joint is created from two bodies and has the following basic + attributes: + + >>> from sympy.physics.mechanics import Body, WeldJoint + >>> parent = Body('P') + >>> parent + P + >>> child = Body('C') + >>> child + C + >>> joint = WeldJoint('PC', parent, child) + >>> joint + WeldJoint: PC parent: P child: C + >>> joint.name + 'PC' + >>> joint.parent + P + >>> joint.child + C + >>> joint.parent_point + P_masscenter + >>> joint.child_point + C_masscenter + >>> joint.coordinates + Matrix(0, 0, []) + >>> joint.speeds + Matrix(0, 0, []) + >>> joint.child.frame.ang_vel_in(joint.parent.frame) + 0 + >>> joint.child.frame.dcm(joint.parent.frame) + Matrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1]]) + >>> joint.child_point.pos_from(joint.parent_point) + 0 + + To further demonstrate the use of the weld joint, two relatively-fixed + bodies rotated by a quarter turn about the Y axis can be created as follows: + + >>> from sympy import symbols, pi + >>> from sympy.physics.mechanics import ReferenceFrame, Body, WeldJoint + >>> l1, l2 = symbols('l1 l2') + + First create the bodies to represent the parent and rotated child body. + + >>> parent = Body('P') + >>> child = Body('C') + + Next the intermediate frame specifying the fixed rotation with respect to + the parent can be created. + + >>> rotated_frame = ReferenceFrame('Pr') + >>> rotated_frame.orient_axis(parent.frame, parent.y, pi / 2) + + The weld between the parent body and child body is located at a distance + ``l1`` from the parent's center of mass in the X direction and ``l2`` from + the child's center of mass in the child's negative X direction. + + >>> weld = WeldJoint('weld', parent, child, parent_point=l1 * parent.x, + ... child_point=-l2 * child.x, + ... parent_interframe=rotated_frame) + + Now that the joint has been established, the kinematics of the bodies can be + accessed. The direction cosine matrix of the child body with respect to the + parent can be found: + + >>> child.dcm(parent) + Matrix([ + [0, 0, -1], + [0, 1, 0], + [1, 0, 0]]) + + As can also been seen from the direction cosine matrix, the parent X axis is + aligned with the child's Z axis: + >>> parent.x == child.z + True + + The position of the child's center of mass with respect to the parent's + center of mass can be found with: + + >>> child.masscenter.pos_from(parent.masscenter) + l1*P_frame.x + l2*C_frame.x + + The angular velocity of the child with respect to the parent is 0 as one + would expect. + + >>> child.ang_vel_in(parent) + 0 + + """ + + def __init__(self, name, parent, child, parent_point=None, child_point=None, + parent_interframe=None, child_interframe=None): + super().__init__(name, parent, child, [], [], parent_point, + child_point, parent_interframe=parent_interframe, + child_interframe=child_interframe) + self._kdes = Matrix(1, 0, []).T # Removes stackability problems #10770 + + def __str__(self): + return (f'WeldJoint: {self.name} parent: {self.parent} ' + f'child: {self.child}') + + def _generate_coordinates(self, coordinate): + return Matrix() + + def _generate_speeds(self, speed): + return Matrix() + + def _orient_frames(self): + self.child_interframe.orient_axis(self.parent_interframe, + self.parent_interframe.x, 0) + + def _set_angular_velocity(self): + self.child_interframe.set_ang_vel(self.parent_interframe, 0) + + def _set_linear_velocity(self): + self.child_point.set_pos(self.parent_point, 0) + self.parent_point.set_vel(self.parent.frame, 0) + self.child_point.set_vel(self.child.frame, 0) + self.child.masscenter.set_vel(self.parent.frame, 0) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py new file mode 100644 index 0000000000000000000000000000000000000000..cae658a621b797d6626c6537c5aa5a0645fc15d5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/jointsmethod.py @@ -0,0 +1,279 @@ +from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod, + RigidBody, Particle) +from sympy.physics.mechanics.method import _Methods +from sympy.core.backend import Matrix + +__all__ = ['JointsMethod'] + + +class JointsMethod(_Methods): + """Method for formulating the equations of motion using a set of interconnected bodies with joints. + + Parameters + ========== + + newtonion : Body or ReferenceFrame + The newtonion(inertial) frame. + *joints : Joint + The joints in the system + + Attributes + ========== + + q, u : iterable + Iterable of the generalized coordinates and speeds + bodies : iterable + Iterable of Body objects in the system. + loads : iterable + Iterable of (Point, vector) or (ReferenceFrame, vector) tuples + describing the forces on the system. + mass_matrix : Matrix, shape(n, n) + The system's mass matrix + forcing : Matrix, shape(n, 1) + The system's forcing vector + mass_matrix_full : Matrix, shape(2*n, 2*n) + The "mass matrix" for the u's and q's + forcing_full : Matrix, shape(2*n, 1) + The "forcing vector" for the u's and q's + method : KanesMethod or Lagrange's method + Method's object. + kdes : iterable + Iterable of kde in they system. + + Examples + ======== + + This is a simple example for a one degree of freedom translational + spring-mass-damper. + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint + >>> from sympy.physics.vector import dynamicsymbols + >>> c, k = symbols('c k') + >>> x, v = dynamicsymbols('x v') + >>> wall = Body('W') + >>> body = Body('B') + >>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v) + >>> wall.apply_force(c*v*wall.x, reaction_body=body) + >>> wall.apply_force(k*x*wall.x, reaction_body=body) + >>> method = JointsMethod(wall, J) + >>> method.form_eoms() + Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]]) + >>> M = method.mass_matrix_full + >>> F = method.forcing_full + >>> rhs = M.LUsolve(F) + >>> rhs + Matrix([ + [ v(t)], + [(-c*v(t) - k*x(t))/B_mass]]) + + Notes + ===== + + ``JointsMethod`` currently only works with systems that do not have any + configuration or motion constraints. + + """ + + def __init__(self, newtonion, *joints): + if isinstance(newtonion, Body): + self.frame = newtonion.frame + else: + self.frame = newtonion + + self._joints = joints + self._bodies = self._generate_bodylist() + self._loads = self._generate_loadlist() + self._q = self._generate_q() + self._u = self._generate_u() + self._kdes = self._generate_kdes() + + self._method = None + + @property + def bodies(self): + """List of bodies in they system.""" + return self._bodies + + @property + def loads(self): + """List of loads on the system.""" + return self._loads + + @property + def q(self): + """List of the generalized coordinates.""" + return self._q + + @property + def u(self): + """List of the generalized speeds.""" + return self._u + + @property + def kdes(self): + """List of the generalized coordinates.""" + return self._kdes + + @property + def forcing_full(self): + """The "forcing vector" for the u's and q's.""" + return self.method.forcing_full + + @property + def mass_matrix_full(self): + """The "mass matrix" for the u's and q's.""" + return self.method.mass_matrix_full + + @property + def mass_matrix(self): + """The system's mass matrix.""" + return self.method.mass_matrix + + @property + def forcing(self): + """The system's forcing vector.""" + return self.method.forcing + + @property + def method(self): + """Object of method used to form equations of systems.""" + return self._method + + def _generate_bodylist(self): + bodies = [] + for joint in self._joints: + if joint.child not in bodies: + bodies.append(joint.child) + if joint.parent not in bodies: + bodies.append(joint.parent) + return bodies + + def _generate_loadlist(self): + load_list = [] + for body in self.bodies: + load_list.extend(body.loads) + return load_list + + def _generate_q(self): + q_ind = [] + for joint in self._joints: + for coordinate in joint.coordinates: + if coordinate in q_ind: + raise ValueError('Coordinates of joints should be unique.') + q_ind.append(coordinate) + return Matrix(q_ind) + + def _generate_u(self): + u_ind = [] + for joint in self._joints: + for speed in joint.speeds: + if speed in u_ind: + raise ValueError('Speeds of joints should be unique.') + u_ind.append(speed) + return Matrix(u_ind) + + def _generate_kdes(self): + kd_ind = Matrix(1, 0, []).T + for joint in self._joints: + kd_ind = kd_ind.col_join(joint.kdes) + return kd_ind + + def _convert_bodies(self): + # Convert `Body` to `Particle` and `RigidBody` + bodylist = [] + for body in self.bodies: + if body.is_rigidbody: + rb = RigidBody(body.name, body.masscenter, body.frame, body.mass, + (body.central_inertia, body.masscenter)) + rb.potential_energy = body.potential_energy + bodylist.append(rb) + else: + part = Particle(body.name, body.masscenter, body.mass) + part.potential_energy = body.potential_energy + bodylist.append(part) + return bodylist + + def form_eoms(self, method=KanesMethod): + """Method to form system's equation of motions. + + Parameters + ========== + + method : Class + Class name of method. + + Returns + ======== + + Matrix + Vector of equations of motions. + + Examples + ======== + + This is a simple example for a one degree of freedom translational + spring-mass-damper. + + >>> from sympy import S, symbols + >>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body + >>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod + >>> q = dynamicsymbols('q') + >>> qd = dynamicsymbols('q', 1) + >>> m, k, b = symbols('m k b') + >>> wall = Body('W') + >>> part = Body('P', mass=m) + >>> part.potential_energy = k * q**2 / S(2) + >>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd) + >>> wall.apply_force(b * qd * wall.x, reaction_body=part) + >>> method = JointsMethod(wall, J) + >>> method.form_eoms(LagrangesMethod) + Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]]) + + We can also solve for the states using the 'rhs' method. + + >>> method.rhs() + Matrix([ + [ Derivative(q(t), t)], + [(-b*Derivative(q(t), t) - k*q(t))/m]]) + + """ + + bodylist = self._convert_bodies() + if issubclass(method, LagrangesMethod): #LagrangesMethod or similar + L = Lagrangian(self.frame, *bodylist) + self._method = method(L, self.q, self.loads, bodylist, self.frame) + else: #KanesMethod or similar + self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes, + forcelist=self.loads, bodies=bodylist) + soln = self.method._form_eoms() + return soln + + def rhs(self, inv_method=None): + """Returns equations that can be solved numerically. + + Parameters + ========== + + inv_method : str + The specific sympy inverse matrix calculation method to use. For a + list of valid methods, see + :meth:`~sympy.matrices.matrices.MatrixBase.inv` + + Returns + ======== + + Matrix + Numerically solvable equations. + + See Also + ======== + + sympy.physics.mechanics.kane.KanesMethod.rhs: + KanesMethod's rhs function. + sympy.physics.mechanics.lagrange.LagrangesMethod.rhs: + LagrangesMethod's rhs function. + + """ + + return self.method.rhs(inv_method=inv_method) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py new file mode 100644 index 0000000000000000000000000000000000000000..33308e2add7670f436dbcb77e3605d6c36b82145 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/kane.py @@ -0,0 +1,741 @@ +from sympy.core.backend import zeros, Matrix, diff, eye +from sympy.core.sorting import default_sort_key +from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, + partial_velocity) +from sympy.physics.mechanics.method import _Methods +from sympy.physics.mechanics.particle import Particle +from sympy.physics.mechanics.rigidbody import RigidBody +from sympy.physics.mechanics.functions import ( + msubs, find_dynamicsymbols, _f_list_parser, _validate_coordinates) +from sympy.physics.mechanics.linearize import Linearizer +from sympy.utilities.iterables import iterable + +__all__ = ['KanesMethod'] + + +class KanesMethod(_Methods): + r"""Kane's method object. + + Explanation + =========== + + This object is used to do the "book-keeping" as you go through and form + equations of motion in the way Kane presents in: + Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill + + The attributes are for equations in the form [M] udot = forcing. + + Attributes + ========== + + q, u : Matrix + Matrices of the generalized coordinates and speeds + bodies : iterable + Iterable of Point and RigidBody objects in the system. + loads : iterable + Iterable of (Point, vector) or (ReferenceFrame, vector) tuples + describing the forces on the system. + auxiliary_eqs : Matrix + If applicable, the set of auxiliary Kane's + equations used to solve for non-contributing + forces. + mass_matrix : Matrix + The system's dynamics mass matrix: [k_d; k_dnh] + forcing : Matrix + The system's dynamics forcing vector: -[f_d; f_dnh] + mass_matrix_kin : Matrix + The "mass matrix" for kinematic differential equations: k_kqdot + forcing_kin : Matrix + The forcing vector for kinematic differential equations: -(k_ku*u + f_k) + mass_matrix_full : Matrix + The "mass matrix" for the u's and q's with dynamics and kinematics + forcing_full : Matrix + The "forcing vector" for the u's and q's with dynamics and kinematics + explicit_kinematics : bool + Boolean whether the mass matrices and forcing vectors should use the + explicit form (default) or implicit form for kinematics. + See the notes for more details. + + Notes + ===== + + The mass matrices and forcing vectors related to kinematic equations + are given in the explicit form by default. In other words, the kinematic + mass matrix is $\mathbf{k_{k\dot{q}}} = \mathbf{I}$. + In order to get the implicit form of those matrices/vectors, you can set the + ``explicit_kinematics`` attribute to ``False``. So $\mathbf{k_{k\dot{q}}}$ is not + necessarily an identity matrix. This can provide more compact equations for + non-simple kinematics (see #22626). + + Examples + ======== + + This is a simple example for a one degree of freedom translational + spring-mass-damper. + + In this example, we first need to do the kinematics. + This involves creating generalized speeds and coordinates and their + derivatives. + Then we create a point and set its velocity in a frame. + + >>> from sympy import symbols + >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame + >>> from sympy.physics.mechanics import Point, Particle, KanesMethod + >>> q, u = dynamicsymbols('q u') + >>> qd, ud = dynamicsymbols('q u', 1) + >>> m, c, k = symbols('m c k') + >>> N = ReferenceFrame('N') + >>> P = Point('P') + >>> P.set_vel(N, u * N.x) + + Next we need to arrange/store information in the way that KanesMethod + requires. The kinematic differential equations need to be stored in a + dict. A list of forces/torques must be constructed, where each entry in + the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the + Vectors represent the Force or Torque. + Next a particle needs to be created, and it needs to have a point and mass + assigned to it. + Finally, a list of all bodies and particles needs to be created. + + >>> kd = [qd - u] + >>> FL = [(P, (-k * q - c * u) * N.x)] + >>> pa = Particle('pa', P, m) + >>> BL = [pa] + + Finally we can generate the equations of motion. + First we create the KanesMethod object and supply an inertial frame, + coordinates, generalized speeds, and the kinematic differential equations. + Additional quantities such as configuration and motion constraints, + dependent coordinates and speeds, and auxiliary speeds are also supplied + here (see the online documentation). + Next we form FR* and FR to complete: Fr + Fr* = 0. + We have the equations of motion at this point. + It makes sense to rearrange them though, so we calculate the mass matrix and + the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is + the mass matrix, udot is a vector of the time derivatives of the + generalized speeds, and forcing is a vector representing "forcing" terms. + + >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) + >>> (fr, frstar) = KM.kanes_equations(BL, FL) + >>> MM = KM.mass_matrix + >>> forcing = KM.forcing + >>> rhs = MM.inv() * forcing + >>> rhs + Matrix([[(-c*u(t) - k*q(t))/m]]) + >>> KM.linearize(A_and_B=True)[0] + Matrix([ + [ 0, 1], + [-k/m, -c/m]]) + + Please look at the documentation pages for more information on how to + perform linearization and how to deal with dependent coordinates & speeds, + and how do deal with bringing non-contributing forces into evidence. + + """ + + def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, + configuration_constraints=None, u_dependent=None, + velocity_constraints=None, acceleration_constraints=None, + u_auxiliary=None, bodies=None, forcelist=None, explicit_kinematics=True): + + """Please read the online documentation. """ + if not q_ind: + q_ind = [dynamicsymbols('dummy_q')] + kd_eqs = [dynamicsymbols('dummy_kd')] + + if not isinstance(frame, ReferenceFrame): + raise TypeError('An inertial ReferenceFrame must be supplied') + self._inertial = frame + + self._fr = None + self._frstar = None + + self._forcelist = forcelist + self._bodylist = bodies + + self.explicit_kinematics = explicit_kinematics + + self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, + u_auxiliary) + _validate_coordinates(self.q, self.u) + self._initialize_kindiffeq_matrices(kd_eqs) + self._initialize_constraint_matrices(configuration_constraints, + velocity_constraints, acceleration_constraints) + + def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): + """Initialize the coordinate and speed vectors.""" + + none_handler = lambda x: Matrix(x) if x else Matrix() + + # Initialize generalized coordinates + q_dep = none_handler(q_dep) + if not iterable(q_ind): + raise TypeError('Generalized coordinates must be an iterable.') + if not iterable(q_dep): + raise TypeError('Dependent coordinates must be an iterable.') + q_ind = Matrix(q_ind) + self._qdep = q_dep + self._q = Matrix([q_ind, q_dep]) + self._qdot = self.q.diff(dynamicsymbols._t) + + # Initialize generalized speeds + u_dep = none_handler(u_dep) + if not iterable(u_ind): + raise TypeError('Generalized speeds must be an iterable.') + if not iterable(u_dep): + raise TypeError('Dependent speeds must be an iterable.') + u_ind = Matrix(u_ind) + self._udep = u_dep + self._u = Matrix([u_ind, u_dep]) + self._udot = self.u.diff(dynamicsymbols._t) + self._uaux = none_handler(u_aux) + + def _initialize_constraint_matrices(self, config, vel, acc): + """Initializes constraint matrices.""" + + # Define vector dimensions + o = len(self.u) + m = len(self._udep) + p = o - m + none_handler = lambda x: Matrix(x) if x else Matrix() + + # Initialize configuration constraints + config = none_handler(config) + if len(self._qdep) != len(config): + raise ValueError('There must be an equal number of dependent ' + 'coordinates and configuration constraints.') + self._f_h = none_handler(config) + + # Initialize velocity and acceleration constraints + vel = none_handler(vel) + acc = none_handler(acc) + if len(vel) != m: + raise ValueError('There must be an equal number of dependent ' + 'speeds and velocity constraints.') + if acc and (len(acc) != m): + raise ValueError('There must be an equal number of dependent ' + 'speeds and acceleration constraints.') + if vel: + u_zero = {i: 0 for i in self.u} + udot_zero = {i: 0 for i in self._udot} + + # When calling kanes_equations, another class instance will be + # created if auxiliary u's are present. In this case, the + # computation of kinetic differential equation matrices will be + # skipped as this was computed during the original KanesMethod + # object, and the qd_u_map will not be available. + if self._qdot_u_map is not None: + vel = msubs(vel, self._qdot_u_map) + + self._f_nh = msubs(vel, u_zero) + self._k_nh = (vel - self._f_nh).jacobian(self.u) + # If no acceleration constraints given, calculate them. + if not acc: + _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + + self._f_nh.diff(dynamicsymbols._t)) + if self._qdot_u_map is not None: + _f_dnh = msubs(_f_dnh, self._qdot_u_map) + self._f_dnh = _f_dnh + self._k_dnh = self._k_nh + else: + if self._qdot_u_map is not None: + acc = msubs(acc, self._qdot_u_map) + self._f_dnh = msubs(acc, udot_zero) + self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) + + # Form of non-holonomic constraints is B*u + C = 0. + # We partition B into independent and dependent columns: + # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds + # to independent speeds as: udep = Ars*uind, neglecting the C term. + B_ind = self._k_nh[:, :p] + B_dep = self._k_nh[:, p:o] + self._Ars = -B_dep.LUsolve(B_ind) + else: + self._f_nh = Matrix() + self._k_nh = Matrix() + self._f_dnh = Matrix() + self._k_dnh = Matrix() + self._Ars = Matrix() + + def _initialize_kindiffeq_matrices(self, kdeqs): + """Initialize the kinematic differential equation matrices. + + Parameters + ========== + kdeqs : sequence of sympy expressions + Kinematic differential equations in the form of f(u,q',q,t) where + f() = 0. The equations have to be linear in the generalized + coordinates and generalized speeds. + + """ + + if kdeqs: + if len(self.q) != len(kdeqs): + raise ValueError('There must be an equal number of kinematic ' + 'differential equations and coordinates.') + + u = self.u + qdot = self._qdot + + kdeqs = Matrix(kdeqs) + + u_zero = {ui: 0 for ui in u} + uaux_zero = {uai: 0 for uai in self._uaux} + qdot_zero = {qdi: 0 for qdi in qdot} + + # Extract the linear coefficient matrices as per the following + # equation: + # + # k_ku(q,t)*u(t) + k_kqdot(q,t)*q'(t) + f_k(q,t) = 0 + # + k_ku = kdeqs.jacobian(u) + k_kqdot = kdeqs.jacobian(qdot) + f_k = kdeqs.xreplace(u_zero).xreplace(qdot_zero) + + # The kinematic differential equations should be linear in both q' + # and u, so check for u and q' in the components. + dy_syms = find_dynamicsymbols(k_ku.row_join(k_kqdot).row_join(f_k)) + nonlin_vars = [vari for vari in u[:] + qdot[:] if vari in dy_syms] + if nonlin_vars: + msg = ('The provided kinematic differential equations are ' + 'nonlinear in {}. They must be linear in the ' + 'generalized speeds and derivatives of the generalized ' + 'coordinates.') + raise ValueError(msg.format(nonlin_vars)) + + self._f_k_implicit = f_k.xreplace(uaux_zero) + self._k_ku_implicit = k_ku.xreplace(uaux_zero) + self._k_kqdot_implicit = k_kqdot + + # Solve for q'(t) such that the coefficient matrices are now in + # this form: + # + # k_kqdot^-1*k_ku*u(t) + I*q'(t) + k_kqdot^-1*f_k = 0 + # + # NOTE : Solving the kinematic differential equations here is not + # necessary and prevents the equations from being provided in fully + # implicit form. + f_k_explicit = k_kqdot.LUsolve(f_k) + k_ku_explicit = k_kqdot.LUsolve(k_ku) + self._qdot_u_map = dict(zip(qdot, -(k_ku_explicit*u + f_k_explicit))) + + self._f_k = f_k_explicit.xreplace(uaux_zero) + self._k_ku = k_ku_explicit.xreplace(uaux_zero) + self._k_kqdot = eye(len(qdot)) + + else: + self._qdot_u_map = None + self._f_k_implicit = self._f_k = Matrix() + self._k_ku_implicit = self._k_ku = Matrix() + self._k_kqdot_implicit = self._k_kqdot = Matrix() + + def _form_fr(self, fl): + """Form the generalized active force.""" + if fl is not None and (len(fl) == 0 or not iterable(fl)): + raise ValueError('Force pairs must be supplied in an ' + 'non-empty iterable or None.') + + N = self._inertial + # pull out relevant velocities for constructing partial velocities + vel_list, f_list = _f_list_parser(fl, N) + vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] + f_list = [msubs(i, self._qdot_u_map) for i in f_list] + + # Fill Fr with dot product of partial velocities and forces + o = len(self.u) + b = len(f_list) + FR = zeros(o, 1) + partials = partial_velocity(vel_list, self.u, N) + for i in range(o): + FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) + + # In case there are dependent speeds + if self._udep: + p = o - len(self._udep) + FRtilde = FR[:p, 0] + FRold = FR[p:o, 0] + FRtilde += self._Ars.T * FRold + FR = FRtilde + + self._forcelist = fl + self._fr = FR + return FR + + def _form_frstar(self, bl): + """Form the generalized inertia force.""" + + if not iterable(bl): + raise TypeError('Bodies must be supplied in an iterable.') + + t = dynamicsymbols._t + N = self._inertial + # Dicts setting things to zero + udot_zero = {i: 0 for i in self._udot} + uaux_zero = {i: 0 for i in self._uaux} + uauxdot = [diff(i, t) for i in self._uaux] + uauxdot_zero = {i: 0 for i in uauxdot} + # Dictionary of q' and q'' to u and u' + q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in + self._qdot_u_map.items()} + q_ddot_u_map.update(self._qdot_u_map) + + # Fill up the list of partials: format is a list with num elements + # equal to number of entries in body list. Each of these elements is a + # list - either of length 1 for the translational components of + # particles or of length 2 for the translational and rotational + # components of rigid bodies. The inner most list is the list of + # partial velocities. + def get_partial_velocity(body): + if isinstance(body, RigidBody): + vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] + elif isinstance(body, Particle): + vlist = [body.point.vel(N),] + else: + raise TypeError('The body list may only contain either ' + 'RigidBody or Particle as list elements.') + v = [msubs(vel, self._qdot_u_map) for vel in vlist] + return partial_velocity(v, self.u, N) + partials = [get_partial_velocity(body) for body in bl] + + # Compute fr_star in two components: + # fr_star = -(MM*u' + nonMM) + o = len(self.u) + MM = zeros(o, o) + nonMM = zeros(o, 1) + zero_uaux = lambda expr: msubs(expr, uaux_zero) + zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) + for i, body in enumerate(bl): + if isinstance(body, RigidBody): + M = zero_uaux(body.mass) + I = zero_uaux(body.central_inertia) + vel = zero_uaux(body.masscenter.vel(N)) + omega = zero_uaux(body.frame.ang_vel_in(N)) + acc = zero_udot_uaux(body.masscenter.acc(N)) + inertial_force = (M.diff(t) * vel + M * acc) + inertial_torque = zero_uaux((I.dt(body.frame) & omega) + + msubs(I & body.frame.ang_acc_in(N), udot_zero) + + (omega ^ (I & omega))) + for j in range(o): + tmp_vel = zero_uaux(partials[i][0][j]) + tmp_ang = zero_uaux(I & partials[i][1][j]) + for k in range(o): + # translational + MM[j, k] += M * (tmp_vel & partials[i][0][k]) + # rotational + MM[j, k] += (tmp_ang & partials[i][1][k]) + nonMM[j] += inertial_force & partials[i][0][j] + nonMM[j] += inertial_torque & partials[i][1][j] + else: + M = zero_uaux(body.mass) + vel = zero_uaux(body.point.vel(N)) + acc = zero_udot_uaux(body.point.acc(N)) + inertial_force = (M.diff(t) * vel + M * acc) + for j in range(o): + temp = zero_uaux(partials[i][0][j]) + for k in range(o): + MM[j, k] += M * (temp & partials[i][0][k]) + nonMM[j] += inertial_force & partials[i][0][j] + # Compose fr_star out of MM and nonMM + MM = zero_uaux(msubs(MM, q_ddot_u_map)) + nonMM = msubs(msubs(nonMM, q_ddot_u_map), + udot_zero, uauxdot_zero, uaux_zero) + fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) + + # If there are dependent speeds, we need to find fr_star_tilde + if self._udep: + p = o - len(self._udep) + fr_star_ind = fr_star[:p, 0] + fr_star_dep = fr_star[p:o, 0] + fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) + # Apply the same to MM + MMi = MM[:p, :] + MMd = MM[p:o, :] + MM = MMi + (self._Ars.T * MMd) + + self._bodylist = bl + self._frstar = fr_star + self._k_d = MM + self._f_d = -msubs(self._fr + self._frstar, udot_zero) + return fr_star + + def to_linearizer(self): + """Returns an instance of the Linearizer class, initiated from the + data in the KanesMethod class. This may be more desirable than using + the linearize class method, as the Linearizer object will allow more + efficient recalculation (i.e. about varying operating points).""" + + if (self._fr is None) or (self._frstar is None): + raise ValueError('Need to compute Fr, Fr* first.') + + # Get required equation components. The Kane's method class breaks + # these into pieces. Need to reassemble + f_c = self._f_h + if self._f_nh and self._k_nh: + f_v = self._f_nh + self._k_nh*Matrix(self.u) + else: + f_v = Matrix() + if self._f_dnh and self._k_dnh: + f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) + else: + f_a = Matrix() + # Dicts to sub to zero, for splitting up expressions + u_zero = {i: 0 for i in self.u} + ud_zero = {i: 0 for i in self._udot} + qd_zero = {i: 0 for i in self._qdot} + qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])} + # Break the kinematic differential eqs apart into f_0 and f_1 + f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) + f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) + # Break the dynamic differential eqs into f_2 and f_3 + f_2 = msubs(self._frstar, qd_u_zero) + f_3 = msubs(self._frstar, ud_zero) + self._fr + f_4 = zeros(len(f_2), 1) + + # Get the required vector components + q = self.q + u = self.u + if self._qdep: + q_i = q[:-len(self._qdep)] + else: + q_i = q + q_d = self._qdep + if self._udep: + u_i = u[:-len(self._udep)] + else: + u_i = u + u_d = self._udep + + # Form dictionary to set auxiliary speeds & their derivatives to 0. + uaux = self._uaux + uauxdot = uaux.diff(dynamicsymbols._t) + uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])} + + # Checking for dynamic symbols outside the dynamic differential + # equations; throws error if there is. + sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) + if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, + self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): + raise ValueError('Cannot have dynamicsymbols outside dynamic \ + forcing vector.') + + # Find all other dynamic symbols, forming the forcing vector r. + # Sort r to make it canonical. + r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) + r.sort(key=default_sort_key) + + # Check for any derivatives of variables in r that are also found in r. + for i in r: + if diff(i, dynamicsymbols._t) in r: + raise ValueError('Cannot have derivatives of specified \ + quantities when linearizing forcing terms.') + return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, + q_d, u_i, u_d, r) + + # TODO : Remove `new_method` after 1.1 has been released. + def linearize(self, *, new_method=None, **kwargs): + """ Linearize the equations of motion about a symbolic operating point. + + Explanation + =========== + + If kwarg A_and_B is False (default), returns M, A, B, r for the + linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. + + If kwarg A_and_B is True, returns A, B, r for the linearized form + dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is + computationally intensive if there are many symbolic parameters. For + this reason, it may be more desirable to use the default A_and_B=False, + returning M, A, and B. Values may then be substituted in to these + matrices, and the state space form found as + A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. + + In both cases, r is found as all dynamicsymbols in the equations of + motion that are not part of q, u, q', or u'. They are sorted in + canonical form. + + The operating points may be also entered using the ``op_point`` kwarg. + This takes a dictionary of {symbol: value}, or a an iterable of such + dictionaries. The values may be numeric or symbolic. The more values + you can specify beforehand, the faster this computation will run. + + For more documentation, please see the ``Linearizer`` class.""" + linearizer = self.to_linearizer() + result = linearizer.linearize(**kwargs) + return result + (linearizer.r,) + + def kanes_equations(self, bodies=None, loads=None): + """ Method to form Kane's equations, Fr + Fr* = 0. + + Explanation + =========== + + Returns (Fr, Fr*). In the case where auxiliary generalized speeds are + present (say, s auxiliary speeds, o generalized speeds, and m motion + constraints) the length of the returned vectors will be o - m + s in + length. The first o - m equations will be the constrained Kane's + equations, then the s auxiliary Kane's equations. These auxiliary + equations can be accessed with the auxiliary_eqs property. + + Parameters + ========== + + bodies : iterable + An iterable of all RigidBody's and Particle's in the system. + A system must have at least one body. + loads : iterable + Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) + tuples which represent the force at a point or torque on a frame. + Must be either a non-empty iterable of tuples or None which corresponds + to a system with no constraints. + """ + if bodies is None: + bodies = self.bodies + if loads is None and self._forcelist is not None: + loads = self._forcelist + if loads == []: + loads = None + if not self._k_kqdot: + raise AttributeError('Create an instance of KanesMethod with ' + 'kinematic differential equations to use this method.') + fr = self._form_fr(loads) + frstar = self._form_frstar(bodies) + if self._uaux: + if not self._udep: + km = KanesMethod(self._inertial, self.q, self._uaux, + u_auxiliary=self._uaux) + else: + km = KanesMethod(self._inertial, self.q, self._uaux, + u_auxiliary=self._uaux, u_dependent=self._udep, + velocity_constraints=(self._k_nh * self.u + + self._f_nh), + acceleration_constraints=(self._k_dnh * self._udot + + self._f_dnh) + ) + km._qdot_u_map = self._qdot_u_map + self._km = km + fraux = km._form_fr(loads) + frstaraux = km._form_frstar(bodies) + self._aux_eq = fraux + frstaraux + self._fr = fr.col_join(fraux) + self._frstar = frstar.col_join(frstaraux) + return (self._fr, self._frstar) + + def _form_eoms(self): + fr, frstar = self.kanes_equations(self.bodylist, self.forcelist) + return fr + frstar + + def rhs(self, inv_method=None): + """Returns the system's equations of motion in first order form. The + output is the right hand side of:: + + x' = |q'| =: f(q, u, r, p, t) + |u'| + + The right hand side is what is needed by most numerical ODE + integrators. + + Parameters + ========== + + inv_method : str + The specific sympy inverse matrix calculation method to use. For a + list of valid methods, see + :meth:`~sympy.matrices.matrices.MatrixBase.inv` + + """ + rhs = zeros(len(self.q) + len(self.u), 1) + kdes = self.kindiffdict() + for i, q_i in enumerate(self.q): + rhs[i] = kdes[q_i.diff()] + + if inv_method is None: + rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) + else: + rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, + try_block_diag=True) * + self.forcing) + + return rhs + + def kindiffdict(self): + """Returns a dictionary mapping q' to u.""" + if not self._qdot_u_map: + raise AttributeError('Create an instance of KanesMethod with ' + 'kinematic differential equations to use this method.') + return self._qdot_u_map + + @property + def auxiliary_eqs(self): + """A matrix containing the auxiliary equations.""" + if not self._fr or not self._frstar: + raise ValueError('Need to compute Fr, Fr* first.') + if not self._uaux: + raise ValueError('No auxiliary speeds have been declared.') + return self._aux_eq + + @property + def mass_matrix_kin(self): + r"""The kinematic "mass matrix" $\mathbf{k_{k\dot{q}}}$ of the system.""" + return self._k_kqdot if self.explicit_kinematics else self._k_kqdot_implicit + + @property + def forcing_kin(self): + """The kinematic "forcing vector" of the system.""" + if self.explicit_kinematics: + return -(self._k_ku * Matrix(self.u) + self._f_k) + else: + return -(self._k_ku_implicit * Matrix(self.u) + self._f_k_implicit) + + @property + def mass_matrix(self): + """The mass matrix of the system.""" + if not self._fr or not self._frstar: + raise ValueError('Need to compute Fr, Fr* first.') + return Matrix([self._k_d, self._k_dnh]) + + @property + def forcing(self): + """The forcing vector of the system.""" + if not self._fr or not self._frstar: + raise ValueError('Need to compute Fr, Fr* first.') + return -Matrix([self._f_d, self._f_dnh]) + + @property + def mass_matrix_full(self): + """The mass matrix of the system, augmented by the kinematic + differential equations in explicit or implicit form.""" + if not self._fr or not self._frstar: + raise ValueError('Need to compute Fr, Fr* first.') + o, n = len(self.u), len(self.q) + return (self.mass_matrix_kin.row_join(zeros(n, o))).col_join( + zeros(o, n).row_join(self.mass_matrix)) + + @property + def forcing_full(self): + """The forcing vector of the system, augmented by the kinematic + differential equations in explicit or implicit form.""" + return Matrix([self.forcing_kin, self.forcing]) + + @property + def q(self): + return self._q + + @property + def u(self): + return self._u + + @property + def bodylist(self): + return self._bodylist + + @property + def forcelist(self): + return self._forcelist + + @property + def bodies(self): + return self._bodylist + + @property + def loads(self): + return self._forcelist diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py new file mode 100644 index 0000000000000000000000000000000000000000..10a111ee2e869ceb1d9255a99c91eb7a9d8f2859 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py @@ -0,0 +1,477 @@ +from sympy.core.backend import diff, zeros, Matrix, eye, sympify +from sympy.core.sorting import default_sort_key +from sympy.physics.vector import dynamicsymbols, ReferenceFrame +from sympy.physics.mechanics.method import _Methods +from sympy.physics.mechanics.functions import ( + find_dynamicsymbols, msubs, _f_list_parser, _validate_coordinates) +from sympy.physics.mechanics.linearize import Linearizer +from sympy.utilities.iterables import iterable + +__all__ = ['LagrangesMethod'] + + +class LagrangesMethod(_Methods): + """Lagrange's method object. + + Explanation + =========== + + This object generates the equations of motion in a two step procedure. The + first step involves the initialization of LagrangesMethod by supplying the + Lagrangian and the generalized coordinates, at the bare minimum. If there + are any constraint equations, they can be supplied as keyword arguments. + The Lagrange multipliers are automatically generated and are equal in + number to the constraint equations. Similarly any non-conservative forces + can be supplied in an iterable (as described below and also shown in the + example) along with a ReferenceFrame. This is also discussed further in the + __init__ method. + + Attributes + ========== + + q, u : Matrix + Matrices of the generalized coordinates and speeds + loads : iterable + Iterable of (Point, vector) or (ReferenceFrame, vector) tuples + describing the forces on the system. + bodies : iterable + Iterable containing the rigid bodies and particles of the system. + mass_matrix : Matrix + The system's mass matrix + forcing : Matrix + The system's forcing vector + mass_matrix_full : Matrix + The "mass matrix" for the qdot's, qdoubledot's, and the + lagrange multipliers (lam) + forcing_full : Matrix + The forcing vector for the qdot's, qdoubledot's and + lagrange multipliers (lam) + + Examples + ======== + + This is a simple example for a one degree of freedom translational + spring-mass-damper. + + In this example, we first need to do the kinematics. + This involves creating generalized coordinates and their derivatives. + Then we create a point and set its velocity in a frame. + + >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian + >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point + >>> from sympy.physics.mechanics import dynamicsymbols + >>> from sympy import symbols + >>> q = dynamicsymbols('q') + >>> qd = dynamicsymbols('q', 1) + >>> m, k, b = symbols('m k b') + >>> N = ReferenceFrame('N') + >>> P = Point('P') + >>> P.set_vel(N, qd * N.x) + + We need to then prepare the information as required by LagrangesMethod to + generate equations of motion. + First we create the Particle, which has a point attached to it. + Following this the lagrangian is created from the kinetic and potential + energies. + Then, an iterable of nonconservative forces/torques must be constructed, + where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, + with the Vectors representing the nonconservative forces or torques. + + >>> Pa = Particle('Pa', P, m) + >>> Pa.potential_energy = k * q**2 / 2.0 + >>> L = Lagrangian(N, Pa) + >>> fl = [(P, -b * qd * N.x)] + + Finally we can generate the equations of motion. + First we create the LagrangesMethod object. To do this one must supply + the Lagrangian, and the generalized coordinates. The constraint equations, + the forcelist, and the inertial frame may also be provided, if relevant. + Next we generate Lagrange's equations of motion, such that: + Lagrange's equations of motion = 0. + We have the equations of motion at this point. + + >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) + >>> print(l.form_lagranges_equations()) + Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]]) + + We can also solve for the states using the 'rhs' method. + + >>> print(l.rhs()) + Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) + + Please refer to the docstrings on each method for more details. + """ + + def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, + hol_coneqs=None, nonhol_coneqs=None): + """Supply the following for the initialization of LagrangesMethod. + + Lagrangian : Sympifyable + + qs : array_like + The generalized coordinates + + hol_coneqs : array_like, optional + The holonomic constraint equations + + nonhol_coneqs : array_like, optional + The nonholonomic constraint equations + + forcelist : iterable, optional + Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) + tuples which represent the force at a point or torque on a frame. + This feature is primarily to account for the nonconservative forces + and/or moments. + + bodies : iterable, optional + Takes an iterable containing the rigid bodies and particles of the + system. + + frame : ReferenceFrame, optional + Supply the inertial frame. This is used to determine the + generalized forces due to non-conservative forces. + """ + + self._L = Matrix([sympify(Lagrangian)]) + self.eom = None + self._m_cd = Matrix() # Mass Matrix of differentiated coneqs + self._m_d = Matrix() # Mass Matrix of dynamic equations + self._f_cd = Matrix() # Forcing part of the diff coneqs + self._f_d = Matrix() # Forcing part of the dynamic equations + self.lam_coeffs = Matrix() # The coeffecients of the multipliers + + forcelist = forcelist if forcelist else [] + if not iterable(forcelist): + raise TypeError('Force pairs must be supplied in an iterable.') + self._forcelist = forcelist + if frame and not isinstance(frame, ReferenceFrame): + raise TypeError('frame must be a valid ReferenceFrame') + self._bodies = bodies + self.inertial = frame + + self.lam_vec = Matrix() + + self._term1 = Matrix() + self._term2 = Matrix() + self._term3 = Matrix() + self._term4 = Matrix() + + # Creating the qs, qdots and qdoubledots + if not iterable(qs): + raise TypeError('Generalized coordinates must be an iterable') + self._q = Matrix(qs) + self._qdots = self.q.diff(dynamicsymbols._t) + self._qdoubledots = self._qdots.diff(dynamicsymbols._t) + _validate_coordinates(self.q) + + mat_build = lambda x: Matrix(x) if x else Matrix() + hol_coneqs = mat_build(hol_coneqs) + nonhol_coneqs = mat_build(nonhol_coneqs) + self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), + nonhol_coneqs]) + self._hol_coneqs = hol_coneqs + + def form_lagranges_equations(self): + """Method to form Lagrange's equations of motion. + + Returns a vector of equations of motion using Lagrange's equations of + the second kind. + """ + + qds = self._qdots + qdd_zero = {i: 0 for i in self._qdoubledots} + n = len(self.q) + + # Internally we represent the EOM as four terms: + # EOM = term1 - term2 - term3 - term4 = 0 + + # First term + self._term1 = self._L.jacobian(qds) + self._term1 = self._term1.diff(dynamicsymbols._t).T + + # Second term + self._term2 = self._L.jacobian(self.q).T + + # Third term + if self.coneqs: + coneqs = self.coneqs + m = len(coneqs) + # Creating the multipliers + self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) + self.lam_coeffs = -coneqs.jacobian(qds) + self._term3 = self.lam_coeffs.T * self.lam_vec + # Extracting the coeffecients of the qdds from the diff coneqs + diffconeqs = coneqs.diff(dynamicsymbols._t) + self._m_cd = diffconeqs.jacobian(self._qdoubledots) + # The remaining terms i.e. the 'forcing' terms in diff coneqs + self._f_cd = -diffconeqs.subs(qdd_zero) + else: + self._term3 = zeros(n, 1) + + # Fourth term + if self.forcelist: + N = self.inertial + self._term4 = zeros(n, 1) + for i, qd in enumerate(qds): + flist = zip(*_f_list_parser(self.forcelist, N)) + self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) + else: + self._term4 = zeros(n, 1) + + # Form the dynamic mass and forcing matrices + without_lam = self._term1 - self._term2 - self._term4 + self._m_d = without_lam.jacobian(self._qdoubledots) + self._f_d = -without_lam.subs(qdd_zero) + + # Form the EOM + self.eom = without_lam - self._term3 + return self.eom + + def _form_eoms(self): + return self.form_lagranges_equations() + + @property + def mass_matrix(self): + """Returns the mass matrix, which is augmented by the Lagrange + multipliers, if necessary. + + Explanation + =========== + + If the system is described by 'n' generalized coordinates and there are + no constraint equations then an n X n matrix is returned. + + If there are 'n' generalized coordinates and 'm' constraint equations + have been supplied during initialization then an n X (n+m) matrix is + returned. The (n + m - 1)th and (n + m)th columns contain the + coefficients of the Lagrange multipliers. + """ + + if self.eom is None: + raise ValueError('Need to compute the equations of motion first') + if self.coneqs: + return (self._m_d).row_join(self.lam_coeffs.T) + else: + return self._m_d + + @property + def mass_matrix_full(self): + """Augments the coefficients of qdots to the mass_matrix.""" + + if self.eom is None: + raise ValueError('Need to compute the equations of motion first') + n = len(self.q) + m = len(self.coneqs) + row1 = eye(n).row_join(zeros(n, n + m)) + row2 = zeros(n, n).row_join(self.mass_matrix) + if self.coneqs: + row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) + return row1.col_join(row2).col_join(row3) + else: + return row1.col_join(row2) + + @property + def forcing(self): + """Returns the forcing vector from 'lagranges_equations' method.""" + + if self.eom is None: + raise ValueError('Need to compute the equations of motion first') + return self._f_d + + @property + def forcing_full(self): + """Augments qdots to the forcing vector above.""" + + if self.eom is None: + raise ValueError('Need to compute the equations of motion first') + if self.coneqs: + return self._qdots.col_join(self.forcing).col_join(self._f_cd) + else: + return self._qdots.col_join(self.forcing) + + def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): + """Returns an instance of the Linearizer class, initiated from the + data in the LagrangesMethod class. This may be more desirable than using + the linearize class method, as the Linearizer object will allow more + efficient recalculation (i.e. about varying operating points). + + Parameters + ========== + + q_ind, qd_ind : array_like, optional + The independent generalized coordinates and speeds. + q_dep, qd_dep : array_like, optional + The dependent generalized coordinates and speeds. + """ + + # Compose vectors + t = dynamicsymbols._t + q = self.q + u = self._qdots + ud = u.diff(t) + # Get vector of lagrange multipliers + lams = self.lam_vec + + mat_build = lambda x: Matrix(x) if x else Matrix() + q_i = mat_build(q_ind) + q_d = mat_build(q_dep) + u_i = mat_build(qd_ind) + u_d = mat_build(qd_dep) + + # Compose general form equations + f_c = self._hol_coneqs + f_v = self.coneqs + f_a = f_v.diff(t) + f_0 = u + f_1 = -u + f_2 = self._term1 + f_3 = -(self._term2 + self._term4) + f_4 = -self._term3 + + # Check that there are an appropriate number of independent and + # dependent coordinates + if len(q_d) != len(f_c) or len(u_d) != len(f_v): + raise ValueError(("Must supply {:} dependent coordinates, and " + + "{:} dependent speeds").format(len(f_c), len(f_v))) + if set(Matrix([q_i, q_d])) != set(q): + raise ValueError("Must partition q into q_ind and q_dep, with " + + "no extra or missing symbols.") + if set(Matrix([u_i, u_d])) != set(u): + raise ValueError("Must partition qd into qd_ind and qd_dep, " + + "with no extra or missing symbols.") + + # Find all other dynamic symbols, forming the forcing vector r. + # Sort r to make it canonical. + insyms = set(Matrix([q, u, ud, lams])) + r = list(find_dynamicsymbols(f_3, insyms)) + r.sort(key=default_sort_key) + # Check for any derivatives of variables in r that are also found in r. + for i in r: + if diff(i, dynamicsymbols._t) in r: + raise ValueError('Cannot have derivatives of specified \ + quantities when linearizing forcing terms.') + + return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, + q_d, u_i, u_d, r, lams) + + def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, + **kwargs): + """Linearize the equations of motion about a symbolic operating point. + + Explanation + =========== + + If kwarg A_and_B is False (default), returns M, A, B, r for the + linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. + + If kwarg A_and_B is True, returns A, B, r for the linearized form + dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is + computationally intensive if there are many symbolic parameters. For + this reason, it may be more desirable to use the default A_and_B=False, + returning M, A, and B. Values may then be substituted in to these + matrices, and the state space form found as + A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. + + In both cases, r is found as all dynamicsymbols in the equations of + motion that are not part of q, u, q', or u'. They are sorted in + canonical form. + + The operating points may be also entered using the ``op_point`` kwarg. + This takes a dictionary of {symbol: value}, or a an iterable of such + dictionaries. The values may be numeric or symbolic. The more values + you can specify beforehand, the faster this computation will run. + + For more documentation, please see the ``Linearizer`` class.""" + + linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) + result = linearizer.linearize(**kwargs) + return result + (linearizer.r,) + + def solve_multipliers(self, op_point=None, sol_type='dict'): + """Solves for the values of the lagrange multipliers symbolically at + the specified operating point. + + Parameters + ========== + + op_point : dict or iterable of dicts, optional + Point at which to solve at. The operating point is specified as + a dictionary or iterable of dictionaries of {symbol: value}. The + value may be numeric or symbolic itself. + + sol_type : str, optional + Solution return type. Valid options are: + - 'dict': A dict of {symbol : value} (default) + - 'Matrix': An ordered column matrix of the solution + """ + + # Determine number of multipliers + k = len(self.lam_vec) + if k == 0: + raise ValueError("System has no lagrange multipliers to solve for.") + # Compose dict of operating conditions + if isinstance(op_point, dict): + op_point_dict = op_point + elif iterable(op_point): + op_point_dict = {} + for op in op_point: + op_point_dict.update(op) + elif op_point is None: + op_point_dict = {} + else: + raise TypeError("op_point must be either a dictionary or an " + "iterable of dictionaries.") + # Compose the system to be solved + mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join( + zeros(k, k))) + force_matrix = self.forcing.col_join(self._f_cd) + # Sub in the operating point + mass_matrix = msubs(mass_matrix, op_point_dict) + force_matrix = msubs(force_matrix, op_point_dict) + # Solve for the multipliers + sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] + if sol_type == 'dict': + return dict(zip(self.lam_vec, sol_list)) + elif sol_type == 'Matrix': + return Matrix(sol_list) + else: + raise ValueError("Unknown sol_type {:}.".format(sol_type)) + + def rhs(self, inv_method=None, **kwargs): + """Returns equations that can be solved numerically. + + Parameters + ========== + + inv_method : str + The specific sympy inverse matrix calculation method to use. For a + list of valid methods, see + :meth:`~sympy.matrices.matrices.MatrixBase.inv` + """ + + if inv_method is None: + self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) + else: + self._rhs = (self.mass_matrix_full.inv(inv_method, + try_block_diag=True) * self.forcing_full) + return self._rhs + + @property + def q(self): + return self._q + + @property + def u(self): + return self._qdots + + @property + def bodies(self): + return self._bodies + + @property + def forcelist(self): + return self._forcelist + + @property + def loads(self): + return self._forcelist diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1dad2e8b3cab50a3f807ff58c72ae67cc13ae7 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/linearize.py @@ -0,0 +1,443 @@ +__all__ = ['Linearizer'] + +from sympy.core.backend import Matrix, eye, zeros +from sympy.core.symbol import Dummy +from sympy.utilities.iterables import flatten +from sympy.physics.vector import dynamicsymbols +from sympy.physics.mechanics.functions import msubs + +from collections import namedtuple +from collections.abc import Iterable + +class Linearizer: + """This object holds the general model form for a dynamic system. + This model is used for computing the linearized form of the system, + while properly dealing with constraints leading to dependent + coordinates and speeds. + + Attributes + ========== + + f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix + Matrices holding the general system form. + q, u, r : Matrix + Matrices holding the generalized coordinates, speeds, and + input vectors. + q_i, u_i : Matrix + Matrices of the independent generalized coordinates and speeds. + q_d, u_d : Matrix + Matrices of the dependent generalized coordinates and speeds. + perm_mat : Matrix + Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T + """ + + def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, + q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None): + """ + Parameters + ========== + + f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like + System of equations holding the general system form. + Supply empty array or Matrix if the parameter + does not exist. + q : array_like + The generalized coordinates. + u : array_like + The generalized speeds + q_i, u_i : array_like, optional + The independent generalized coordinates and speeds. + q_d, u_d : array_like, optional + The dependent generalized coordinates and speeds. + r : array_like, optional + The input variables. + lams : array_like, optional + The lagrange multipliers + """ + + # Generalized equation form + self.f_0 = Matrix(f_0) + self.f_1 = Matrix(f_1) + self.f_2 = Matrix(f_2) + self.f_3 = Matrix(f_3) + self.f_4 = Matrix(f_4) + self.f_c = Matrix(f_c) + self.f_v = Matrix(f_v) + self.f_a = Matrix(f_a) + + # Generalized equation variables + self.q = Matrix(q) + self.u = Matrix(u) + none_handler = lambda x: Matrix(x) if x else Matrix() + self.q_i = none_handler(q_i) + self.q_d = none_handler(q_d) + self.u_i = none_handler(u_i) + self.u_d = none_handler(u_d) + self.r = none_handler(r) + self.lams = none_handler(lams) + + # Derivatives of generalized equation variables + self._qd = self.q.diff(dynamicsymbols._t) + self._ud = self.u.diff(dynamicsymbols._t) + # If the user doesn't actually use generalized variables, and the + # qd and u vectors have any intersecting variables, this can cause + # problems. We'll fix this with some hackery, and Dummy variables + dup_vars = set(self._qd).intersection(self.u) + self._qd_dup = Matrix([var if var not in dup_vars else Dummy() + for var in self._qd]) + + # Derive dimesion terms + l = len(self.f_c) + m = len(self.f_v) + n = len(self.q) + o = len(self.u) + s = len(self.r) + k = len(self.lams) + dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k']) + self._dims = dims(l, m, n, o, s, k) + + self._Pq = None + self._Pqi = None + self._Pqd = None + self._Pu = None + self._Pui = None + self._Pud = None + self._C_0 = None + self._C_1 = None + self._C_2 = None + self.perm_mat = None + + self._setup_done = False + + def _setup(self): + # Calculations here only need to be run once. They are moved out of + # the __init__ method to increase the speed of Linearizer creation. + self._form_permutation_matrices() + self._form_block_matrices() + self._form_coefficient_matrices() + self._setup_done = True + + def _form_permutation_matrices(self): + """Form the permutation matrices Pq and Pu.""" + + # Extract dimension variables + l, m, n, o, s, k = self._dims + # Compute permutation matrices + if n != 0: + self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d])) + if l > 0: + self._Pqi = self._Pq[:, :-l] + self._Pqd = self._Pq[:, -l:] + else: + self._Pqi = self._Pq + self._Pqd = Matrix() + if o != 0: + self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d])) + if m > 0: + self._Pui = self._Pu[:, :-m] + self._Pud = self._Pu[:, -m:] + else: + self._Pui = self._Pu + self._Pud = Matrix() + # Compute combination permutation matrix for computing A and B + P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)]) + P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)]) + if P_col1: + if P_col2: + self.perm_mat = P_col1.row_join(P_col2) + else: + self.perm_mat = P_col1 + else: + self.perm_mat = P_col2 + + def _form_coefficient_matrices(self): + """Form the coefficient matrices C_0, C_1, and C_2.""" + + # Extract dimension variables + l, m, n, o, s, k = self._dims + # Build up the coefficient matrices C_0, C_1, and C_2 + # If there are configuration constraints (l > 0), form C_0 as normal. + # If not, C_0 is I_(nxn). Note that this works even if n=0 + if l > 0: + f_c_jac_q = self.f_c.jacobian(self.q) + self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q * + self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi + else: + self._C_0 = eye(n) + # If there are motion constraints (m > 0), form C_1 and C_2 as normal. + # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if + # o = 0. + if m > 0: + f_v_jac_u = self.f_v.jacobian(self.u) + temp = f_v_jac_u * self._Pud + if n != 0: + f_v_jac_q = self.f_v.jacobian(self.q) + self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q) + else: + self._C_1 = zeros(o, n) + self._C_2 = (eye(o) - self._Pud * + temp.LUsolve(f_v_jac_u)) * self._Pui + else: + self._C_1 = zeros(o, n) + self._C_2 = eye(o) + + def _form_block_matrices(self): + """Form the block matrices for composing M, A, and B.""" + + # Extract dimension variables + l, m, n, o, s, k = self._dims + # Block Matrix Definitions. These are only defined if under certain + # conditions. If undefined, an empty matrix is used instead + if n != 0: + self._M_qq = self.f_0.jacobian(self._qd) + self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q) + else: + self._M_qq = Matrix() + self._A_qq = Matrix() + if n != 0 and m != 0: + self._M_uqc = self.f_a.jacobian(self._qd_dup) + self._A_uqc = -self.f_a.jacobian(self.q) + else: + self._M_uqc = Matrix() + self._A_uqc = Matrix() + if n != 0 and o - m + k != 0: + self._M_uqd = self.f_3.jacobian(self._qd_dup) + self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q) + else: + self._M_uqd = Matrix() + self._A_uqd = Matrix() + if o != 0 and m != 0: + self._M_uuc = self.f_a.jacobian(self._ud) + self._A_uuc = -self.f_a.jacobian(self.u) + else: + self._M_uuc = Matrix() + self._A_uuc = Matrix() + if o != 0 and o - m + k != 0: + self._M_uud = self.f_2.jacobian(self._ud) + self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u) + else: + self._M_uud = Matrix() + self._A_uud = Matrix() + if o != 0 and n != 0: + self._A_qu = -self.f_1.jacobian(self.u) + else: + self._A_qu = Matrix() + if k != 0 and o - m + k != 0: + self._M_uld = self.f_4.jacobian(self.lams) + else: + self._M_uld = Matrix() + if s != 0 and o - m + k != 0: + self._B_u = -self.f_3.jacobian(self.r) + else: + self._B_u = Matrix() + + def linearize(self, op_point=None, A_and_B=False, simplify=False): + """Linearize the system about the operating point. Note that + q_op, u_op, qd_op, ud_op must satisfy the equations of motion. + These may be either symbolic or numeric. + + Parameters + ========== + + op_point : dict or iterable of dicts, optional + Dictionary or iterable of dictionaries containing the operating + point conditions. These will be substituted in to the linearized + system before the linearization is complete. Leave blank if you + want a completely symbolic form. Note that any reduction in + symbols (whether substituted for numbers or expressions with a + common parameter) will result in faster runtime. + + A_and_B : bool, optional + If A_and_B=False (default), (M, A, B) is returned for forming + [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True, + (A, B) is returned for forming dx = [A]x + [B]r, where + x = [q_ind, u_ind]^T. + + simplify : bool, optional + Determines if returned values are simplified before return. + For large expressions this may be time consuming. Default is False. + + Potential Issues + ================ + + Note that the process of solving with A_and_B=True is + computationally intensive if there are many symbolic parameters. + For this reason, it may be more desirable to use the default + A_and_B=False, returning M, A, and B. More values may then be + substituted in to these matrices later on. The state space form can + then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where + P = Linearizer.perm_mat. + """ + + # Run the setup if needed: + if not self._setup_done: + self._setup() + + # Compose dict of operating conditions + if isinstance(op_point, dict): + op_point_dict = op_point + elif isinstance(op_point, Iterable): + op_point_dict = {} + for op in op_point: + op_point_dict.update(op) + else: + op_point_dict = {} + + # Extract dimension variables + l, m, n, o, s, k = self._dims + + # Rename terms to shorten expressions + M_qq = self._M_qq + M_uqc = self._M_uqc + M_uqd = self._M_uqd + M_uuc = self._M_uuc + M_uud = self._M_uud + M_uld = self._M_uld + A_qq = self._A_qq + A_uqc = self._A_uqc + A_uqd = self._A_uqd + A_qu = self._A_qu + A_uuc = self._A_uuc + A_uud = self._A_uud + B_u = self._B_u + C_0 = self._C_0 + C_1 = self._C_1 + C_2 = self._C_2 + + # Build up Mass Matrix + # |M_qq 0_nxo 0_nxk| + # M = |M_uqc M_uuc 0_mxk| + # |M_uqd M_uud M_uld| + if o != 0: + col2 = Matrix([zeros(n, o), M_uuc, M_uud]) + if k != 0: + col3 = Matrix([zeros(n + m, k), M_uld]) + if n != 0: + col1 = Matrix([M_qq, M_uqc, M_uqd]) + if o != 0 and k != 0: + M = col1.row_join(col2).row_join(col3) + elif o != 0: + M = col1.row_join(col2) + else: + M = col1 + elif k != 0: + M = col2.row_join(col3) + else: + M = col2 + M_eq = msubs(M, op_point_dict) + + # Build up state coefficient matrix A + # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2| + # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2| + # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2| + # Col 1 is only defined if n != 0 + if n != 0: + r1c1 = A_qq + if o != 0: + r1c1 += (A_qu * C_1) + r1c1 = r1c1 * C_0 + if m != 0: + r2c1 = A_uqc + if o != 0: + r2c1 += (A_uuc * C_1) + r2c1 = r2c1 * C_0 + else: + r2c1 = Matrix() + if o - m + k != 0: + r3c1 = A_uqd + if o != 0: + r3c1 += (A_uud * C_1) + r3c1 = r3c1 * C_0 + else: + r3c1 = Matrix() + col1 = Matrix([r1c1, r2c1, r3c1]) + else: + col1 = Matrix() + # Col 2 is only defined if o != 0 + if o != 0: + if n != 0: + r1c2 = A_qu * C_2 + else: + r1c2 = Matrix() + if m != 0: + r2c2 = A_uuc * C_2 + else: + r2c2 = Matrix() + if o - m + k != 0: + r3c2 = A_uud * C_2 + else: + r3c2 = Matrix() + col2 = Matrix([r1c2, r2c2, r3c2]) + else: + col2 = Matrix() + if col1: + if col2: + Amat = col1.row_join(col2) + else: + Amat = col1 + else: + Amat = col2 + Amat_eq = msubs(Amat, op_point_dict) + + # Build up the B matrix if there are forcing variables + # |0_(n + m)xs| + # B = |B_u | + if s != 0 and o - m + k != 0: + Bmat = zeros(n + m, s).col_join(B_u) + Bmat_eq = msubs(Bmat, op_point_dict) + else: + Bmat_eq = Matrix() + + # kwarg A_and_B indicates to return A, B for forming the equation + # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T, + if A_and_B: + A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq) + if Bmat_eq: + B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq) + else: + # Bmat = Matrix([]), so no need to sub + B_cont = Bmat_eq + if simplify: + A_cont.simplify() + B_cont.simplify() + return A_cont, B_cont + # Otherwise return M, A, B for forming the equation + # [M]dx = [A]x + [B]r, where x = [q, u]^T + else: + if simplify: + M_eq.simplify() + Amat_eq.simplify() + Bmat_eq.simplify() + return M_eq, Amat_eq, Bmat_eq + + +def permutation_matrix(orig_vec, per_vec): + """Compute the permutation matrix to change order of + orig_vec into order of per_vec. + + Parameters + ========== + + orig_vec : array_like + Symbols in original ordering. + per_vec : array_like + Symbols in new ordering. + + Returns + ======= + + p_matrix : Matrix + Permutation matrix such that orig_vec == (p_matrix * per_vec). + """ + if not isinstance(orig_vec, (list, tuple)): + orig_vec = flatten(orig_vec) + if not isinstance(per_vec, (list, tuple)): + per_vec = flatten(per_vec) + if set(orig_vec) != set(per_vec): + raise ValueError("orig_vec and per_vec must be the same length, " + + "and contain the same symbols.") + ind_list = [orig_vec.index(i) for i in per_vec] + p_matrix = zeros(len(orig_vec)) + for i, j in enumerate(ind_list): + p_matrix[i, j] = 1 + return p_matrix diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/method.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/method.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2c4a5f388e56e37bd9ecdf6daffc08ffa51070 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/method.py @@ -0,0 +1,39 @@ +from abc import ABC, abstractmethod + +class _Methods(ABC): + """Abstract Base Class for all methods.""" + + @abstractmethod + def q(self): + pass + + @abstractmethod + def u(self): + pass + + @abstractmethod + def bodies(self): + pass + + @abstractmethod + def loads(self): + pass + + @abstractmethod + def mass_matrix(self): + pass + + @abstractmethod + def forcing(self): + pass + + @abstractmethod + def mass_matrix_full(self): + pass + + @abstractmethod + def forcing_full(self): + pass + + def _form_eoms(self): + raise NotImplementedError("Subclasses must implement this.") diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/models.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/models.py new file mode 100644 index 0000000000000000000000000000000000000000..a89b929ffd540a07787f6f94714850b348c90781 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/models.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python +"""This module contains some sample symbolic models used for testing and +examples.""" + +# Internal imports +from sympy.core import backend as sm +import sympy.physics.mechanics as me + + +def multi_mass_spring_damper(n=1, apply_gravity=False, + apply_external_forces=False): + r"""Returns a system containing the symbolic equations of motion and + associated variables for a simple multi-degree of freedom point mass, + spring, damper system with optional gravitational and external + specified forces. For example, a two mass system under the influence of + gravity and external forces looks like: + + :: + + ---------------- + | | | | g + \ | | | V + k0 / --- c0 | + | | | x0, v0 + --------- V + | m0 | ----- + --------- | + | | | | + \ v | | | + k1 / f0 --- c1 | + | | | x1, v1 + --------- V + | m1 | ----- + --------- + | f1 + V + + Parameters + ========== + + n : integer + The number of masses in the serial chain. + apply_gravity : boolean + If true, gravity will be applied to each mass. + apply_external_forces : boolean + If true, a time varying external force will be applied to each mass. + + Returns + ======= + + kane : sympy.physics.mechanics.kane.KanesMethod + A KanesMethod object. + + """ + + mass = sm.symbols('m:{}'.format(n)) + stiffness = sm.symbols('k:{}'.format(n)) + damping = sm.symbols('c:{}'.format(n)) + + acceleration_due_to_gravity = sm.symbols('g') + + coordinates = me.dynamicsymbols('x:{}'.format(n)) + speeds = me.dynamicsymbols('v:{}'.format(n)) + specifieds = me.dynamicsymbols('f:{}'.format(n)) + + ceiling = me.ReferenceFrame('N') + origin = me.Point('origin') + origin.set_vel(ceiling, 0) + + points = [origin] + kinematic_equations = [] + particles = [] + forces = [] + + for i in range(n): + + center = points[-1].locatenew('center{}'.format(i), + coordinates[i] * ceiling.x) + center.set_vel(ceiling, points[-1].vel(ceiling) + + speeds[i] * ceiling.x) + points.append(center) + + block = me.Particle('block{}'.format(i), center, mass[i]) + + kinematic_equations.append(speeds[i] - coordinates[i].diff()) + + total_force = (-stiffness[i] * coordinates[i] - + damping[i] * speeds[i]) + try: + total_force += (stiffness[i + 1] * coordinates[i + 1] + + damping[i + 1] * speeds[i + 1]) + except IndexError: # no force from below on last mass + pass + + if apply_gravity: + total_force += mass[i] * acceleration_due_to_gravity + + if apply_external_forces: + total_force += specifieds[i] + + forces.append((center, total_force * ceiling.x)) + + particles.append(block) + + kane = me.KanesMethod(ceiling, q_ind=coordinates, u_ind=speeds, + kd_eqs=kinematic_equations) + kane.kanes_equations(particles, forces) + + return kane + + +def n_link_pendulum_on_cart(n=1, cart_force=True, joint_torques=False): + r"""Returns the system containing the symbolic first order equations of + motion for a 2D n-link pendulum on a sliding cart under the influence of + gravity. + + :: + + | + o y v + \ 0 ^ g + \ | + --\-|---- + | \| | + F-> | o --|---> x + | | + --------- + o o + + Parameters + ========== + + n : integer + The number of links in the pendulum. + cart_force : boolean, default=True + If true an external specified lateral force is applied to the cart. + joint_torques : boolean, default=False + If true joint torques will be added as specified inputs at each + joint. + + Returns + ======= + + kane : sympy.physics.mechanics.kane.KanesMethod + A KanesMethod object. + + Notes + ===== + + The degrees of freedom of the system are n + 1, i.e. one for each + pendulum link and one for the lateral motion of the cart. + + M x' = F, where x = [u0, ..., un+1, q0, ..., qn+1] + + The joint angles are all defined relative to the ground where the x axis + defines the ground line and the y axis points up. The joint torques are + applied between each adjacent link and the between the cart and the + lower link where a positive torque corresponds to positive angle. + + """ + if n <= 0: + raise ValueError('The number of links must be a positive integer.') + + q = me.dynamicsymbols('q:{}'.format(n + 1)) + u = me.dynamicsymbols('u:{}'.format(n + 1)) + + if joint_torques is True: + T = me.dynamicsymbols('T1:{}'.format(n + 1)) + + m = sm.symbols('m:{}'.format(n + 1)) + l = sm.symbols('l:{}'.format(n)) + g, t = sm.symbols('g t') + + I = me.ReferenceFrame('I') + O = me.Point('O') + O.set_vel(I, 0) + + P0 = me.Point('P0') + P0.set_pos(O, q[0] * I.x) + P0.set_vel(I, u[0] * I.x) + Pa0 = me.Particle('Pa0', P0, m[0]) + + frames = [I] + points = [P0] + particles = [Pa0] + forces = [(P0, -m[0] * g * I.y)] + kindiffs = [q[0].diff(t) - u[0]] + + if cart_force is True or joint_torques is True: + specified = [] + else: + specified = None + + for i in range(n): + Bi = I.orientnew('B{}'.format(i), 'Axis', [q[i + 1], I.z]) + Bi.set_ang_vel(I, u[i + 1] * I.z) + frames.append(Bi) + + Pi = points[-1].locatenew('P{}'.format(i + 1), l[i] * Bi.y) + Pi.v2pt_theory(points[-1], I, Bi) + points.append(Pi) + + Pai = me.Particle('Pa' + str(i + 1), Pi, m[i + 1]) + particles.append(Pai) + + forces.append((Pi, -m[i + 1] * g * I.y)) + + if joint_torques is True: + + specified.append(T[i]) + + if i == 0: + forces.append((I, -T[i] * I.z)) + + if i == n - 1: + forces.append((Bi, T[i] * I.z)) + else: + forces.append((Bi, T[i] * I.z - T[i + 1] * I.z)) + + kindiffs.append(q[i + 1].diff(t) - u[i + 1]) + + if cart_force is True: + F = me.dynamicsymbols('F') + forces.append((P0, F * I.x)) + specified.append(F) + + kane = me.KanesMethod(I, q_ind=q, u_ind=u, kd_eqs=kindiffs) + kane.kanes_equations(particles, forces) + + return kane diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py new file mode 100644 index 0000000000000000000000000000000000000000..2abc5235566eee1cde73c39a2c37069730e03758 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/particle.py @@ -0,0 +1,281 @@ +from sympy.core.backend import sympify +from sympy.physics.vector import Point + +from sympy.utilities.exceptions import sympy_deprecation_warning + +__all__ = ['Particle'] + + +class Particle: + """A particle. + + Explanation + =========== + + Particles have a non-zero mass and lack spatial extension; they take up no + space. + + Values need to be supplied on initialization, but can be changed later. + + Parameters + ========== + + name : str + Name of particle + point : Point + A physics/mechanics Point which represents the position, velocity, and + acceleration of this Particle + mass : sympifyable + A SymPy expression representing the Particle's mass + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point + >>> from sympy import Symbol + >>> po = Point('po') + >>> m = Symbol('m') + >>> pa = Particle('pa', po, m) + >>> # Or you could change these later + >>> pa.mass = m + >>> pa.point = po + + """ + + def __init__(self, name, point, mass): + if not isinstance(name, str): + raise TypeError('Supply a valid name.') + self._name = name + self.mass = mass + self.point = point + self.potential_energy = 0 + + def __str__(self): + return self._name + + def __repr__(self): + return self.__str__() + + @property + def mass(self): + """Mass of the particle.""" + return self._mass + + @mass.setter + def mass(self, value): + self._mass = sympify(value) + + @property + def point(self): + """Point of the particle.""" + return self._point + + @point.setter + def point(self, p): + if not isinstance(p, Point): + raise TypeError("Particle point attribute must be a Point object.") + self._point = p + + def linear_momentum(self, frame): + """Linear momentum of the particle. + + Explanation + =========== + + The linear momentum L, of a particle P, with respect to frame N is + given by: + + L = m * v + + where m is the mass of the particle, and v is the velocity of the + particle in the frame N. + + Parameters + ========== + + frame : ReferenceFrame + The frame in which linear momentum is desired. + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame + >>> from sympy.physics.mechanics import dynamicsymbols + >>> from sympy.physics.vector import init_vprinting + >>> init_vprinting(pretty_print=False) + >>> m, v = dynamicsymbols('m v') + >>> N = ReferenceFrame('N') + >>> P = Point('P') + >>> A = Particle('A', P, m) + >>> P.set_vel(N, v * N.x) + >>> A.linear_momentum(N) + m*v*N.x + + """ + + return self.mass * self.point.vel(frame) + + def angular_momentum(self, point, frame): + """Angular momentum of the particle about the point. + + Explanation + =========== + + The angular momentum H, about some point O of a particle, P, is given + by: + + ``H = cross(r, m * v)`` + + where r is the position vector from point O to the particle P, m is + the mass of the particle, and v is the velocity of the particle in + the inertial frame, N. + + Parameters + ========== + + point : Point + The point about which angular momentum of the particle is desired. + + frame : ReferenceFrame + The frame in which angular momentum is desired. + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame + >>> from sympy.physics.mechanics import dynamicsymbols + >>> from sympy.physics.vector import init_vprinting + >>> init_vprinting(pretty_print=False) + >>> m, v, r = dynamicsymbols('m v r') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> A = O.locatenew('A', r * N.x) + >>> P = Particle('P', A, m) + >>> P.point.set_vel(N, v * N.y) + >>> P.angular_momentum(O, N) + m*r*v*N.z + + """ + + return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) + + def kinetic_energy(self, frame): + """Kinetic energy of the particle. + + Explanation + =========== + + The kinetic energy, T, of a particle, P, is given by: + + ``T = 1/2 (dot(m * v, v))`` + + where m is the mass of particle P, and v is the velocity of the + particle in the supplied ReferenceFrame. + + Parameters + ========== + + frame : ReferenceFrame + The Particle's velocity is typically defined with respect to + an inertial frame but any relevant frame in which the velocity is + known can be supplied. + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame + >>> from sympy import symbols + >>> m, v, r = symbols('m v r') + >>> N = ReferenceFrame('N') + >>> O = Point('O') + >>> P = Particle('P', O, m) + >>> P.point.set_vel(N, v * N.y) + >>> P.kinetic_energy(N) + m*v**2/2 + + """ + + return (self.mass / sympify(2) * self.point.vel(frame) & + self.point.vel(frame)) + + @property + def potential_energy(self): + """The potential energy of the Particle. + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point + >>> from sympy import symbols + >>> m, g, h = symbols('m g h') + >>> O = Point('O') + >>> P = Particle('P', O, m) + >>> P.potential_energy = m * g * h + >>> P.potential_energy + g*h*m + + """ + + return self._pe + + @potential_energy.setter + def potential_energy(self, scalar): + """Used to set the potential energy of the Particle. + + Parameters + ========== + + scalar : Sympifyable + The potential energy (a scalar) of the Particle. + + Examples + ======== + + >>> from sympy.physics.mechanics import Particle, Point + >>> from sympy import symbols + >>> m, g, h = symbols('m g h') + >>> O = Point('O') + >>> P = Particle('P', O, m) + >>> P.potential_energy = m * g * h + + """ + + self._pe = sympify(scalar) + + def set_potential_energy(self, scalar): + sympy_deprecation_warning( + """ +The sympy.physics.mechanics.Particle.set_potential_energy() +method is deprecated. Instead use + + P.potential_energy = scalar + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-set-potential-energy", + ) + self.potential_energy = scalar + + def parallel_axis(self, point, frame): + """Returns an inertia dyadic of the particle with respect to another + point and frame. + + Parameters + ========== + + point : sympy.physics.vector.Point + The point to express the inertia dyadic about. + frame : sympy.physics.vector.ReferenceFrame + The reference frame used to construct the dyadic. + + Returns + ======= + + inertia : sympy.physics.vector.Dyadic + The inertia dyadic of the particle expressed about the provided + point and frame. + + """ + # circular import issue + from sympy.physics.mechanics import inertia_of_point_mass + return inertia_of_point_mass(self.mass, self.point.pos_from(point), + frame) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py new file mode 100644 index 0000000000000000000000000000000000000000..27aefe74865178ac2d85bd61fa3f6b24bbada707 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/rigidbody.py @@ -0,0 +1,366 @@ +from sympy.core.backend import sympify +from sympy.physics.vector import Point, ReferenceFrame, Dyadic + +from sympy.utilities.exceptions import sympy_deprecation_warning + +__all__ = ['RigidBody'] + + +class RigidBody: + """An idealized rigid body. + + Explanation + =========== + + This is essentially a container which holds the various components which + describe a rigid body: a name, mass, center of mass, reference frame, and + inertia. + + All of these need to be supplied on creation, but can be changed + afterwards. + + Attributes + ========== + + name : string + The body's name. + masscenter : Point + The point which represents the center of mass of the rigid body. + frame : ReferenceFrame + The ReferenceFrame which the rigid body is fixed in. + mass : Sympifyable + The body's mass. + inertia : (Dyadic, Point) + The body's inertia about a point; stored in a tuple as shown above. + + Examples + ======== + + >>> from sympy import Symbol + >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody + >>> from sympy.physics.mechanics import outer + >>> m = Symbol('m') + >>> A = ReferenceFrame('A') + >>> P = Point('P') + >>> I = outer (A.x, A.x) + >>> inertia_tuple = (I, P) + >>> B = RigidBody('B', P, A, m, inertia_tuple) + >>> # Or you could change them afterwards + >>> m2 = Symbol('m2') + >>> B.mass = m2 + + """ + + def __init__(self, name, masscenter, frame, mass, inertia): + if not isinstance(name, str): + raise TypeError('Supply a valid name.') + self._name = name + self.masscenter = masscenter + self.mass = mass + self.frame = frame + self.inertia = inertia + self.potential_energy = 0 + + def __str__(self): + return self._name + + def __repr__(self): + return self.__str__() + + @property + def frame(self): + """The ReferenceFrame fixed to the body.""" + return self._frame + + @frame.setter + def frame(self, F): + if not isinstance(F, ReferenceFrame): + raise TypeError("RigidBody frame must be a ReferenceFrame object.") + self._frame = F + + @property + def masscenter(self): + """The body's center of mass.""" + return self._masscenter + + @masscenter.setter + def masscenter(self, p): + if not isinstance(p, Point): + raise TypeError("RigidBody center of mass must be a Point object.") + self._masscenter = p + + @property + def mass(self): + """The body's mass.""" + return self._mass + + @mass.setter + def mass(self, m): + self._mass = sympify(m) + + @property + def inertia(self): + """The body's inertia about a point; stored as (Dyadic, Point).""" + return (self._inertia, self._inertia_point) + + @inertia.setter + def inertia(self, I): + if not isinstance(I[0], Dyadic): + raise TypeError("RigidBody inertia must be a Dyadic object.") + if not isinstance(I[1], Point): + raise TypeError("RigidBody inertia must be about a Point.") + self._inertia = I[0] + self._inertia_point = I[1] + # have I S/O, want I S/S* + # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O + # I_S/S* = I_S/O - I_S*/O + from sympy.physics.mechanics.functions import inertia_of_point_mass + I_Ss_O = inertia_of_point_mass(self.mass, + self.masscenter.pos_from(I[1]), + self.frame) + self._central_inertia = I[0] - I_Ss_O + + @property + def central_inertia(self): + """The body's central inertia dyadic.""" + return self._central_inertia + + @central_inertia.setter + def central_inertia(self, I): + if not isinstance(I, Dyadic): + raise TypeError("RigidBody inertia must be a Dyadic object.") + self.inertia = (I, self.masscenter) + + def linear_momentum(self, frame): + """ Linear momentum of the rigid body. + + Explanation + =========== + + The linear momentum L, of a rigid body B, with respect to frame N is + given by: + + L = M * v* + + where M is the mass of the rigid body and v* is the velocity of + the mass center of B in the frame, N. + + Parameters + ========== + + frame : ReferenceFrame + The frame in which linear momentum is desired. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer + >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols + >>> from sympy.physics.vector import init_vprinting + >>> init_vprinting(pretty_print=False) + >>> M, v = dynamicsymbols('M v') + >>> N = ReferenceFrame('N') + >>> P = Point('P') + >>> P.set_vel(N, v * N.x) + >>> I = outer (N.x, N.x) + >>> Inertia_tuple = (I, P) + >>> B = RigidBody('B', P, N, M, Inertia_tuple) + >>> B.linear_momentum(N) + M*v*N.x + + """ + + return self.mass * self.masscenter.vel(frame) + + def angular_momentum(self, point, frame): + """Returns the angular momentum of the rigid body about a point in the + given frame. + + Explanation + =========== + + The angular momentum H of a rigid body B about some point O in a frame + N is given by: + + ``H = dot(I, w) + cross(r, M * v)`` + + where I is the central inertia dyadic of B, w is the angular velocity + of body B in the frame, N, r is the position vector from point O to the + mass center of B, and v is the velocity of the mass center in the + frame, N. + + Parameters + ========== + + point : Point + The point about which angular momentum is desired. + frame : ReferenceFrame + The frame in which angular momentum is desired. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer + >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols + >>> from sympy.physics.vector import init_vprinting + >>> init_vprinting(pretty_print=False) + >>> M, v, r, omega = dynamicsymbols('M v r omega') + >>> N = ReferenceFrame('N') + >>> b = ReferenceFrame('b') + >>> b.set_ang_vel(N, omega * b.x) + >>> P = Point('P') + >>> P.set_vel(N, 1 * N.x) + >>> I = outer(b.x, b.x) + >>> B = RigidBody('B', P, b, M, (I, P)) + >>> B.angular_momentum(P, N) + omega*b.x + + """ + I = self.central_inertia + w = self.frame.ang_vel_in(frame) + m = self.mass + r = self.masscenter.pos_from(point) + v = self.masscenter.vel(frame) + + return I.dot(w) + r.cross(m * v) + + def kinetic_energy(self, frame): + """Kinetic energy of the rigid body. + + Explanation + =========== + + The kinetic energy, T, of a rigid body, B, is given by: + + ``T = 1/2 * (dot(dot(I, w), w) + dot(m * v, v))`` + + where I and m are the central inertia dyadic and mass of rigid body B, + respectively, omega is the body's angular velocity and v is the + velocity of the body's mass center in the supplied ReferenceFrame. + + Parameters + ========== + + frame : ReferenceFrame + The RigidBody's angular velocity and the velocity of it's mass + center are typically defined with respect to an inertial frame but + any relevant frame in which the velocities are known can be supplied. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer + >>> from sympy.physics.mechanics import RigidBody + >>> from sympy import symbols + >>> M, v, r, omega = symbols('M v r omega') + >>> N = ReferenceFrame('N') + >>> b = ReferenceFrame('b') + >>> b.set_ang_vel(N, omega * b.x) + >>> P = Point('P') + >>> P.set_vel(N, v * N.x) + >>> I = outer (b.x, b.x) + >>> inertia_tuple = (I, P) + >>> B = RigidBody('B', P, b, M, inertia_tuple) + >>> B.kinetic_energy(N) + M*v**2/2 + omega**2/2 + + """ + + rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia & + self.frame.ang_vel_in(frame)) / sympify(2)) + + translational_KE = (self.mass * (self.masscenter.vel(frame) & + self.masscenter.vel(frame)) / sympify(2)) + + return rotational_KE + translational_KE + + @property + def potential_energy(self): + """The potential energy of the RigidBody. + + Examples + ======== + + >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame + >>> from sympy import symbols + >>> M, g, h = symbols('M g h') + >>> b = ReferenceFrame('b') + >>> P = Point('P') + >>> I = outer (b.x, b.x) + >>> Inertia_tuple = (I, P) + >>> B = RigidBody('B', P, b, M, Inertia_tuple) + >>> B.potential_energy = M * g * h + >>> B.potential_energy + M*g*h + + """ + + return self._pe + + @potential_energy.setter + def potential_energy(self, scalar): + """Used to set the potential energy of this RigidBody. + + Parameters + ========== + + scalar: Sympifyable + The potential energy (a scalar) of the RigidBody. + + Examples + ======== + + >>> from sympy.physics.mechanics import Point, outer + >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame + >>> from sympy import symbols + >>> b = ReferenceFrame('b') + >>> M, g, h = symbols('M g h') + >>> P = Point('P') + >>> I = outer (b.x, b.x) + >>> Inertia_tuple = (I, P) + >>> B = RigidBody('B', P, b, M, Inertia_tuple) + >>> B.potential_energy = M * g * h + + """ + + self._pe = sympify(scalar) + + def set_potential_energy(self, scalar): + sympy_deprecation_warning( + """ +The sympy.physics.mechanics.RigidBody.set_potential_energy() +method is deprecated. Instead use + + B.potential_energy = scalar + """, + deprecated_since_version="1.5", + active_deprecations_target="deprecated-set-potential-energy", + ) + self.potential_energy = scalar + + def parallel_axis(self, point, frame=None): + """Returns the inertia dyadic of the body with respect to another + point. + + Parameters + ========== + + point : sympy.physics.vector.Point + The point to express the inertia dyadic about. + frame : sympy.physics.vector.ReferenceFrame + The reference frame used to construct the dyadic. + + Returns + ======= + + inertia : sympy.physics.vector.Dyadic + The inertia dyadic of the rigid body expressed about the provided + point. + + """ + # circular import issue + from sympy.physics.mechanics.functions import inertia_of_point_mass + if frame is None: + frame = self.frame + return self.central_inertia + inertia_of_point_mass( + self.mass, self.masscenter.pos_from(point), frame) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/system.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/system.py new file mode 100644 index 0000000000000000000000000000000000000000..aa63b4dc16efda629478fb67faf148ada77ce107 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/system.py @@ -0,0 +1,445 @@ +from sympy.core.backend import eye, Matrix, zeros +from sympy.physics.mechanics import dynamicsymbols +from sympy.physics.mechanics.functions import find_dynamicsymbols + +__all__ = ['SymbolicSystem'] + + +class SymbolicSystem: + """SymbolicSystem is a class that contains all the information about a + system in a symbolic format such as the equations of motions and the bodies + and loads in the system. + + There are three ways that the equations of motion can be described for + Symbolic System: + + + [1] Explicit form where the kinematics and dynamics are combined + x' = F_1(x, t, r, p) + + [2] Implicit form where the kinematics and dynamics are combined + M_2(x, p) x' = F_2(x, t, r, p) + + [3] Implicit form where the kinematics and dynamics are separate + M_3(q, p) u' = F_3(q, u, t, r, p) + q' = G(q, u, t, r, p) + + where + + x : states, e.g. [q, u] + t : time + r : specified (exogenous) inputs + p : constants + q : generalized coordinates + u : generalized speeds + F_1 : right hand side of the combined equations in explicit form + F_2 : right hand side of the combined equations in implicit form + F_3 : right hand side of the dynamical equations in implicit form + M_2 : mass matrix of the combined equations in implicit form + M_3 : mass matrix of the dynamical equations in implicit form + G : right hand side of the kinematical differential equations + + Parameters + ========== + + coord_states : ordered iterable of functions of time + This input will either be a collection of the coordinates or states + of the system depending on whether or not the speeds are also + given. If speeds are specified this input will be assumed to + be the coordinates otherwise this input will be assumed to + be the states. + + right_hand_side : Matrix + This variable is the right hand side of the equations of motion in + any of the forms. The specific form will be assumed depending on + whether a mass matrix or coordinate derivatives are given. + + speeds : ordered iterable of functions of time, optional + This is a collection of the generalized speeds of the system. If + given it will be assumed that the first argument (coord_states) + will represent the generalized coordinates of the system. + + mass_matrix : Matrix, optional + The matrix of the implicit forms of the equations of motion (forms + [2] and [3]). The distinction between the forms is determined by + whether or not the coordinate derivatives are passed in. If + they are given form [3] will be assumed otherwise form [2] is + assumed. + + coordinate_derivatives : Matrix, optional + The right hand side of the kinematical equations in explicit form. + If given it will be assumed that the equations of motion are being + entered in form [3]. + + alg_con : Iterable, optional + The indexes of the rows in the equations of motion that contain + algebraic constraints instead of differential equations. If the + equations are input in form [3], it will be assumed the indexes are + referencing the mass_matrix/right_hand_side combination and not the + coordinate_derivatives. + + output_eqns : Dictionary, optional + Any output equations that are desired to be tracked are stored in a + dictionary where the key corresponds to the name given for the + specific equation and the value is the equation itself in symbolic + form + + coord_idxs : Iterable, optional + If coord_states corresponds to the states rather than the + coordinates this variable will tell SymbolicSystem which indexes of + the states correspond to generalized coordinates. + + speed_idxs : Iterable, optional + If coord_states corresponds to the states rather than the + coordinates this variable will tell SymbolicSystem which indexes of + the states correspond to generalized speeds. + + bodies : iterable of Body/Rigidbody objects, optional + Iterable containing the bodies of the system + + loads : iterable of load instances (described below), optional + Iterable containing the loads of the system where forces are given + by (point of application, force vector) and torques are given by + (reference frame acting upon, torque vector). Ex [(point, force), + (ref_frame, torque)] + + Attributes + ========== + + coordinates : Matrix, shape(n, 1) + This is a matrix containing the generalized coordinates of the system + + speeds : Matrix, shape(m, 1) + This is a matrix containing the generalized speeds of the system + + states : Matrix, shape(o, 1) + This is a matrix containing the state variables of the system + + alg_con : List + This list contains the indices of the algebraic constraints in the + combined equations of motion. The presence of these constraints + requires that a DAE solver be used instead of an ODE solver. + If the system is given in form [3] the alg_con variable will be + adjusted such that it is a representation of the combined kinematics + and dynamics thus make sure it always matches the mass matrix + entered. + + dyn_implicit_mat : Matrix, shape(m, m) + This is the M matrix in form [3] of the equations of motion (the mass + matrix or generalized inertia matrix of the dynamical equations of + motion in implicit form). + + dyn_implicit_rhs : Matrix, shape(m, 1) + This is the F vector in form [3] of the equations of motion (the right + hand side of the dynamical equations of motion in implicit form). + + comb_implicit_mat : Matrix, shape(o, o) + This is the M matrix in form [2] of the equations of motion. + This matrix contains a block diagonal structure where the top + left block (the first rows) represent the matrix in the + implicit form of the kinematical equations and the bottom right + block (the last rows) represent the matrix in the implicit form + of the dynamical equations. + + comb_implicit_rhs : Matrix, shape(o, 1) + This is the F vector in form [2] of the equations of motion. The top + part of the vector represents the right hand side of the implicit form + of the kinemaical equations and the bottom of the vector represents the + right hand side of the implicit form of the dynamical equations of + motion. + + comb_explicit_rhs : Matrix, shape(o, 1) + This vector represents the right hand side of the combined equations of + motion in explicit form (form [1] from above). + + kin_explicit_rhs : Matrix, shape(m, 1) + This is the right hand side of the explicit form of the kinematical + equations of motion as can be seen in form [3] (the G matrix). + + output_eqns : Dictionary + If output equations were given they are stored in a dictionary where + the key corresponds to the name given for the specific equation and + the value is the equation itself in symbolic form + + bodies : Tuple + If the bodies in the system were given they are stored in a tuple for + future access + + loads : Tuple + If the loads in the system were given they are stored in a tuple for + future access. This includes forces and torques where forces are given + by (point of application, force vector) and torques are given by + (reference frame acted upon, torque vector). + + Example + ======= + + As a simple example, the dynamics of a simple pendulum will be input into a + SymbolicSystem object manually. First some imports will be needed and then + symbols will be set up for the length of the pendulum (l), mass at the end + of the pendulum (m), and a constant for gravity (g). :: + + >>> from sympy import Matrix, sin, symbols + >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem + >>> l, m, g = symbols('l m g') + + The system will be defined by an angle of theta from the vertical and a + generalized speed of omega will be used where omega = theta_dot. :: + + >>> theta, omega = dynamicsymbols('theta omega') + + Now the equations of motion are ready to be formed and passed to the + SymbolicSystem object. :: + + >>> kin_explicit_rhs = Matrix([omega]) + >>> dyn_implicit_mat = Matrix([l**2 * m]) + >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)]) + >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega], + ... dyn_implicit_mat) + + Notes + ===== + + m : number of generalized speeds + n : number of generalized coordinates + o : number of states + + """ + + def __init__(self, coord_states, right_hand_side, speeds=None, + mass_matrix=None, coordinate_derivatives=None, alg_con=None, + output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None, + loads=None): + """Initializes a SymbolicSystem object""" + + # Extract information on speeds, coordinates and states + if speeds is None: + self._states = Matrix(coord_states) + + if coord_idxs is None: + self._coordinates = None + else: + coords = [coord_states[i] for i in coord_idxs] + self._coordinates = Matrix(coords) + + if speed_idxs is None: + self._speeds = None + else: + speeds_inter = [coord_states[i] for i in speed_idxs] + self._speeds = Matrix(speeds_inter) + else: + self._coordinates = Matrix(coord_states) + self._speeds = Matrix(speeds) + self._states = self._coordinates.col_join(self._speeds) + + # Extract equations of motion form + if coordinate_derivatives is not None: + self._kin_explicit_rhs = coordinate_derivatives + self._dyn_implicit_rhs = right_hand_side + self._dyn_implicit_mat = mass_matrix + self._comb_implicit_rhs = None + self._comb_implicit_mat = None + self._comb_explicit_rhs = None + elif mass_matrix is not None: + self._kin_explicit_rhs = None + self._dyn_implicit_rhs = None + self._dyn_implicit_mat = None + self._comb_implicit_rhs = right_hand_side + self._comb_implicit_mat = mass_matrix + self._comb_explicit_rhs = None + else: + self._kin_explicit_rhs = None + self._dyn_implicit_rhs = None + self._dyn_implicit_mat = None + self._comb_implicit_rhs = None + self._comb_implicit_mat = None + self._comb_explicit_rhs = right_hand_side + + # Set the remainder of the inputs as instance attributes + if alg_con is not None and coordinate_derivatives is not None: + alg_con = [i + len(coordinate_derivatives) for i in alg_con] + self._alg_con = alg_con + self.output_eqns = output_eqns + + # Change the body and loads iterables to tuples if they are not tuples + # already + if not isinstance(bodies, tuple) and bodies is not None: + bodies = tuple(bodies) + if not isinstance(loads, tuple) and loads is not None: + loads = tuple(loads) + self._bodies = bodies + self._loads = loads + + @property + def coordinates(self): + """Returns the column matrix of the generalized coordinates""" + if self._coordinates is None: + raise AttributeError("The coordinates were not specified.") + else: + return self._coordinates + + @property + def speeds(self): + """Returns the column matrix of generalized speeds""" + if self._speeds is None: + raise AttributeError("The speeds were not specified.") + else: + return self._speeds + + @property + def states(self): + """Returns the column matrix of the state variables""" + return self._states + + @property + def alg_con(self): + """Returns a list with the indices of the rows containing algebraic + constraints in the combined form of the equations of motion""" + return self._alg_con + + @property + def dyn_implicit_mat(self): + """Returns the matrix, M, corresponding to the dynamic equations in + implicit form, M x' = F, where the kinematical equations are not + included""" + if self._dyn_implicit_mat is None: + raise AttributeError("dyn_implicit_mat is not specified for " + "equations of motion form [1] or [2].") + else: + return self._dyn_implicit_mat + + @property + def dyn_implicit_rhs(self): + """Returns the column matrix, F, corresponding to the dynamic equations + in implicit form, M x' = F, where the kinematical equations are not + included""" + if self._dyn_implicit_rhs is None: + raise AttributeError("dyn_implicit_rhs is not specified for " + "equations of motion form [1] or [2].") + else: + return self._dyn_implicit_rhs + + @property + def comb_implicit_mat(self): + """Returns the matrix, M, corresponding to the equations of motion in + implicit form (form [2]), M x' = F, where the kinematical equations are + included""" + if self._comb_implicit_mat is None: + if self._dyn_implicit_mat is not None: + num_kin_eqns = len(self._kin_explicit_rhs) + num_dyn_eqns = len(self._dyn_implicit_rhs) + zeros1 = zeros(num_kin_eqns, num_dyn_eqns) + zeros2 = zeros(num_dyn_eqns, num_kin_eqns) + inter1 = eye(num_kin_eqns).row_join(zeros1) + inter2 = zeros2.row_join(self._dyn_implicit_mat) + self._comb_implicit_mat = inter1.col_join(inter2) + return self._comb_implicit_mat + else: + raise AttributeError("comb_implicit_mat is not specified for " + "equations of motion form [1].") + else: + return self._comb_implicit_mat + + @property + def comb_implicit_rhs(self): + """Returns the column matrix, F, corresponding to the equations of + motion in implicit form (form [2]), M x' = F, where the kinematical + equations are included""" + if self._comb_implicit_rhs is None: + if self._dyn_implicit_rhs is not None: + kin_inter = self._kin_explicit_rhs + dyn_inter = self._dyn_implicit_rhs + self._comb_implicit_rhs = kin_inter.col_join(dyn_inter) + return self._comb_implicit_rhs + else: + raise AttributeError("comb_implicit_mat is not specified for " + "equations of motion in form [1].") + else: + return self._comb_implicit_rhs + + def compute_explicit_form(self): + """If the explicit right hand side of the combined equations of motion + is to provided upon initialization, this method will calculate it. This + calculation can potentially take awhile to compute.""" + if self._comb_explicit_rhs is not None: + raise AttributeError("comb_explicit_rhs is already formed.") + + inter1 = getattr(self, 'kin_explicit_rhs', None) + if inter1 is not None: + inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs) + out = inter1.col_join(inter2) + else: + out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs) + + self._comb_explicit_rhs = out + + @property + def comb_explicit_rhs(self): + """Returns the right hand side of the equations of motion in explicit + form, x' = F, where the kinematical equations are included""" + if self._comb_explicit_rhs is None: + raise AttributeError("Please run .combute_explicit_form before " + "attempting to access comb_explicit_rhs.") + else: + return self._comb_explicit_rhs + + @property + def kin_explicit_rhs(self): + """Returns the right hand side of the kinematical equations in explicit + form, q' = G""" + if self._kin_explicit_rhs is None: + raise AttributeError("kin_explicit_rhs is not specified for " + "equations of motion form [1] or [2].") + else: + return self._kin_explicit_rhs + + def dynamic_symbols(self): + """Returns a column matrix containing all of the symbols in the system + that depend on time""" + # Create a list of all of the expressions in the equations of motion + if self._comb_explicit_rhs is None: + eom_expressions = (self.comb_implicit_mat[:] + + self.comb_implicit_rhs[:]) + else: + eom_expressions = (self._comb_explicit_rhs[:]) + + functions_of_time = set() + for expr in eom_expressions: + functions_of_time = functions_of_time.union( + find_dynamicsymbols(expr)) + functions_of_time = functions_of_time.union(self._states) + + return tuple(functions_of_time) + + def constant_symbols(self): + """Returns a column matrix containing all of the symbols in the system + that do not depend on time""" + # Create a list of all of the expressions in the equations of motion + if self._comb_explicit_rhs is None: + eom_expressions = (self.comb_implicit_mat[:] + + self.comb_implicit_rhs[:]) + else: + eom_expressions = (self._comb_explicit_rhs[:]) + + constants = set() + for expr in eom_expressions: + constants = constants.union(expr.free_symbols) + constants.remove(dynamicsymbols._t) + + return tuple(constants) + + @property + def bodies(self): + """Returns the bodies in the system""" + if self._bodies is None: + raise AttributeError("bodies were not specified for the system.") + else: + return self._bodies + + @property + def loads(self): + """Returns the loads in the system""" + if self._loads is None: + raise AttributeError("loads were not specified for the system.") + else: + return self._loads diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1df05ef3a9284276e52318bb0b826d2c903d2494 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_joint.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..647a479e2c4566b4c7fa7cddbc86a71aea4905c2 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eecfb3f5b479526c0f17733537ccdd9cee693db Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de20d0e9d7d113a5e907f75fe572341f7c924b83 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_particle.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f37339617a69af14b9af8685cd2487a5b08449 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_system.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py new file mode 100644 index 0000000000000000000000000000000000000000..52b6c8aa47abbcd306a9258da0d90ecd2e5e7f5b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_joint.py @@ -0,0 +1,1144 @@ +from sympy.core.function import expand_mul +from sympy.core.numbers import pi +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.core.backend import Matrix, _simplify_matrix, eye, zeros +from sympy.core.symbol import symbols +from sympy.physics.mechanics import (dynamicsymbols, Body, JointsMethod, + PinJoint, PrismaticJoint, CylindricalJoint, + PlanarJoint, SphericalJoint, WeldJoint) +from sympy.physics.mechanics.joint import Joint +from sympy.physics.vector import Vector, ReferenceFrame, Point +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +Vector.simp = True +t = dynamicsymbols._t # type: ignore + + +def _generate_body(interframe=False): + N = ReferenceFrame('N') + A = ReferenceFrame('A') + P = Body('P', frame=N) + C = Body('C', frame=A) + if interframe: + Pint, Cint = ReferenceFrame('P_int'), ReferenceFrame('C_int') + Pint.orient_axis(N, N.x, pi) + Cint.orient_axis(A, A.y, -pi / 2) + return N, A, P, C, Pint, Cint + return N, A, P, C + + +def test_Joint(): + parent = Body('parent') + child = Body('child') + raises(TypeError, lambda: Joint('J', parent, child)) + + +def test_coordinate_generation(): + q, u, qj, uj = dynamicsymbols('q u q_J u_J') + q0j, q1j, q2j, q3j, u0j, u1j, u2j, u3j = dynamicsymbols('q0:4_J u0:4_J') + q0, q1, q2, q3, u0, u1, u2, u3 = dynamicsymbols('q0:4 u0:4') + _, _, P, C = _generate_body() + # Using PinJoint to access Joint's coordinate generation method + J = PinJoint('J', P, C) + # Test single given + assert J._fill_coordinate_list(q, 1) == Matrix([q]) + assert J._fill_coordinate_list([u], 1) == Matrix([u]) + assert J._fill_coordinate_list([u], 1, offset=2) == Matrix([u]) + # Test None + assert J._fill_coordinate_list(None, 1) == Matrix([qj]) + assert J._fill_coordinate_list([None], 1) == Matrix([qj]) + assert J._fill_coordinate_list([q0, None, None], 3) == Matrix( + [q0, q1j, q2j]) + # Test autofill + assert J._fill_coordinate_list(None, 3) == Matrix([q0j, q1j, q2j]) + assert J._fill_coordinate_list([], 3) == Matrix([q0j, q1j, q2j]) + # Test offset + assert J._fill_coordinate_list([], 3, offset=1) == Matrix([q1j, q2j, q3j]) + assert J._fill_coordinate_list([q1, None, q3], 3, offset=1) == Matrix( + [q1, q2j, q3]) + assert J._fill_coordinate_list(None, 2, offset=2) == Matrix([q2j, q3j]) + # Test label + assert J._fill_coordinate_list(None, 1, 'u') == Matrix([uj]) + assert J._fill_coordinate_list([], 3, 'u') == Matrix([u0j, u1j, u2j]) + # Test single numbering + assert J._fill_coordinate_list(None, 1, number_single=True) == Matrix([q0j]) + assert J._fill_coordinate_list([], 1, 'u', 2, True) == Matrix([u2j]) + assert J._fill_coordinate_list([], 3, 'q') == Matrix([q0j, q1j, q2j]) + # Test invalid number of coordinates supplied + raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 1)) + raises(ValueError, lambda: J._fill_coordinate_list([u0, u1, None], 2, 'u')) + raises(ValueError, lambda: J._fill_coordinate_list([q0, q1], 3)) + # Test incorrect coordinate type + raises(TypeError, lambda: J._fill_coordinate_list([q0, symbols('q1')], 2)) + raises(TypeError, lambda: J._fill_coordinate_list([q0 + q1, q1], 2)) + # Test if derivative as generalized speed is allowed + _, _, P, C = _generate_body() + PinJoint('J', P, C, q1, q1.diff(t)) + # Test duplicate coordinates + _, _, P, C = _generate_body() + raises(ValueError, lambda: SphericalJoint('J', P, C, [q1j, None, None])) + raises(ValueError, lambda: SphericalJoint('J', P, C, speeds=[u0, u0, u1])) + + +def test_pin_joint(): + P = Body('P') + C = Body('C') + l, m = symbols('l m') + q, u = dynamicsymbols('q_J, u_J') + Pj = PinJoint('J', P, C) + assert Pj.name == 'J' + assert Pj.parent == P + assert Pj.child == C + assert Pj.coordinates == Matrix([q]) + assert Pj.speeds == Matrix([u]) + assert Pj.kdes == Matrix([u - q.diff(t)]) + assert Pj.joint_axis == P.frame.x + assert Pj.child_point.pos_from(C.masscenter) == Vector(0) + assert Pj.parent_point.pos_from(P.masscenter) == Vector(0) + assert Pj.parent_point.pos_from(Pj._child_point) == Vector(0) + assert C.masscenter.pos_from(P.masscenter) == Vector(0) + assert Pj.parent_interframe == P.frame + assert Pj.child_interframe == C.frame + assert Pj.__str__() == 'PinJoint: J parent: P child: C' + + P1 = Body('P1') + C1 = Body('C1') + Pint = ReferenceFrame('P_int') + Pint.orient_axis(P1.frame, P1.y, pi / 2) + J1 = PinJoint('J1', P1, C1, parent_point=l*P1.frame.x, + child_point=m*C1.frame.y, joint_axis=P1.frame.z, + parent_interframe=Pint) + assert J1._joint_axis == P1.frame.z + assert J1._child_point.pos_from(C1.masscenter) == m * C1.frame.y + assert J1._parent_point.pos_from(P1.masscenter) == l * P1.frame.x + assert J1._parent_point.pos_from(J1._child_point) == Vector(0) + assert (P1.masscenter.pos_from(C1.masscenter) == + -l*P1.frame.x + m*C1.frame.y) + assert J1.parent_interframe == Pint + assert J1.child_interframe == C1.frame + + q, u = dynamicsymbols('q, u') + N, A, P, C, Pint, Cint = _generate_body(True) + parent_point = P.masscenter.locatenew('parent_point', N.x + N.y) + child_point = C.masscenter.locatenew('child_point', C.y + C.z) + J = PinJoint('J', P, C, q, u, parent_point=parent_point, + child_point=child_point, parent_interframe=Pint, + child_interframe=Cint, joint_axis=N.z) + assert J.joint_axis == N.z + assert J.parent_point.vel(N) == 0 + assert J.parent_point == parent_point + assert J.child_point == child_point + assert J.child_point.pos_from(P.masscenter) == N.x + N.y + assert J.parent_point.pos_from(C.masscenter) == C.y + C.z + assert C.masscenter.pos_from(P.masscenter) == N.x + N.y - C.y - C.z + assert C.masscenter.vel(N).express(N) == (u * sin(q) - u * cos(q)) * N.x + ( + -u * sin(q) - u * cos(q)) * N.y + assert J.parent_interframe == Pint + assert J.child_interframe == Cint + + +def test_pin_joint_double_pendulum(): + q1, q2 = dynamicsymbols('q1 q2') + u1, u2 = dynamicsymbols('u1 u2') + m, l = symbols('m l') + N = ReferenceFrame('N') + A = ReferenceFrame('A') + B = ReferenceFrame('B') + C = Body('C', frame=N) # ceiling + PartP = Body('P', frame=A, mass=m) + PartR = Body('R', frame=B, mass=m) + + J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1, + child_point=-l*A.x, joint_axis=C.frame.z) + J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2, + child_point=-l*B.x, joint_axis=PartP.frame.z) + + # Check orientation + assert N.dcm(A) == Matrix([[cos(q1), -sin(q1), 0], + [sin(q1), cos(q1), 0], [0, 0, 1]]) + assert A.dcm(B) == Matrix([[cos(q2), -sin(q2), 0], + [sin(q2), cos(q2), 0], [0, 0, 1]]) + assert _simplify_matrix(N.dcm(B)) == Matrix([[cos(q1 + q2), -sin(q1 + q2), 0], + [sin(q1 + q2), cos(q1 + q2), 0], + [0, 0, 1]]) + + # Check Angular Velocity + assert A.ang_vel_in(N) == u1 * N.z + assert B.ang_vel_in(A) == u2 * A.z + assert B.ang_vel_in(N) == u1 * N.z + u2 * A.z + + # Check kde + assert J1.kdes == Matrix([u1 - q1.diff(t)]) + assert J2.kdes == Matrix([u2 - q2.diff(t)]) + + # Check Linear Velocity + assert PartP.masscenter.vel(N) == l*u1*A.y + assert PartR.masscenter.vel(A) == l*u2*B.y + assert PartR.masscenter.vel(N) == l*u1*A.y + l*(u1 + u2)*B.y + + +def test_pin_joint_chaos_pendulum(): + mA, mB, lA, lB, h = symbols('mA, mB, lA, lB, h') + theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha') + N = ReferenceFrame('N') + A = ReferenceFrame('A') + B = ReferenceFrame('B') + lA = (lB - h / 2) / 2 + lC = (lB/2 + h/4) + rod = Body('rod', frame=A, mass=mA) + plate = Body('plate', mass=mB, frame=B) + C = Body('C', frame=N) + J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega, + child_point=lA*A.z, joint_axis=N.y) + J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha, + parent_point=lC*A.z, joint_axis=A.z) + + # Check orientation + assert A.dcm(N) == Matrix([[cos(theta), 0, -sin(theta)], + [0, 1, 0], + [sin(theta), 0, cos(theta)]]) + assert A.dcm(B) == Matrix([[cos(phi), -sin(phi), 0], + [sin(phi), cos(phi), 0], + [0, 0, 1]]) + assert B.dcm(N) == Matrix([ + [cos(phi)*cos(theta), sin(phi), -sin(theta)*cos(phi)], + [-sin(phi)*cos(theta), cos(phi), sin(phi)*sin(theta)], + [sin(theta), 0, cos(theta)]]) + + # Check Angular Velocity + assert A.ang_vel_in(N) == omega*N.y + assert A.ang_vel_in(B) == -alpha*A.z + assert N.ang_vel_in(B) == -omega*N.y - alpha*A.z + + # Check kde + assert J1.kdes == Matrix([omega - theta.diff(t)]) + assert J2.kdes == Matrix([alpha - phi.diff(t)]) + + # Check pos of masscenters + assert C.masscenter.pos_from(rod.masscenter) == lA*A.z + assert rod.masscenter.pos_from(plate.masscenter) == - lC * A.z + + # Check Linear Velocities + assert rod.masscenter.vel(N) == (h/4 - lB/2)*omega*A.x + assert plate.masscenter.vel(N) == ((h/4 - lB/2)*omega + + (h/4 + lB/2)*omega)*A.x + + +def test_pin_joint_interframe(): + q, u = dynamicsymbols('q, u') + # Check not connected + N, A, P, C = _generate_body() + Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint') + raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint)) + raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint)) + # Check not fixed interframe + Pint.orient_axis(N, N.z, q) + Cint.orient_axis(A, A.z, q) + raises(ValueError, lambda: PinJoint('J', P, C, parent_interframe=Pint)) + raises(ValueError, lambda: PinJoint('J', P, C, child_interframe=Cint)) + # Check only parent_interframe + N, A, P, C = _generate_body() + Pint = ReferenceFrame('Pint') + Pint.orient_body_fixed(N, (pi / 4, pi, pi / 3), 'xyz') + PinJoint('J', P, C, q, u, parent_point=N.x, child_point=-C.y, + parent_interframe=Pint, joint_axis=Pint.x) + assert _simplify_matrix(N.dcm(A)) - Matrix([ + [-1 / 2, sqrt(3) * cos(q) / 2, -sqrt(3) * sin(q) / 2], + [sqrt(6) / 4, sqrt(2) * (2 * sin(q) + cos(q)) / 4, + sqrt(2) * (-sin(q) + 2 * cos(q)) / 4], + [sqrt(6) / 4, sqrt(2) * (-2 * sin(q) + cos(q)) / 4, + -sqrt(2) * (sin(q) + 2 * cos(q)) / 4]]) == zeros(3) + assert A.ang_vel_in(N) == u * Pint.x + assert C.masscenter.pos_from(P.masscenter) == N.x + A.y + assert C.masscenter.vel(N) == u * A.z + assert P.masscenter.vel(Pint) == Vector(0) + assert C.masscenter.vel(Pint) == u * A.z + # Check only child_interframe + N, A, P, C = _generate_body() + Cint = ReferenceFrame('Cint') + Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz') + PinJoint('J', P, C, q, u, parent_point=-N.z, child_point=C.x, + child_interframe=Cint, joint_axis=P.x + P.z) + assert _simplify_matrix(N.dcm(A)) == Matrix([ + [-sqrt(2) * sin(q) / 2, + -sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4, + sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4], + [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4, + (-sqrt(2) + sqrt(6)) * sin(q) / 4], + [sqrt(2) * sin(q) / 2, + sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4, + sqrt(3) * (1 - cos(q)) / 4 + cos(q) / 4 + S(1) / 4]]) + assert A.ang_vel_in(N) == sqrt(2) * u / 2 * N.x + sqrt(2) * u / 2 * N.z + assert C.masscenter.pos_from(P.masscenter) == - N.z - A.x + assert C.masscenter.vel(N).simplify() == ( + -sqrt(6) - sqrt(2)) * u / 4 * A.y + ( + -sqrt(2) + sqrt(6)) * u / 4 * A.z + assert C.masscenter.vel(Cint) == Vector(0) + # Check combination + N, A, P, C = _generate_body() + Pint, Cint = ReferenceFrame('Pint'), ReferenceFrame('Cint') + Pint.orient_body_fixed(N, (-pi / 2, pi, pi / 2), 'xyz') + Cint.orient_body_fixed(A, (2 * pi / 3, -pi, pi / 2), 'xyz') + PinJoint('J', P, C, q, u, parent_point=N.x - N.y, child_point=-C.z, + parent_interframe=Pint, child_interframe=Cint, + joint_axis=Pint.x + Pint.z) + assert _simplify_matrix(N.dcm(A)) == Matrix([ + [cos(q), (sqrt(2) + sqrt(6)) * -sin(q) / 4, + (-sqrt(2) + sqrt(6)) * sin(q) / 4], + [-sqrt(2) * sin(q) / 2, + -sqrt(3) * (cos(q) + 1) / 4 - cos(q) / 4 + S(1) / 4, + sqrt(3) * (cos(q) - 1) / 4 - cos(q) / 4 - S(1) / 4], + [sqrt(2) * sin(q) / 2, + sqrt(3) * (cos(q) - 1) / 4 + cos(q) / 4 + S(1) / 4, + -sqrt(3) * (cos(q) + 1) / 4 + cos(q) / 4 - S(1) / 4]]) + assert A.ang_vel_in(N) == sqrt(2) * u / 2 * Pint.x + sqrt( + 2) * u / 2 * Pint.z + assert C.masscenter.pos_from(P.masscenter) == N.x - N.y + A.z + N_v_C = (-sqrt(2) + sqrt(6)) * u / 4 * A.x + assert C.masscenter.vel(N).simplify() == N_v_C + assert C.masscenter.vel(Pint).simplify() == N_v_C + assert C.masscenter.vel(Cint) == Vector(0) + + +def test_pin_joint_joint_axis(): + q, u = dynamicsymbols('q, u') + # Check parent as reference + N, A, P, C, Pint, Cint = _generate_body(True) + pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, + child_interframe=Cint, joint_axis=P.y) + assert pin.joint_axis == P.y + assert N.dcm(A) == Matrix([[sin(q), 0, cos(q)], [0, -1, 0], + [cos(q), 0, -sin(q)]]) + # Check parent_interframe as reference + N, A, P, C, Pint, Cint = _generate_body(True) + pin = PinJoint('J', P, C, q, u, parent_interframe=Pint, + child_interframe=Cint, joint_axis=Pint.y) + assert pin.joint_axis == Pint.y + assert N.dcm(A) == Matrix([[-sin(q), 0, cos(q)], [0, -1, 0], + [cos(q), 0, sin(q)]]) + # Check combination of joint_axis with interframes supplied as vectors (2x) + N, A, P, C = _generate_body() + pin = PinJoint('J', P, C, q, u, parent_interframe=N.z, + child_interframe=-C.z, joint_axis=N.z) + assert pin.joint_axis == N.z + assert N.dcm(A) == Matrix([[-cos(q), -sin(q), 0], [-sin(q), cos(q), 0], + [0, 0, -1]]) + N, A, P, C = _generate_body() + pin = PinJoint('J', P, C, q, u, parent_interframe=N.z, + child_interframe=-C.z, joint_axis=N.x) + assert pin.joint_axis == N.x + assert N.dcm(A) == Matrix([[-1, 0, 0], [0, cos(q), sin(q)], + [0, sin(q), -cos(q)]]) + # Check time varying axis + N, A, P, C, Pint, Cint = _generate_body(True) + raises(ValueError, lambda: PinJoint('J', P, C, + joint_axis=cos(q) * N.x + sin(q) * N.y)) + # Check joint_axis provided in child frame + raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=C.x)) + # Check some invalid combinations + raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=P.x + C.y)) + raises(ValueError, lambda: PinJoint( + 'J', P, C, parent_interframe=Pint, child_interframe=Cint, + joint_axis=Pint.x + C.y)) + raises(ValueError, lambda: PinJoint( + 'J', P, C, parent_interframe=Pint, child_interframe=Cint, + joint_axis=P.x + Cint.y)) + # Check valid special combination + N, A, P, C, Pint, Cint = _generate_body(True) + PinJoint('J', P, C, parent_interframe=Pint, child_interframe=Cint, + joint_axis=Pint.x + P.y) + # Check invalid zero vector + raises(Exception, lambda: PinJoint( + 'J', P, C, parent_interframe=Pint, child_interframe=Cint, + joint_axis=Vector(0))) + raises(Exception, lambda: PinJoint( + 'J', P, C, parent_interframe=Pint, child_interframe=Cint, + joint_axis=P.y + Pint.y)) + + +def test_pin_joint_arbitrary_axis(): + q, u = dynamicsymbols('q_J, u_J') + + # When the bodies are attached though masscenters but axes are opposite. + N, A, P, C = _generate_body() + PinJoint('J', P, C, child_interframe=-A.x) + + assert (-A.x).angle_between(N.x) == 0 + assert -A.x.express(N) == N.x + assert A.dcm(N) == Matrix([[-1, 0, 0], + [0, -cos(q), -sin(q)], + [0, -sin(q), cos(q)]]) + assert A.ang_vel_in(N) == u*N.x + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + assert C.masscenter.pos_from(P.masscenter) == 0 + assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == 0 + assert C.masscenter.vel(N) == 0 + + # When axes are different and parent joint is at masscenter but child joint + # is at a unit vector from child masscenter. + N, A, P, C = _generate_body() + PinJoint('J', P, C, child_interframe=A.y, child_point=A.x) + + assert A.y.angle_between(N.x) == 0 # Axis are aligned + assert A.y.express(N) == N.x + assert A.dcm(N) == Matrix([[0, -cos(q), -sin(q)], + [1, 0, 0], + [0, -sin(q), cos(q)]]) + assert A.ang_vel_in(N) == u*N.x + assert A.ang_vel_in(N).express(A) == u * A.y + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + assert A.ang_vel_in(N).cross(A.y) == 0 + assert C.masscenter.vel(N) == u*A.z + assert C.masscenter.pos_from(P.masscenter) == -A.x + assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == + cos(q)*N.y + sin(q)*N.z) + assert C.masscenter.vel(N).angle_between(A.x) == pi/2 + + # Similar to previous case but wrt parent body + N, A, P, C = _generate_body() + PinJoint('J', P, C, parent_interframe=N.y, parent_point=N.x) + + assert N.y.angle_between(A.x) == 0 # Axis are aligned + assert N.y.express(A) == A.x + assert A.dcm(N) == Matrix([[0, 1, 0], + [-cos(q), 0, sin(q)], + [sin(q), 0, cos(q)]]) + assert A.ang_vel_in(N) == u*N.y + assert A.ang_vel_in(N).express(A) == u*A.x + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + angle = A.ang_vel_in(N).angle_between(A.x) + assert angle.xreplace({u: 1}) == 0 + assert C.masscenter.vel(N) == 0 + assert C.masscenter.pos_from(P.masscenter) == N.x + + # Both joint pos id defined but different axes + N, A, P, C = _generate_body() + PinJoint('J', P, C, parent_point=N.x, child_point=A.x, + child_interframe=A.x + A.y) + assert expand_mul(N.x.angle_between(A.x + A.y)) == 0 # Axis are aligned + assert (A.x + A.y).express(N).simplify() == sqrt(2)*N.x + assert _simplify_matrix(A.dcm(N)) == Matrix([ + [sqrt(2)/2, -sqrt(2)*cos(q)/2, -sqrt(2)*sin(q)/2], + [sqrt(2)/2, sqrt(2)*cos(q)/2, sqrt(2)*sin(q)/2], + [0, -sin(q), cos(q)]]) + assert A.ang_vel_in(N) == u*N.x + assert (A.ang_vel_in(N).express(A).simplify() == + (u*A.x + u*A.y)/sqrt(2)) + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + angle = A.ang_vel_in(N).angle_between(A.x + A.y) + assert angle.xreplace({u: 1}) == 0 + assert C.masscenter.vel(N).simplify() == (u * A.z)/sqrt(2) + assert C.masscenter.pos_from(P.masscenter) == N.x - A.x + assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == + (1 - sqrt(2)/2)*N.x + sqrt(2)*cos(q)/2*N.y + + sqrt(2)*sin(q)/2*N.z) + assert (C.masscenter.vel(N).express(N).simplify() == + -sqrt(2)*u*sin(q)/2*N.y + sqrt(2)*u*cos(q)/2*N.z) + assert C.masscenter.vel(N).angle_between(A.x) == pi/2 + + N, A, P, C = _generate_body() + PinJoint('J', P, C, parent_point=N.x, child_point=A.x, + child_interframe=A.x + A.y - A.z) + assert expand_mul(N.x.angle_between(A.x + A.y - A.z)) == 0 # Axis aligned + assert (A.x + A.y - A.z).express(N).simplify() == sqrt(3)*N.x + assert _simplify_matrix(A.dcm(N)) == Matrix([ + [sqrt(3)/3, -sqrt(6)*sin(q + pi/4)/3, + sqrt(6)*cos(q + pi/4)/3], + [sqrt(3)/3, sqrt(6)*cos(q + pi/12)/3, + sqrt(6)*sin(q + pi/12)/3], + [-sqrt(3)/3, sqrt(6)*cos(q + 5*pi/12)/3, + sqrt(6)*sin(q + 5*pi/12)/3]]) + assert A.ang_vel_in(N) == u*N.x + assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y - + u*A.z)/sqrt(3) + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + angle = A.ang_vel_in(N).angle_between(A.x + A.y-A.z) + assert angle.xreplace({u: 1}) == 0 + assert C.masscenter.vel(N).simplify() == (u*A.y + u*A.z)/sqrt(3) + assert C.masscenter.pos_from(P.masscenter) == N.x - A.x + assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == + (1 - sqrt(3)/3)*N.x + sqrt(6)*sin(q + pi/4)/3*N.y - + sqrt(6)*cos(q + pi/4)/3*N.z) + assert (C.masscenter.vel(N).express(N).simplify() == + sqrt(6)*u*cos(q + pi/4)/3*N.y + + sqrt(6)*u*sin(q + pi/4)/3*N.z) + assert C.masscenter.vel(N).angle_between(A.x) == pi/2 + + N, A, P, C = _generate_body() + m, n = symbols('m n') + PinJoint('J', P, C, parent_point=m * N.x, child_point=n * A.x, + child_interframe=A.x + A.y - A.z, + parent_interframe=N.x - N.y + N.z) + angle = (N.x - N.y + N.z).angle_between(A.x + A.y - A.z) + assert expand_mul(angle) == 0 # Axis are aligned + assert ((A.x-A.y+A.z).express(N).simplify() == + (-4*cos(q)/3 - S(1)/3)*N.x + (S(1)/3 - 4*sin(q + pi/6)/3)*N.y + + (4*cos(q + pi/3)/3 - S(1)/3)*N.z) + assert _simplify_matrix(A.dcm(N)) == Matrix([ + [S(1)/3 - 2*cos(q)/3, -2*sin(q + pi/6)/3 - S(1)/3, + 2*cos(q + pi/3)/3 + S(1)/3], + [2*cos(q + pi/3)/3 + S(1)/3, 2*cos(q)/3 - S(1)/3, + 2*sin(q + pi/6)/3 + S(1)/3], + [-2*sin(q + pi/6)/3 - S(1)/3, 2*cos(q + pi/3)/3 + S(1)/3, + 2*cos(q)/3 - S(1)/3]]) + assert A.ang_vel_in(N) == (u*N.x - u*N.y + u*N.z)/sqrt(3) + assert A.ang_vel_in(N).express(A).simplify() == (u*A.x + u*A.y - + u*A.z)/sqrt(3) + assert A.ang_vel_in(N).magnitude() == sqrt(u**2) + angle = A.ang_vel_in(N).angle_between(A.x+A.y-A.z) + assert angle.xreplace({u: 1}) == 0 + assert (C.masscenter.vel(N).simplify() == + sqrt(3)*n*u/3*A.y + sqrt(3)*n*u/3*A.z) + assert C.masscenter.pos_from(P.masscenter) == m*N.x - n*A.x + assert (C.masscenter.pos_from(P.masscenter).express(N).simplify() == + (m + n*(2*cos(q) - 1)/3)*N.x + n*(2*sin(q + pi/6) + + 1)/3*N.y - n*(2*cos(q + pi/3) + 1)/3*N.z) + assert (C.masscenter.vel(N).express(N).simplify() == + - 2*n*u*sin(q)/3*N.x + 2*n*u*cos(q + pi/6)/3*N.y + + 2*n*u*sin(q + pi/3)/3*N.z) + assert C.masscenter.vel(N).dot(N.x - N.y + N.z).simplify() == 0 + + +def test_create_aligned_frame_pi(): + N, A, P, C = _generate_body() + f = Joint._create_aligned_interframe(P, -P.x, P.x) + assert f.z == P.z + f = Joint._create_aligned_interframe(P, -P.y, P.y) + assert f.x == P.x + f = Joint._create_aligned_interframe(P, -P.z, P.z) + assert f.y == P.y + f = Joint._create_aligned_interframe(P, -P.x - P.y, P.x + P.y) + assert f.z == P.z + f = Joint._create_aligned_interframe(P, -P.y - P.z, P.y + P.z) + assert f.x == P.x + f = Joint._create_aligned_interframe(P, -P.x - P.z, P.x + P.z) + assert f.y == P.y + f = Joint._create_aligned_interframe(P, -P.x - P.y - P.z, P.x + P.y + P.z) + assert f.y - f.z == P.y - P.z + + +def test_pin_joint_axis(): + q, u = dynamicsymbols('q u') + # Test default joint axis + N, A, P, C, Pint, Cint = _generate_body(True) + J = PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint) + assert J.joint_axis == Pint.x + # Test for the same joint axis expressed in different frames + N_R_A = Matrix([[0, sin(q), cos(q)], + [0, -cos(q), sin(q)], + [1, 0, 0]]) + N, A, P, C, Pint, Cint = _generate_body(True) + PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, + joint_axis=N.z) + assert N.dcm(A) == N_R_A + N, A, P, C, Pint, Cint = _generate_body(True) + PinJoint('J', P, C, q, u, parent_interframe=Pint, child_interframe=Cint, + joint_axis=-Pint.z) + assert N.dcm(A) == N_R_A + # Test time varying joint axis + N, A, P, C, Pint, Cint = _generate_body(True) + raises(ValueError, lambda: PinJoint('J', P, C, joint_axis=q * N.z)) + + +def test_locate_joint_pos(): + # Test Vector and default + N, A, P, C = _generate_body() + joint = PinJoint('J', P, C, parent_point=N.y + N.z) + assert joint.parent_point.name == 'J_P_joint' + assert joint.parent_point.pos_from(P.masscenter) == N.y + N.z + assert joint.child_point == C.masscenter + # Test Point objects + N, A, P, C = _generate_body() + parent_point = P.masscenter.locatenew('p', N.y + N.z) + joint = PinJoint('J', P, C, parent_point=parent_point, + child_point=C.masscenter) + assert joint.parent_point == parent_point + assert joint.child_point == C.masscenter + # Check invalid type + N, A, P, C = _generate_body() + raises(TypeError, + lambda: PinJoint('J', P, C, parent_point=N.x.to_matrix(N))) + # Test time varying positions + q = dynamicsymbols('q') + N, A, P, C = _generate_body() + raises(ValueError, lambda: PinJoint('J', P, C, parent_point=q * N.x)) + N, A, P, C = _generate_body() + child_point = C.masscenter.locatenew('p', q * A.y) + raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point)) + # Test undefined position + child_point = Point('p') + raises(ValueError, lambda: PinJoint('J', P, C, child_point=child_point)) + + +def test_locate_joint_frame(): + # Test rotated frame and default + N, A, P, C = _generate_body() + parent_interframe = ReferenceFrame('int_frame') + parent_interframe.orient_axis(N, N.z, 1) + joint = PinJoint('J', P, C, parent_interframe=parent_interframe) + assert joint.parent_interframe == parent_interframe + assert joint.parent_interframe.ang_vel_in(N) == 0 + assert joint.child_interframe == A + # Test time varying orientations + q = dynamicsymbols('q') + N, A, P, C = _generate_body() + parent_interframe = ReferenceFrame('int_frame') + parent_interframe.orient_axis(N, N.z, q) + raises(ValueError, + lambda: PinJoint('J', P, C, parent_interframe=parent_interframe)) + # Test undefined frame + N, A, P, C = _generate_body() + child_interframe = ReferenceFrame('int_frame') + child_interframe.orient_axis(N, N.z, 1) # Defined with respect to parent + raises(ValueError, + lambda: PinJoint('J', P, C, child_interframe=child_interframe)) + + +def test_sliding_joint(): + _, _, P, C = _generate_body() + q, u = dynamicsymbols('q_S, u_S') + S = PrismaticJoint('S', P, C) + assert S.name == 'S' + assert S.parent == P + assert S.child == C + assert S.coordinates == Matrix([q]) + assert S.speeds == Matrix([u]) + assert S.kdes == Matrix([u - q.diff(t)]) + assert S.joint_axis == P.frame.x + assert S.child_point.pos_from(C.masscenter) == Vector(0) + assert S.parent_point.pos_from(P.masscenter) == Vector(0) + assert S.parent_point.pos_from(S.child_point) == - q * P.frame.x + assert P.masscenter.pos_from(C.masscenter) == - q * P.frame.x + assert C.masscenter.vel(P.frame) == u * P.frame.x + assert P.ang_vel_in(C) == 0 + assert C.ang_vel_in(P) == 0 + assert S.__str__() == 'PrismaticJoint: S parent: P child: C' + + N, A, P, C = _generate_body() + l, m = symbols('l m') + Pint = ReferenceFrame('P_int') + Pint.orient_axis(P.frame, P.y, pi / 2) + S = PrismaticJoint('S', P, C, parent_point=l * P.frame.x, + child_point=m * C.frame.y, joint_axis=P.frame.z, + parent_interframe=Pint) + + assert S.joint_axis == P.frame.z + assert S.child_point.pos_from(C.masscenter) == m * C.frame.y + assert S.parent_point.pos_from(P.masscenter) == l * P.frame.x + assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z + assert P.masscenter.pos_from(C.masscenter) == - l*N.x - q*N.z + m*A.y + assert C.masscenter.vel(P.frame) == u * P.frame.z + assert P.masscenter.vel(Pint) == Vector(0) + assert C.ang_vel_in(P) == 0 + assert P.ang_vel_in(C) == 0 + + _, _, P, C = _generate_body() + Pint = ReferenceFrame('P_int') + Pint.orient_axis(P.frame, P.y, pi / 2) + S = PrismaticJoint('S', P, C, parent_point=l * P.frame.z, + child_point=m * C.frame.x, joint_axis=P.frame.z, + parent_interframe=Pint) + assert S.joint_axis == P.frame.z + assert S.child_point.pos_from(C.masscenter) == m * C.frame.x + assert S.parent_point.pos_from(P.masscenter) == l * P.frame.z + assert S.parent_point.pos_from(S.child_point) == - q * P.frame.z + assert P.masscenter.pos_from(C.masscenter) == (-l - q)*P.frame.z + m*C.frame.x + assert C.masscenter.vel(P.frame) == u * P.frame.z + assert C.ang_vel_in(P) == 0 + assert P.ang_vel_in(C) == 0 + + +def test_sliding_joint_arbitrary_axis(): + q, u = dynamicsymbols('q_S, u_S') + + N, A, P, C = _generate_body() + PrismaticJoint('S', P, C, child_interframe=-A.x) + + assert (-A.x).angle_between(N.x) == 0 + assert -A.x.express(N) == N.x + assert A.dcm(N) == Matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]]) + assert C.masscenter.pos_from(P.masscenter) == q * N.x + assert C.masscenter.pos_from(P.masscenter).express(A).simplify() == -q * A.x + assert C.masscenter.vel(N) == u * N.x + assert C.masscenter.vel(N).express(A) == -u * A.x + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + #When axes are different and parent joint is at masscenter but child joint is at a unit vector from + #child masscenter. + N, A, P, C = _generate_body() + PrismaticJoint('S', P, C, child_interframe=A.y, child_point=A.x) + + assert A.y.angle_between(N.x) == 0 #Axis are aligned + assert A.y.express(N) == N.x + assert A.dcm(N) == Matrix([[0, -1, 0], [1, 0, 0], [0, 0, 1]]) + assert C.masscenter.vel(N) == u * N.x + assert C.masscenter.vel(N).express(A) == u * A.y + assert C.masscenter.pos_from(P.masscenter) == q*N.x - A.x + assert C.masscenter.pos_from(P.masscenter).express(N).simplify() == q*N.x + N.y + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + #Similar to previous case but wrt parent body + N, A, P, C = _generate_body() + PrismaticJoint('S', P, C, parent_interframe=N.y, parent_point=N.x) + + assert N.y.angle_between(A.x) == 0 #Axis are aligned + assert N.y.express(A) == A.x + assert A.dcm(N) == Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 1]]) + assert C.masscenter.vel(N) == u * N.y + assert C.masscenter.vel(N).express(A) == u * A.x + assert C.masscenter.pos_from(P.masscenter) == N.x + q*N.y + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + #Both joint pos is defined but different axes + N, A, P, C = _generate_body() + PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x, + child_interframe=A.x + A.y) + assert N.x.angle_between(A.x + A.y) == 0 #Axis are aligned + assert (A.x + A.y).express(N) == sqrt(2)*N.x + assert A.dcm(N) == Matrix([[sqrt(2)/2, -sqrt(2)/2, 0], [sqrt(2)/2, sqrt(2)/2, 0], [0, 0, 1]]) + assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x + assert C.masscenter.pos_from(P.masscenter).express(N) == (q - sqrt(2)/2 + 1)*N.x + sqrt(2)/2*N.y + assert C.masscenter.vel(N).express(A) == u * (A.x + A.y)/sqrt(2) + assert C.masscenter.vel(N) == u*N.x + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + N, A, P, C = _generate_body() + PrismaticJoint('S', P, C, parent_point=N.x, child_point=A.x, + child_interframe=A.x + A.y - A.z) + assert N.x.angle_between(A.x + A.y - A.z) == 0 #Axis are aligned + assert (A.x + A.y - A.z).express(N) == sqrt(3)*N.x + assert _simplify_matrix(A.dcm(N)) == Matrix([[sqrt(3)/3, -sqrt(3)/3, sqrt(3)/3], + [sqrt(3)/3, sqrt(3)/6 + S(1)/2, S(1)/2 - sqrt(3)/6], + [-sqrt(3)/3, S(1)/2 - sqrt(3)/6, sqrt(3)/6 + S(1)/2]]) + assert C.masscenter.pos_from(P.masscenter) == (q + 1)*N.x - A.x + assert C.masscenter.pos_from(P.masscenter).express(N) == \ + (q - sqrt(3)/3 + 1)*N.x + sqrt(3)/3*N.y - sqrt(3)/3*N.z + assert C.masscenter.vel(N) == u*N.x + 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 + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + N, A, P, C = _generate_body() + m, n = symbols('m n') + PrismaticJoint('S', P, C, parent_point=m*N.x, child_point=n*A.x, + child_interframe=A.x + A.y - A.z, + parent_interframe=N.x - N.y + N.z) + # 0 angle means that the axis are aligned + assert (N.x-N.y+N.z).angle_between(A.x+A.y-A.z).simplify() == 0 + assert (A.x+A.y-A.z).express(N) == N.x - N.y + N.z + assert _simplify_matrix(A.dcm(N)) == Matrix([[-S(1)/3, -S(2)/3, S(2)/3], + [S(2)/3, S(1)/3, S(2)/3], + [-S(2)/3, S(2)/3, S(1)/3]]) + assert C.masscenter.pos_from(P.masscenter) == \ + (m + sqrt(3)*q/3)*N.x - sqrt(3)*q/3*N.y + sqrt(3)*q/3*N.z - n*A.x + assert C.masscenter.pos_from(P.masscenter).express(N) == \ + (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 + assert C.masscenter.vel(N) == sqrt(3)*u/3*N.x - sqrt(3)*u/3*N.y + sqrt(3)*u/3*N.z + 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 + assert A.ang_vel_in(N) == 0 + assert N.ang_vel_in(A) == 0 + + +def test_cylindrical_joint(): + N, A, P, C = _generate_body() + q0_def, q1_def, u0_def, u1_def = dynamicsymbols('q0:2_J, u0:2_J') + Cj = CylindricalJoint('J', P, C) + assert Cj.name == 'J' + assert Cj.parent == P + assert Cj.child == C + assert Cj.coordinates == Matrix([q0_def, q1_def]) + assert Cj.speeds == Matrix([u0_def, u1_def]) + assert Cj.rotation_coordinate == q0_def + assert Cj.translation_coordinate == q1_def + assert Cj.rotation_speed == u0_def + assert Cj.translation_speed == u1_def + assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t)]) + assert Cj.joint_axis == N.x + assert Cj.child_point.pos_from(C.masscenter) == Vector(0) + assert Cj.parent_point.pos_from(P.masscenter) == Vector(0) + assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.x + assert C.masscenter.pos_from(P.masscenter) == q1_def * N.x + assert Cj.child_point.vel(N) == u1_def * N.x + assert A.ang_vel_in(N) == u0_def * N.x + assert Cj.parent_interframe == N + assert Cj.child_interframe == A + assert Cj.__str__() == 'CylindricalJoint: J parent: P child: C' + + q0, q1, u0, u1 = dynamicsymbols('q0:2, u0:2') + l, m = symbols('l, m') + N, A, P, C, Pint, Cint = _generate_body(True) + Cj = CylindricalJoint('J', P, C, rotation_coordinate=q0, rotation_speed=u0, + translation_speed=u1, parent_point=m * N.x, + child_point=l * A.y, parent_interframe=Pint, + child_interframe=Cint, joint_axis=2 * N.z) + assert Cj.coordinates == Matrix([q0, q1_def]) + assert Cj.speeds == Matrix([u0, u1]) + assert Cj.rotation_coordinate == q0 + assert Cj.translation_coordinate == q1_def + assert Cj.rotation_speed == u0 + assert Cj.translation_speed == u1 + assert Cj.kdes == Matrix([u0 - q0.diff(t), u1 - q1_def.diff(t)]) + assert Cj.joint_axis == 2 * N.z + assert Cj.child_point.pos_from(C.masscenter) == l * A.y + assert Cj.parent_point.pos_from(P.masscenter) == m * N.x + assert Cj.parent_point.pos_from(Cj._child_point) == -q1_def * N.z + assert C.masscenter.pos_from( + P.masscenter) == m * N.x + q1_def * N.z - l * A.y + assert C.masscenter.vel(N) == u1 * N.z - u0 * l * A.z + assert A.ang_vel_in(N) == u0 * N.z + + +def test_planar_joint(): + N, A, P, C = _generate_body() + q0_def, q1_def, q2_def = dynamicsymbols('q0:3_J') + u0_def, u1_def, u2_def = dynamicsymbols('u0:3_J') + Cj = PlanarJoint('J', P, C) + assert Cj.name == 'J' + assert Cj.parent == P + assert Cj.child == C + assert Cj.coordinates == Matrix([q0_def, q1_def, q2_def]) + assert Cj.speeds == Matrix([u0_def, u1_def, u2_def]) + assert Cj.rotation_coordinate == q0_def + assert Cj.planar_coordinates == Matrix([q1_def, q2_def]) + assert Cj.rotation_speed == u0_def + assert Cj.planar_speeds == Matrix([u1_def, u2_def]) + assert Cj.kdes == Matrix([u0_def - q0_def.diff(t), u1_def - q1_def.diff(t), + u2_def - q2_def.diff(t)]) + assert Cj.rotation_axis == N.x + assert Cj.planar_vectors == [N.y, N.z] + assert Cj.child_point.pos_from(C.masscenter) == Vector(0) + assert Cj.parent_point.pos_from(P.masscenter) == Vector(0) + r_P_C = q1_def * N.y + q2_def * N.z + assert Cj.parent_point.pos_from(Cj.child_point) == -r_P_C + assert C.masscenter.pos_from(P.masscenter) == r_P_C + assert Cj.child_point.vel(N) == u1_def * N.y + u2_def * N.z + assert A.ang_vel_in(N) == u0_def * N.x + assert Cj.parent_interframe == N + assert Cj.child_interframe == A + assert Cj.__str__() == 'PlanarJoint: J parent: P child: C' + + q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3') + l, m = symbols('l, m') + N, A, P, C, Pint, Cint = _generate_body(True) + Cj = PlanarJoint('J', P, C, rotation_coordinate=q0, + planar_coordinates=[q1, q2], planar_speeds=[u1, u2], + parent_point=m * N.x, child_point=l * A.y, + parent_interframe=Pint, child_interframe=Cint) + assert Cj.coordinates == Matrix([q0, q1, q2]) + assert Cj.speeds == Matrix([u0_def, u1, u2]) + assert Cj.rotation_coordinate == q0 + assert Cj.planar_coordinates == Matrix([q1, q2]) + assert Cj.rotation_speed == u0_def + assert Cj.planar_speeds == Matrix([u1, u2]) + assert Cj.kdes == Matrix([u0_def - q0.diff(t), u1 - q1.diff(t), + u2 - q2.diff(t)]) + assert Cj.rotation_axis == Pint.x + assert Cj.planar_vectors == [Pint.y, Pint.z] + assert Cj.child_point.pos_from(C.masscenter) == l * A.y + assert Cj.parent_point.pos_from(P.masscenter) == m * N.x + assert Cj.parent_point.pos_from(Cj.child_point) == q1 * N.y + q2 * N.z + assert C.masscenter.pos_from( + P.masscenter) == m * N.x - q1 * N.y - q2 * N.z - l * A.y + assert C.masscenter.vel(N) == -u1 * N.y - u2 * N.z + u0_def * l * A.x + assert A.ang_vel_in(N) == u0_def * N.x + + +def test_planar_joint_advanced(): + # Tests whether someone is able to just specify two normals, which will form + # the rotation axis seen from the parent and child body. + # This specific example is a block on a slope, which has that same slope of + # 30 degrees, so in the zero configuration the frames of the parent and + # child are actually aligned. + q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3') + l1, l2 = symbols('l1:3') + N, A, P, C = _generate_body() + J = PlanarJoint('J', P, C, q0, [q1, q2], u0, [u1, u2], + parent_point=l1 * N.z, + child_point=-l2 * C.z, + parent_interframe=N.z + N.y / sqrt(3), + child_interframe=A.z + A.y / sqrt(3)) + assert J.rotation_axis.express(N) == (N.z + N.y / sqrt(3)).normalize() + assert J.rotation_axis.express(A) == (A.z + A.y / sqrt(3)).normalize() + assert J.rotation_axis.angle_between(N.z) == pi / 6 + assert N.dcm(A).xreplace({q0: 0, q1: 0, q2: 0}) == eye(3) + N_R_A = Matrix([ + [cos(q0), -sqrt(3) * sin(q0) / 2, sin(q0) / 2], + [sqrt(3) * sin(q0) / 2, 3 * cos(q0) / 4 + 1 / 4, + sqrt(3) * (1 - cos(q0)) / 4], + [-sin(q0) / 2, sqrt(3) * (1 - cos(q0)) / 4, cos(q0) / 4 + 3 / 4]]) + # N.dcm(A) == N_R_A did not work + assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3) + + +def test_spherical_joint(): + N, A, P, C = _generate_body() + q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3_S, u0:3_S') + S = SphericalJoint('S', P, C) + assert S.name == 'S' + assert S.parent == P + assert S.child == C + assert S.coordinates == Matrix([q0, q1, q2]) + assert S.speeds == Matrix([u0, u1, u2]) + assert S.kdes == Matrix([u0 - q0.diff(t), u1 - q1.diff(t), u2 - q2.diff(t)]) + assert S.child_point.pos_from(C.masscenter) == Vector(0) + assert S.parent_point.pos_from(P.masscenter) == Vector(0) + assert S.parent_point.pos_from(S.child_point) == Vector(0) + assert P.masscenter.pos_from(C.masscenter) == Vector(0) + assert C.masscenter.vel(N) == Vector(0) + assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + ( + u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + ( + -u0 * sin(q1) - u2) * A.z + assert C.ang_vel_in(P) == (u0 * cos(q1) * cos(q2) + u1 * sin(q2)) * A.x + ( + -u0 * sin(q2) * cos(q1) + u1 * cos(q2)) * A.y + ( + u0 * sin(q1) + u2) * A.z + assert S.__str__() == 'SphericalJoint: S parent: P child: C' + assert S._rot_type == 'BODY' + assert S._rot_order == 123 + assert S._amounts is None + + +def test_spherical_joint_speeds_as_derivative_terms(): + # This tests checks whether the system remains valid if the user chooses to + # pass the derivative of the generalized coordinates as generalized speeds + q0, q1, q2 = dynamicsymbols('q0:3') + u0, u1, u2 = dynamicsymbols('q0:3', 1) + N, A, P, C = _generate_body() + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2]) + assert S.coordinates == Matrix([q0, q1, q2]) + assert S.speeds == Matrix([u0, u1, u2]) + assert S.kdes == Matrix([0, 0, 0]) + assert P.ang_vel_in(C) == (-u0 * cos(q1) * cos(q2) - u1 * sin(q2)) * A.x + ( + u0 * sin(q2) * cos(q1) - u1 * cos(q2)) * A.y + ( + -u0 * sin(q1) - u2) * A.z + + +def test_spherical_joint_coords(): + q0s, q1s, q2s, u0s, u1s, u2s = dynamicsymbols('q0:3_S, u0:3_S') + q0, q1, q2, q3, u0, u1, u2, u4 = dynamicsymbols('q0:4, u0:4') + # Test coordinates as list + N, A, P, C = _generate_body() + S = SphericalJoint('S', P, C, [q0, q1, q2], [u0, u1, u2]) + assert S.coordinates == Matrix([q0, q1, q2]) + assert S.speeds == Matrix([u0, u1, u2]) + # Test coordinates as Matrix + N, A, P, C = _generate_body() + S = SphericalJoint('S', P, C, Matrix([q0, q1, q2]), + Matrix([u0, u1, u2])) + assert S.coordinates == Matrix([q0, q1, q2]) + assert S.speeds == Matrix([u0, u1, u2]) + # Test too few generalized coordinates + N, A, P, C = _generate_body() + raises(ValueError, + lambda: SphericalJoint('S', P, C, Matrix([q0, q1]), Matrix([u0]))) + # Test too many generalized coordinates + raises(ValueError, lambda: SphericalJoint( + 'S', P, C, Matrix([q0, q1, q2, q3]), Matrix([u0, u1, u2]))) + raises(ValueError, lambda: SphericalJoint( + 'S', P, C, Matrix([q0, q1, q2]), Matrix([u0, u1, u2, u4]))) + + +def test_spherical_joint_orient_body(): + q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3') + N_R_A = Matrix([ + [-sin(q1), -sin(q2) * cos(q1), cos(q1) * cos(q2)], + [-sin(q0) * cos(q1), sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2), + -sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0)], + [cos(q0) * cos(q1), -sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0), + -sin(q0) * sin(q2) + sin(q1) * cos(q0) * cos(q2)]]) + N_w_A = Matrix([[-u0 * sin(q1) - u2], + [-u0 * sin(q2) * cos(q1) + u1 * cos(q2)], + [u0 * cos(q1) * cos(q2) + u1 * sin(q2)]]) + N_v_Co = Matrix([ + [-sqrt(2) * (u0 * cos(q2 + pi / 4) * cos(q1) + u1 * sin(q2 + pi / 4))], + [-u0 * sin(q1) - u2], [-u0 * sin(q1) - u2]]) + # Test default rot_type='BODY', rot_order=123 + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.y, child_point=-A.y + A.z, + parent_interframe=Pint, child_interframe=Cint, + rot_type='body', rot_order=123) + assert S._rot_type.upper() == 'BODY' + assert S._rot_order == 123 + assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3) + assert A.ang_vel_in(N).to_matrix(A) == N_w_A + assert C.masscenter.vel(N).to_matrix(A) == N_v_Co + # Test change of amounts + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.y, child_point=-A.y + A.z, + parent_interframe=Pint, child_interframe=Cint, + rot_type='BODY', amounts=(q1, q0, q2), rot_order=123) + switch_order = lambda expr: expr.xreplace( + {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2}) + assert S._rot_type.upper() == 'BODY' + assert S._rot_order == 123 + assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3) + assert A.ang_vel_in(N).to_matrix(A) == switch_order(N_w_A) + assert C.masscenter.vel(N).to_matrix(A) == switch_order(N_v_Co) + # Test different rot_order + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.y, child_point=-A.y + A.z, + parent_interframe=Pint, child_interframe=Cint, + rot_type='BodY', rot_order='yxz') + assert S._rot_type.upper() == 'BODY' + assert S._rot_order == 'yxz' + assert _simplify_matrix(N.dcm(A) - Matrix([ + [-sin(q0) * cos(q1), sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0), + sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)], + [-sin(q1), -cos(q1) * cos(q2), -sin(q2) * cos(q1)], + [cos(q0) * cos(q1), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2), + sin(q0) * cos(q2) - sin(q1) * sin(q2) * cos(q0)]])) == zeros(3) + assert A.ang_vel_in(N).to_matrix(A) == Matrix([ + [u0 * sin(q1) - u2], [u0 * cos(q1) * cos(q2) - u1 * sin(q2)], + [u0 * sin(q2) * cos(q1) + u1 * cos(q2)]]) + assert C.masscenter.vel(N).to_matrix(A) == Matrix([ + [-sqrt(2) * (u0 * sin(q2 + pi / 4) * cos(q1) + u1 * cos(q2 + pi / 4))], + [u0 * sin(q1) - u2], [u0 * sin(q1) - u2]]) + + +def test_spherical_joint_orient_space(): + q0, q1, q2, u0, u1, u2 = dynamicsymbols('q0:3, u0:3') + N_R_A = Matrix([ + [-sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2), + sin(q0) * sin(q1) * cos(q2) - sin(q2) * cos(q0), cos(q1) * cos(q2)], + [-sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0), + -sin(q0) * sin(q1) * sin(q2) - cos(q0) * cos(q2), -sin(q2) * cos(q1)], + [cos(q0) * cos(q1), -sin(q0) * cos(q1), sin(q1)]]) + N_w_A = Matrix([ + [u1 * sin(q0) - u2 * cos(q0) * cos(q1)], + [u1 * cos(q0) + u2 * sin(q0) * cos(q1)], [u0 - u2 * sin(q1)]]) + N_v_Co = Matrix([ + [u0 - u2 * sin(q1)], [u0 - u2 * sin(q1)], + [sqrt(2) * (-u1 * sin(q0 + pi / 4) + u2 * cos(q0 + pi / 4) * cos(q1))]]) + # Test default rot_type='BODY', rot_order=123 + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.z, child_point=-A.x + A.y, + parent_interframe=Pint, child_interframe=Cint, + rot_type='space', rot_order=123) + assert S._rot_type.upper() == 'SPACE' + assert S._rot_order == 123 + assert _simplify_matrix(N.dcm(A) - N_R_A) == zeros(3) + assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == N_w_A + assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == N_v_Co + # Test change of amounts + switch_order = lambda expr: expr.xreplace( + {q0: q1, q1: q0, q2: q2, u0: u1, u1: u0, u2: u2}) + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.z, child_point=-A.x + A.y, + parent_interframe=Pint, child_interframe=Cint, + rot_type='SPACE', amounts=(q1, q0, q2), rot_order=123) + assert S._rot_type.upper() == 'SPACE' + assert S._rot_order == 123 + assert _simplify_matrix(N.dcm(A) - switch_order(N_R_A)) == zeros(3) + assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A)) == switch_order(N_w_A) + assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A)) == switch_order(N_v_Co) + # Test different rot_order + N, A, P, C, Pint, Cint = _generate_body(True) + S = SphericalJoint('S', P, C, coordinates=[q0, q1, q2], speeds=[u0, u1, u2], + parent_point=N.x + N.z, child_point=-A.x + A.y, + parent_interframe=Pint, child_interframe=Cint, + rot_type='SPaCe', rot_order='zxy') + assert S._rot_type.upper() == 'SPACE' + assert S._rot_order == 'zxy' + assert _simplify_matrix(N.dcm(A) - Matrix([ + [-sin(q2) * cos(q1), -sin(q0) * cos(q2) + sin(q1) * sin(q2) * cos(q0), + sin(q0) * sin(q1) * sin(q2) + cos(q0) * cos(q2)], + [-sin(q1), -cos(q0) * cos(q1), -sin(q0) * cos(q1)], + [cos(q1) * cos(q2), -sin(q0) * sin(q2) - sin(q1) * cos(q0) * cos(q2), + -sin(q0) * sin(q1) * cos(q2) + sin(q2) * cos(q0)]])) + assert _simplify_matrix(A.ang_vel_in(N).to_matrix(A) - Matrix([ + [-u0 + u2 * sin(q1)], [-u1 * sin(q0) + u2 * cos(q0) * cos(q1)], + [u1 * cos(q0) + u2 * sin(q0) * cos(q1)]])) == zeros(3, 1) + assert _simplify_matrix(C.masscenter.vel(N).to_matrix(A) - Matrix([ + [u1 * cos(q0) + u2 * sin(q0) * cos(q1)], + [u1 * cos(q0) + u2 * sin(q0) * cos(q1)], + [u0 + u1 * sin(q0) - u2 * sin(q1) - + u2 * cos(q0) * cos(q1)]])) == zeros(3, 1) + + +def test_weld_joint(): + _, _, P, C = _generate_body() + W = WeldJoint('W', P, C) + assert W.name == 'W' + assert W.parent == P + assert W.child == C + assert W.coordinates == Matrix() + assert W.speeds == Matrix() + assert W.kdes == Matrix(1, 0, []).T + assert P.dcm(C) == eye(3) + assert W.child_point.pos_from(C.masscenter) == Vector(0) + assert W.parent_point.pos_from(P.masscenter) == Vector(0) + assert W.parent_point.pos_from(W.child_point) == Vector(0) + assert P.masscenter.pos_from(C.masscenter) == Vector(0) + assert C.masscenter.vel(P.frame) == Vector(0) + assert P.ang_vel_in(C) == 0 + assert C.ang_vel_in(P) == 0 + assert W.__str__() == 'WeldJoint: W parent: P child: C' + + N, A, P, C = _generate_body() + l, m = symbols('l m') + Pint = ReferenceFrame('P_int') + Pint.orient_axis(P.frame, P.y, pi / 2) + W = WeldJoint('W', P, C, parent_point=l * P.frame.x, + child_point=m * C.frame.y, parent_interframe=Pint) + + assert W.child_point.pos_from(C.masscenter) == m * C.frame.y + assert W.parent_point.pos_from(P.masscenter) == l * P.frame.x + assert W.parent_point.pos_from(W.child_point) == Vector(0) + assert P.masscenter.pos_from(C.masscenter) == - l * N.x + m * A.y + assert C.masscenter.vel(P.frame) == Vector(0) + assert P.masscenter.vel(Pint) == Vector(0) + assert C.ang_vel_in(P) == 0 + assert P.ang_vel_in(C) == 0 + assert P.x == A.z + + JointsMethod(P, W) # Tests #10770 + + +def test_deprecated_parent_child_axis(): + q, u = dynamicsymbols('q_J, u_J') + N, A, P, C = _generate_body() + with warns_deprecated_sympy(): + PinJoint('J', P, C, child_axis=-A.x) + assert (-A.x).angle_between(N.x) == 0 + assert -A.x.express(N) == N.x + assert A.dcm(N) == Matrix([[-1, 0, 0], + [0, -cos(q), -sin(q)], + [0, -sin(q), cos(q)]]) + assert A.ang_vel_in(N) == u * N.x + assert A.ang_vel_in(N).magnitude() == sqrt(u ** 2) + + N, A, P, C = _generate_body() + with warns_deprecated_sympy(): + PrismaticJoint('J', P, C, parent_axis=P.x + P.y) + assert (A.x).angle_between(N.x + N.y) == 0 + assert A.x.express(N) == (N.x + N.y) / sqrt(2) + assert A.dcm(N) == Matrix([[sqrt(2) / 2, sqrt(2) / 2, 0], + [-sqrt(2) / 2, sqrt(2) / 2, 0], [0, 0, 1]]) + assert A.ang_vel_in(N) == Vector(0) + + +def test_deprecated_joint_pos(): + N, A, P, C = _generate_body() + with warns_deprecated_sympy(): + pin = PinJoint('J', P, C, parent_joint_pos=N.x + N.y, + child_joint_pos=C.y - C.z) + assert pin.parent_point.pos_from(P.masscenter) == N.x + N.y + assert pin.child_point.pos_from(C.masscenter) == C.y - C.z + + N, A, P, C = _generate_body() + with warns_deprecated_sympy(): + slider = PrismaticJoint('J', P, C, parent_joint_pos=N.z + N.y, + child_joint_pos=C.y - C.x) + assert slider.parent_point.pos_from(P.masscenter) == N.z + N.y + assert slider.child_point.pos_from(C.masscenter) == C.y - C.x diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d9a80f5a72717765bb7009520a787be9442fac --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_jointsmethod.py @@ -0,0 +1,212 @@ +from sympy.core.function import expand +from sympy.core.symbol import symbols +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.matrices.dense import Matrix +from sympy.simplify.trigsimp import trigsimp +from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod, + PrismaticJoint, LagrangesMethod, inertia) +from sympy.physics.vector import dynamicsymbols, ReferenceFrame +from sympy.testing.pytest import raises +from sympy.core.backend import zeros +from sympy.utilities.lambdify import lambdify +from sympy.solvers.solvers import solve + + +t = dynamicsymbols._t # type: ignore + + +def test_jointsmethod(): + P = Body('P') + C = Body('C') + Pin = PinJoint('P1', P, C) + C_ixx, g = symbols('C_ixx g') + q, u = dynamicsymbols('q_P1, u_P1') + P.apply_force(g*P.y) + method = JointsMethod(P, Pin) + assert method.frame == P.frame + assert method.bodies == [C, P] + assert method.loads == [(P.masscenter, g*P.frame.y)] + assert method.q == Matrix([q]) + assert method.u == Matrix([u]) + assert method.kdes == Matrix([u - q.diff()]) + soln = method.form_eoms() + assert soln == Matrix([[-C_ixx*u.diff()]]) + assert method.forcing_full == Matrix([[u], [0]]) + assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]]) + assert isinstance(method.method, KanesMethod) + +def test_jointmethod_duplicate_coordinates_speeds(): + P = Body('P') + C = Body('C') + T = Body('T') + q, u = dynamicsymbols('q u') + P1 = PinJoint('P1', P, C, q) + P2 = PrismaticJoint('P2', C, T, q) + raises(ValueError, lambda: JointsMethod(P, P1, P2)) + + P1 = PinJoint('P1', P, C, speeds=u) + P2 = PrismaticJoint('P2', C, T, speeds=u) + raises(ValueError, lambda: JointsMethod(P, P1, P2)) + + P1 = PinJoint('P1', P, C, q, u) + P2 = PrismaticJoint('P2', C, T, q, u) + raises(ValueError, lambda: JointsMethod(P, P1, P2)) + +def test_complete_simple_double_pendulum(): + q1, q2 = dynamicsymbols('q1 q2') + u1, u2 = dynamicsymbols('u1 u2') + m, l, g = symbols('m l g') + C = Body('C') # ceiling + PartP = Body('P', mass=m) + PartR = Body('R', mass=m) + J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1, + child_point=-l*PartP.x, joint_axis=C.z) + J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2, + child_point=-l*PartR.x, joint_axis=PartP.z) + + PartP.apply_force(m*g*C.x) + PartR.apply_force(m*g*C.x) + + method = JointsMethod(C, J1, J2) + method.form_eoms() + + assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m], + [0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]]) + assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) - + g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)], + [-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]])) + +def test_two_dof_joints(): + q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2') + m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2') + W = Body('W') + B1 = Body('B1', mass=m) + B2 = Body('B2', mass=m) + J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1) + J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2) + W.apply_force(k1*q1*W.x, reaction_body=B1) + W.apply_force(c1*u1*W.x, reaction_body=B1) + B1.apply_force(k2*q2*W.x, reaction_body=B2) + B1.apply_force(c2*u2*W.x, reaction_body=B2) + method = JointsMethod(W, J1, J2) + method.form_eoms() + MM = method.mass_matrix + forcing = method.forcing + rhs = MM.LUsolve(forcing) + assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m) + assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 * + c2 * u2) / m) + +def test_simple_pedulum(): + l, m, g = symbols('l m g') + C = Body('C') + b = Body('b', mass=m) + q = dynamicsymbols('q') + P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q, + child_point=-l * b.x, joint_axis=C.z) + b.potential_energy = - m * g * l * cos(q) + method = JointsMethod(C, P) + method.form_eoms(LagrangesMethod) + rhs = method.rhs() + assert rhs[1] == -g*sin(q)/l + +def test_chaos_pendulum(): + #https://www.pydy.org/examples/chaos_pendulum.html + mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g') + theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha') + + A = ReferenceFrame('A') + B = ReferenceFrame('B') + + rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0)) + plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz)) + C = Body('C') + J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega, + child_point=-lA * rod.z, joint_axis=C.y) + J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha, + parent_point=(lB - lA) * rod.z, joint_axis=rod.z) + + rod.apply_force(mA*g*C.z) + plate.apply_force(mB*g*C.z) + + method = JointsMethod(C, J1, J2) + method.form_eoms() + + MM = method.mass_matrix + forcing = method.forcing + rhs = MM.LUsolve(forcing) + xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) * + cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx * + sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB) + assert (rhs[0] - xd).simplify() == 0 + xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz + assert (rhs[1] - xd).simplify() == 0 + +def test_four_bar_linkage_with_manual_constraints(): + q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4, u1:4') + l1, l2, l3, l4, rho = symbols('l1:5, rho') + + N = ReferenceFrame('N') + inertias = [inertia(N, 0, 0, rho * l ** 3 / 12) for l in (l1, l2, l3, l4)] + link1 = Body('Link1', frame=N, mass=rho * l1, central_inertia=inertias[0]) + link2 = Body('Link2', mass=rho * l2, central_inertia=inertias[1]) + link3 = Body('Link3', mass=rho * l3, central_inertia=inertias[2]) + link4 = Body('Link4', mass=rho * l4, central_inertia=inertias[3]) + + joint1 = PinJoint( + 'J1', link1, link2, coordinates=q1, speeds=u1, joint_axis=link1.z, + parent_point=l1 / 2 * link1.x, child_point=-l2 / 2 * link2.x) + joint2 = PinJoint( + 'J2', link2, link3, coordinates=q2, speeds=u2, joint_axis=link2.z, + parent_point=l2 / 2 * link2.x, child_point=-l3 / 2 * link3.x) + joint3 = PinJoint( + 'J3', link3, link4, coordinates=q3, speeds=u3, joint_axis=link3.z, + parent_point=l3 / 2 * link3.x, child_point=-l4 / 2 * link4.x) + + loop = link4.masscenter.pos_from(link1.masscenter) \ + + l1 / 2 * link1.x + l4 / 2 * link4.x + + fh = Matrix([loop.dot(link1.x), loop.dot(link1.y)]) + + method = JointsMethod(link1, joint1, joint2, joint3) + + t = dynamicsymbols._t + qdots = solve(method.kdes, [q1.diff(t), q2.diff(t), q3.diff(t)]) + fhd = fh.diff(t).subs(qdots) + + kane = KanesMethod(method.frame, q_ind=[q1], u_ind=[u1], + q_dependent=[q2, q3], u_dependent=[u2, u3], + kd_eqs=method.kdes, configuration_constraints=fh, + velocity_constraints=fhd, forcelist=method.loads, + bodies=method.bodies) + fr, frs = kane.kanes_equations() + assert fr == zeros(1) + + # Numerically check the mass- and forcing-matrix + p = Matrix([l1, l2, l3, l4, rho]) + q = Matrix([q1, q2, q3]) + u = Matrix([u1, u2, u3]) + eval_m = lambdify((q, p), kane.mass_matrix) + eval_f = lambdify((q, u, p), kane.forcing) + eval_fhd = lambdify((q, u, p), fhd) + + p_vals = [0.13, 0.24, 0.21, 0.34, 997] + q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # Satisfies fh + u_vals = [0.2, -0.17963733938852067, 0.1309060540601612] # Satisfies fhd + mass_check = Matrix([[3.452709815256506e+01, 7.003948798374735e+00, + -4.939690970641498e+00], + [-2.203792703880936e-14, 2.071702479957077e-01, + 2.842917573033711e-01], + [-1.300000000000123e-01, -8.836934896046506e-03, + 1.864891330060847e-01]]) + forcing_check = Matrix([[-0.031211821321648], + [-0.00066022608181], + [0.001813559741243]]) + eps = 1e-10 + assert all(abs(x) < eps for x in eval_fhd(q_vals, u_vals, p_vals)) + assert all(abs(x) < eps for x in + (Matrix(eval_m(q_vals, p_vals)) - mass_check)) + assert all(abs(x) < eps for x in + (Matrix(eval_f(q_vals, u_vals, p_vals)) - forcing_check)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py new file mode 100644 index 0000000000000000000000000000000000000000..cce7ca5040524c4dc7a5a6be55e90afb139f552e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_kane4.py @@ -0,0 +1,115 @@ +from sympy.core.backend import (cos, sin, Matrix, symbols) +from sympy.physics.mechanics import (dynamicsymbols, ReferenceFrame, Point, + KanesMethod, Particle) + +def test_replace_qdots_in_force(): + # Test PR 16700 "Replaces qdots with us in force-list in kanes.py" + # The new functionality allows one to specify forces in qdots which will + # automatically be replaced with u:s which are defined by the kde supplied + # to KanesMethod. The test case is the double pendulum with interacting + # forces in the example of chapter 4.7 "CONTRIBUTING INTERACTION FORCES" + # in Ref. [1]. Reference list at end test function. + + q1, q2 = dynamicsymbols('q1, q2') + qd1, qd2 = dynamicsymbols('q1, q2', level=1) + u1, u2 = dynamicsymbols('u1, u2') + + l, m = symbols('l, m') + + N = ReferenceFrame('N') # Inertial frame + A = N.orientnew('A', 'Axis', (q1, N.z)) # Rod A frame + B = A.orientnew('B', 'Axis', (q2, N.z)) # Rod B frame + + O = Point('O') # Origo + O.set_vel(N, 0) + + P = O.locatenew('P', ( l * A.x )) # Point @ end of rod A + P.v2pt_theory(O, N, A) + + Q = P.locatenew('Q', ( l * B.x )) # Point @ end of rod B + Q.v2pt_theory(P, N, B) + + Ap = Particle('Ap', P, m) + Bp = Particle('Bp', Q, m) + + # The forces are specified below. sigma is the torsional spring stiffness + # and delta is the viscous damping coefficient acting between the two + # bodies. Here, we specify the viscous damper as function of qdots prior + # forming the kde. In more complex systems it not might be obvious which + # kde is most efficient, why it is convenient to specify viscous forces in + # qdots independently of the kde. + sig, delta = symbols('sigma, delta') + Ta = (sig * q2 + delta * qd2) * N.z + forces = [(A, Ta), (B, -Ta)] + + # Try different kdes. + kde1 = [u1 - qd1, u2 - qd2] + kde2 = [u1 - qd1, u2 - (qd1 + qd2)] + + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + # Check EOM for KM2: + # Mass and force matrix from p.6 in Ref. [2] with added forces from + # example of chapter 4.7 in [1] and without gravity. + forcing_matrix_expected = Matrix( [ [ m * l**2 * sin(q2) * u2**2 + sig * q2 + + delta * (u2 - u1)], + [ m * l**2 * sin(q2) * -u1**2 - sig * q2 + - delta * (u2 - u1)] ] ) + mass_matrix_expected = Matrix( [ [ 2 * m * l**2, m * l**2 * cos(q2) ], + [ m * l**2 * cos(q2), m * l**2 ] ] ) + + assert (KM2.mass_matrix.expand() == mass_matrix_expected.expand()) + assert (KM2.forcing.expand() == forcing_matrix_expected.expand()) + + # Check fr1 with reference fr_expected from [1] with u:s instead of qdots. + fr1_expected = Matrix([ 0, -(sig*q2 + delta * u2) ]) + assert fr1.expand() == fr1_expected.expand() + + # Check fr2 + fr2_expected = Matrix([sig * q2 + delta * (u2 - u1), + - sig * q2 - delta * (u2 - u1)]) + assert fr2.expand() == fr2_expected.expand() + + # Specifying forces in u:s should stay the same: + Ta = (sig * q2 + delta * u2) * N.z + forces = [(A, Ta), (B, -Ta)] + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + assert fr1.expand() == fr1_expected.expand() + + Ta = (sig * q2 + delta * (u2-u1)) * N.z + forces = [(A, Ta), (B, -Ta)] + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + assert fr2.expand() == fr2_expected.expand() + + # Test if we have a qubic qdot force: + Ta = (sig * q2 + delta * qd2**3) * N.z + forces = [(A, Ta), (B, -Ta)] + + KM1 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde1) + fr1, fstar1 = KM1.kanes_equations([Ap, Bp], forces) + + fr1_cubic_expected = Matrix([ 0, -(sig*q2 + delta * u2**3) ]) + + assert fr1.expand() == fr1_cubic_expected.expand() + + KM2 = KanesMethod(N, [q1, q2], [u1, u2], kd_eqs=kde2) + fr2, fstar2 = KM2.kanes_equations([Ap, Bp], forces) + + fr2_cubic_expected = Matrix([sig * q2 + delta * (u2 - u1)**3, + - sig * q2 - delta * (u2 - u1)**3]) + + assert fr2.expand() == fr2_cubic_expected.expand() + + # References: + # [1] T.R. Kane, D. a Levinson, Dynamics Theory and Applications, 2005. + # [2] Arun K Banerjee, Flexible Multibody Dynamics:Efficient Formulations + # and Applications, John Wiley and Sons, Ltd, 2016. + # doi:http://dx.doi.org/10.1002/9781119015635. diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff02c9f92d209d33c9fd0a1c7c130b5973f4a86 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_lagrange2.py @@ -0,0 +1,46 @@ +from sympy.core.backend import symbols +from sympy.physics.mechanics import dynamicsymbols +from sympy.physics.mechanics import ReferenceFrame, Point, Particle +from sympy.physics.mechanics import LagrangesMethod, Lagrangian + +### This test asserts that a system with more than one external forces +### is acurately formed with Lagrange method (see issue #8626) + +def test_lagrange_2forces(): + ### Equations for two damped springs in serie with two forces + + ### generalized coordinates + q1, q2 = dynamicsymbols('q1, q2') + ### generalized speeds + q1d, q2d = dynamicsymbols('q1, q2', 1) + + ### Mass, spring strength, friction coefficient + m, k, nu = symbols('m, k, nu') + + N = ReferenceFrame('N') + O = Point('O') + + ### Two points + P1 = O.locatenew('P1', q1 * N.x) + P1.set_vel(N, q1d * N.x) + P2 = O.locatenew('P1', q2 * N.x) + P2.set_vel(N, q2d * N.x) + + pP1 = Particle('pP1', P1, m) + pP1.potential_energy = k * q1**2 / 2 + + pP2 = Particle('pP2', P2, m) + pP2.potential_energy = k * (q1 - q2)**2 / 2 + + #### Friction forces + forcelist = [(P1, - nu * q1d * N.x), + (P2, - nu * q2d * N.x)] + lag = Lagrangian(N, pP1, pP2) + + l_method = LagrangesMethod(lag, (q1, q2), forcelist=forcelist, frame=N) + l_method.form_lagranges_equations() + + eq1 = l_method.eom[0] + assert eq1.diff(q1d) == nu + eq2 = l_method.eom[1] + assert eq2.diff(q2d) == nu diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8fd5fb50c3178f5a5cdab1e80423df8b52f525 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_method.py @@ -0,0 +1,5 @@ +from sympy.physics.mechanics.method import _Methods +from sympy.testing.pytest import raises + +def test_method(): + raises(TypeError, lambda: _Methods()) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py new file mode 100644 index 0000000000000000000000000000000000000000..14efe5ba03f8c31021250c3b99aa40123db569e9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_models.py @@ -0,0 +1,117 @@ +import sympy.physics.mechanics.models as models +from sympy.core.backend import (cos, sin, Matrix, symbols, zeros) +from sympy.simplify.simplify import simplify +from sympy.physics.mechanics import (dynamicsymbols) + + +def test_multi_mass_spring_damper_inputs(): + + c0, k0, m0 = symbols("c0 k0 m0") + g = symbols("g") + v0, x0, f0 = dynamicsymbols("v0 x0 f0") + + kane1 = models.multi_mass_spring_damper(1) + massmatrix1 = Matrix([[m0]]) + forcing1 = Matrix([[-c0*v0 - k0*x0]]) + assert simplify(massmatrix1 - kane1.mass_matrix) == Matrix([0]) + assert simplify(forcing1 - kane1.forcing) == Matrix([0]) + + kane2 = models.multi_mass_spring_damper(1, True) + massmatrix2 = Matrix([[m0]]) + forcing2 = Matrix([[-c0*v0 + g*m0 - k0*x0]]) + assert simplify(massmatrix2 - kane2.mass_matrix) == Matrix([0]) + assert simplify(forcing2 - kane2.forcing) == Matrix([0]) + + kane3 = models.multi_mass_spring_damper(1, True, True) + massmatrix3 = Matrix([[m0]]) + forcing3 = Matrix([[-c0*v0 + g*m0 - k0*x0 + f0]]) + assert simplify(massmatrix3 - kane3.mass_matrix) == Matrix([0]) + assert simplify(forcing3 - kane3.forcing) == Matrix([0]) + + kane4 = models.multi_mass_spring_damper(1, False, True) + massmatrix4 = Matrix([[m0]]) + forcing4 = Matrix([[-c0*v0 - k0*x0 + f0]]) + assert simplify(massmatrix4 - kane4.mass_matrix) == Matrix([0]) + assert simplify(forcing4 - kane4.forcing) == Matrix([0]) + + +def test_multi_mass_spring_damper_higher_order(): + c0, k0, m0 = symbols("c0 k0 m0") + c1, k1, m1 = symbols("c1 k1 m1") + c2, k2, m2 = symbols("c2 k2 m2") + v0, x0 = dynamicsymbols("v0 x0") + v1, x1 = dynamicsymbols("v1 x1") + v2, x2 = dynamicsymbols("v2 x2") + + kane1 = models.multi_mass_spring_damper(3) + massmatrix1 = Matrix([[m0 + m1 + m2, m1 + m2, m2], + [m1 + m2, m1 + m2, m2], + [m2, m2, m2]]) + forcing1 = Matrix([[-c0*v0 - k0*x0], + [-c1*v1 - k1*x1], + [-c2*v2 - k2*x2]]) + assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3) + assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0]) + + +def test_n_link_pendulum_on_cart_inputs(): + l0, m0 = symbols("l0 m0") + m1 = symbols("m1") + g = symbols("g") + q0, q1, F, T1 = dynamicsymbols("q0 q1 F T1") + u0, u1 = dynamicsymbols("u0 u1") + + kane1 = models.n_link_pendulum_on_cart(1) + massmatrix1 = Matrix([[m0 + m1, -l0*m1*cos(q1)], + [-l0*m1*cos(q1), l0**2*m1]]) + forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]]) + assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(2) + assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0]) + + kane2 = models.n_link_pendulum_on_cart(1, False) + massmatrix2 = Matrix([[m0 + m1, -l0*m1*cos(q1)], + [-l0*m1*cos(q1), l0**2*m1]]) + forcing2 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1)]]) + assert simplify(massmatrix2 - kane2.mass_matrix) == zeros(2) + assert simplify(forcing2 - kane2.forcing) == Matrix([0, 0]) + + kane3 = models.n_link_pendulum_on_cart(1, False, True) + massmatrix3 = Matrix([[m0 + m1, -l0*m1*cos(q1)], + [-l0*m1*cos(q1), l0**2*m1]]) + forcing3 = Matrix([[-l0*m1*u1**2*sin(q1)], [g*l0*m1*sin(q1) + T1]]) + assert simplify(massmatrix3 - kane3.mass_matrix) == zeros(2) + assert simplify(forcing3 - kane3.forcing) == Matrix([0, 0]) + + kane4 = models.n_link_pendulum_on_cart(1, True, False) + massmatrix4 = Matrix([[m0 + m1, -l0*m1*cos(q1)], + [-l0*m1*cos(q1), l0**2*m1]]) + forcing4 = Matrix([[-l0*m1*u1**2*sin(q1) + F], [g*l0*m1*sin(q1)]]) + assert simplify(massmatrix4 - kane4.mass_matrix) == zeros(2) + assert simplify(forcing4 - kane4.forcing) == Matrix([0, 0]) + + +def test_n_link_pendulum_on_cart_higher_order(): + l0, m0 = symbols("l0 m0") + l1, m1 = symbols("l1 m1") + m2 = symbols("m2") + g = symbols("g") + q0, q1, q2 = dynamicsymbols("q0 q1 q2") + u0, u1, u2 = dynamicsymbols("u0 u1 u2") + F, T1 = dynamicsymbols("F T1") + + kane1 = models.n_link_pendulum_on_cart(2) + massmatrix1 = Matrix([[m0 + m1 + m2, -l0*m1*cos(q1) - l0*m2*cos(q1), + -l1*m2*cos(q2)], + [-l0*m1*cos(q1) - l0*m2*cos(q1), l0**2*m1 + l0**2*m2, + l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2))], + [-l1*m2*cos(q2), + l0*l1*m2*(sin(q1)*sin(q2) + cos(q1)*cos(q2)), + l1**2*m2]]) + forcing1 = Matrix([[-l0*m1*u1**2*sin(q1) - l0*m2*u1**2*sin(q1) - + l1*m2*u2**2*sin(q2) + F], + [g*l0*m1*sin(q1) + g*l0*m2*sin(q1) - + l0*l1*m2*(sin(q1)*cos(q2) - sin(q2)*cos(q1))*u2**2], + [g*l1*m2*sin(q2) - l0*l1*m2*(-sin(q1)*cos(q2) + + sin(q2)*cos(q1))*u1**2]]) + assert simplify(massmatrix1 - kane1.mass_matrix) == zeros(3) + assert simplify(forcing1 - kane1.forcing) == Matrix([0, 0, 0]) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py new file mode 100644 index 0000000000000000000000000000000000000000..52ff22e2e28409e11793a704bd08bd5f3d8007bd --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/mechanics/tests/test_system.py @@ -0,0 +1,245 @@ +from sympy.core.backend import symbols, Matrix, atan, zeros +from sympy.simplify.simplify import simplify +from sympy.physics.mechanics import (dynamicsymbols, Particle, Point, + ReferenceFrame, SymbolicSystem) +from sympy.testing.pytest import raises + +# This class is going to be tested using a simple pendulum set up in x and y +# coordinates +x, y, u, v, lam = dynamicsymbols('x y u v lambda') +m, l, g = symbols('m l g') + +# Set up the different forms the equations can take +# [1] Explicit form where the kinematics and dynamics are combined +# x' = F(x, t, r, p) +# +# [2] Implicit form where the kinematics and dynamics are combined +# M(x, p) x' = F(x, t, r, p) +# +# [3] Implicit form where the kinematics and dynamics are separate +# M(q, p) u' = F(q, u, t, r, p) +# q' = G(q, u, t, r, p) +dyn_implicit_mat = Matrix([[1, 0, -x/m], + [0, 1, -y/m], + [0, 0, l**2/m]]) + +dyn_implicit_rhs = Matrix([0, 0, u**2 + v**2 - g*y]) + +comb_implicit_mat = Matrix([[1, 0, 0, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 1, 0, -x/m], + [0, 0, 0, 1, -y/m], + [0, 0, 0, 0, l**2/m]]) + +comb_implicit_rhs = Matrix([u, v, 0, 0, u**2 + v**2 - g*y]) + +kin_explicit_rhs = Matrix([u, v]) + +comb_explicit_rhs = comb_implicit_mat.LUsolve(comb_implicit_rhs) + +# Set up a body and load to pass into the system +theta = atan(x/y) +N = ReferenceFrame('N') +A = N.orientnew('A', 'Axis', [theta, N.z]) +O = Point('O') +P = O.locatenew('P', l * A.x) + +Pa = Particle('Pa', P, m) + +bodies = [Pa] +loads = [(P, g * m * N.x)] + +# Set up some output equations to be given to SymbolicSystem +# Change to make these fit the pendulum +PE = symbols("PE") +out_eqns = {PE: m*g*(l+y)} + +# Set up remaining arguments that can be passed to SymbolicSystem +alg_con = [2] +alg_con_full = [4] +coordinates = (x, y, lam) +speeds = (u, v) +states = (x, y, u, v, lam) +coord_idxs = (0, 1) +speed_idxs = (2, 3) + + +def test_form_1(): + symsystem1 = SymbolicSystem(states, comb_explicit_rhs, + alg_con=alg_con_full, output_eqns=out_eqns, + coord_idxs=coord_idxs, speed_idxs=speed_idxs, + bodies=bodies, loads=loads) + + assert symsystem1.coordinates == Matrix([x, y]) + assert symsystem1.speeds == Matrix([u, v]) + assert symsystem1.states == Matrix([x, y, u, v, lam]) + + assert symsystem1.alg_con == [4] + + inter = comb_explicit_rhs + assert simplify(symsystem1.comb_explicit_rhs - inter) == zeros(5, 1) + + assert set(symsystem1.dynamic_symbols()) == {y, v, lam, u, x} + assert type(symsystem1.dynamic_symbols()) == tuple + assert set(symsystem1.constant_symbols()) == {l, g, m} + assert type(symsystem1.constant_symbols()) == tuple + + assert symsystem1.output_eqns == out_eqns + + assert symsystem1.bodies == (Pa,) + assert symsystem1.loads == ((P, g * m * N.x),) + + +def test_form_2(): + symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds, + mass_matrix=comb_implicit_mat, + alg_con=alg_con_full, output_eqns=out_eqns, + bodies=bodies, loads=loads) + + assert symsystem2.coordinates == Matrix([x, y, lam]) + assert symsystem2.speeds == Matrix([u, v]) + assert symsystem2.states == Matrix([x, y, lam, u, v]) + + assert symsystem2.alg_con == [4] + + inter = comb_implicit_rhs + assert simplify(symsystem2.comb_implicit_rhs - inter) == zeros(5, 1) + assert simplify(symsystem2.comb_implicit_mat-comb_implicit_mat) == zeros(5) + + assert set(symsystem2.dynamic_symbols()) == {y, v, lam, u, x} + assert type(symsystem2.dynamic_symbols()) == tuple + assert set(symsystem2.constant_symbols()) == {l, g, m} + assert type(symsystem2.constant_symbols()) == tuple + + inter = comb_explicit_rhs + symsystem2.compute_explicit_form() + assert simplify(symsystem2.comb_explicit_rhs - inter) == zeros(5, 1) + + + assert symsystem2.output_eqns == out_eqns + + assert symsystem2.bodies == (Pa,) + assert symsystem2.loads == ((P, g * m * N.x),) + + +def test_form_3(): + symsystem3 = SymbolicSystem(states, dyn_implicit_rhs, + mass_matrix=dyn_implicit_mat, + coordinate_derivatives=kin_explicit_rhs, + alg_con=alg_con, coord_idxs=coord_idxs, + speed_idxs=speed_idxs, bodies=bodies, + loads=loads) + + assert symsystem3.coordinates == Matrix([x, y]) + assert symsystem3.speeds == Matrix([u, v]) + assert symsystem3.states == Matrix([x, y, u, v, lam]) + + assert symsystem3.alg_con == [4] + + inter1 = kin_explicit_rhs + inter2 = dyn_implicit_rhs + assert simplify(symsystem3.kin_explicit_rhs - inter1) == zeros(2, 1) + assert simplify(symsystem3.dyn_implicit_mat - dyn_implicit_mat) == zeros(3) + assert simplify(symsystem3.dyn_implicit_rhs - inter2) == zeros(3, 1) + + inter = comb_implicit_rhs + assert simplify(symsystem3.comb_implicit_rhs - inter) == zeros(5, 1) + assert simplify(symsystem3.comb_implicit_mat-comb_implicit_mat) == zeros(5) + + inter = comb_explicit_rhs + symsystem3.compute_explicit_form() + assert simplify(symsystem3.comb_explicit_rhs - inter) == zeros(5, 1) + + assert set(symsystem3.dynamic_symbols()) == {y, v, lam, u, x} + assert type(symsystem3.dynamic_symbols()) == tuple + assert set(symsystem3.constant_symbols()) == {l, g, m} + assert type(symsystem3.constant_symbols()) == tuple + + assert symsystem3.output_eqns == {} + + assert symsystem3.bodies == (Pa,) + assert symsystem3.loads == ((P, g * m * N.x),) + + +def test_property_attributes(): + symsystem = SymbolicSystem(states, comb_explicit_rhs, + alg_con=alg_con_full, output_eqns=out_eqns, + coord_idxs=coord_idxs, speed_idxs=speed_idxs, + bodies=bodies, loads=loads) + + with raises(AttributeError): + symsystem.bodies = 42 + with raises(AttributeError): + symsystem.coordinates = 42 + with raises(AttributeError): + symsystem.dyn_implicit_rhs = 42 + with raises(AttributeError): + symsystem.comb_implicit_rhs = 42 + with raises(AttributeError): + symsystem.loads = 42 + with raises(AttributeError): + symsystem.dyn_implicit_mat = 42 + with raises(AttributeError): + symsystem.comb_implicit_mat = 42 + with raises(AttributeError): + symsystem.kin_explicit_rhs = 42 + with raises(AttributeError): + symsystem.comb_explicit_rhs = 42 + with raises(AttributeError): + symsystem.speeds = 42 + with raises(AttributeError): + symsystem.states = 42 + with raises(AttributeError): + symsystem.alg_con = 42 + + +def test_not_specified_errors(): + """This test will cover errors that arise from trying to access attributes + that were not specified upon object creation or were specified on creation + and the user tries to recalculate them.""" + # Trying to access form 2 when form 1 given + # Trying to access form 3 when form 2 given + + symsystem1 = SymbolicSystem(states, comb_explicit_rhs) + + with raises(AttributeError): + symsystem1.comb_implicit_mat + with raises(AttributeError): + symsystem1.comb_implicit_rhs + with raises(AttributeError): + symsystem1.dyn_implicit_mat + with raises(AttributeError): + symsystem1.dyn_implicit_rhs + with raises(AttributeError): + symsystem1.kin_explicit_rhs + with raises(AttributeError): + symsystem1.compute_explicit_form() + + symsystem2 = SymbolicSystem(coordinates, comb_implicit_rhs, speeds=speeds, + mass_matrix=comb_implicit_mat) + + with raises(AttributeError): + symsystem2.dyn_implicit_mat + with raises(AttributeError): + symsystem2.dyn_implicit_rhs + with raises(AttributeError): + symsystem2.kin_explicit_rhs + + # Attribute error when trying to access coordinates and speeds when only the + # states were given. + with raises(AttributeError): + symsystem1.coordinates + with raises(AttributeError): + symsystem1.speeds + + # Attribute error when trying to access bodies and loads when they are not + # given + with raises(AttributeError): + symsystem1.bodies + with raises(AttributeError): + symsystem1.loads + + # Attribute error when trying to access comb_explicit_rhs before it was + # calculated + with raises(AttributeError): + symsystem2.comb_explicit_rhs diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/sho.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/sho.py new file mode 100644 index 0000000000000000000000000000000000000000..c55b31b3fa9fca4fa33a9f8e91c90c2174fe81a5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/sho.py @@ -0,0 +1,95 @@ +from sympy.core import S, pi, Rational +from sympy.functions import assoc_laguerre, sqrt, exp, factorial, factorial2 + + +def R_nl(n, l, nu, r): + """ + Returns the radial wavefunction R_{nl} for a 3d isotropic harmonic + oscillator. + + Parameters + ========== + + n : + The "nodal" quantum number. Corresponds to the number of nodes in + the wavefunction. ``n >= 0`` + l : + The quantum number for orbital angular momentum. + nu : + mass-scaled frequency: nu = m*omega/(2*hbar) where `m` is the mass + and `omega` the frequency of the oscillator. + (in atomic units ``nu == omega/2``) + r : + Radial coordinate. + + Examples + ======== + + >>> from sympy.physics.sho import R_nl + >>> from sympy.abc import r, nu, l + >>> R_nl(0, 0, 1, r) + 2*2**(3/4)*exp(-r**2)/pi**(1/4) + >>> R_nl(1, 0, 1, r) + 4*2**(1/4)*sqrt(3)*(3/2 - 2*r**2)*exp(-r**2)/(3*pi**(1/4)) + + l, nu and r may be symbolic: + + >>> R_nl(0, 0, nu, r) + 2*2**(3/4)*sqrt(nu**(3/2))*exp(-nu*r**2)/pi**(1/4) + >>> R_nl(0, l, 1, r) + r**l*sqrt(2**(l + 3/2)*2**(l + 2)/factorial2(2*l + 1))*exp(-r**2)/pi**(1/4) + + The normalization of the radial wavefunction is: + + >>> from sympy import Integral, oo + >>> Integral(R_nl(0, 0, 1, r)**2*r**2, (r, 0, oo)).n() + 1.00000000000000 + >>> Integral(R_nl(1, 0, 1, r)**2*r**2, (r, 0, oo)).n() + 1.00000000000000 + >>> Integral(R_nl(1, 1, 1, r)**2*r**2, (r, 0, oo)).n() + 1.00000000000000 + + """ + n, l, nu, r = map(S, [n, l, nu, r]) + + # formula uses n >= 1 (instead of nodal n >= 0) + n = n + 1 + C = sqrt( + ((2*nu)**(l + Rational(3, 2))*2**(n + l + 1)*factorial(n - 1))/ + (sqrt(pi)*(factorial2(2*n + 2*l - 1))) + ) + return C*r**(l)*exp(-nu*r**2)*assoc_laguerre(n - 1, l + S.Half, 2*nu*r**2) + + +def E_nl(n, l, hw): + """ + Returns the Energy of an isotropic harmonic oscillator. + + Parameters + ========== + + n : + The "nodal" quantum number. + l : + The orbital angular momentum. + hw : + The harmonic oscillator parameter. + + Notes + ===== + + The unit of the returned value matches the unit of hw, since the energy is + calculated as: + + E_nl = (2*n + l + 3/2)*hw + + Examples + ======== + + >>> from sympy.physics.sho import E_nl + >>> from sympy import symbols + >>> x, y, z = symbols('x, y, z') + >>> E_nl(x, y, z) + z*(2*x + y + 3/2) + """ + return (2*n + l + Rational(3, 2))*hw diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8098408e39622d4af7d953ebfcb0409deeba6915 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61ab7671e2ecb1f6f6ae4fc0f86083411c277bbb Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_clebsch_gordan.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7616cec3d83e963b1b883a498612020de0c4f42d Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_hydrogen.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74ef8429f00eb7fd0afde4335138ddc00b56c48a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_paulialgebra.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..969b5441557103ab84848aee3d4c5264c478486b Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_physics_matrices.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b003e4db0e3a805a81b73c7ab87a69a8475b57a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_pring.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1774e7fa4585a7c2c8dd7042fd2b32c4aca509e2 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_qho_1d.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..197734a98e242722643087f167bc8224a28b62ef Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_secondquant.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32721b8b023589a1122048020022349a60286040 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/__pycache__/test_sho.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a41f1b6b4fbe921ff28ced8f6eade6d2e1648f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_clebsch_gordan.py @@ -0,0 +1,191 @@ +from sympy.core.numbers import (I, pi, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.functions.special.spherical_harmonics import Ynm +from sympy.matrices.dense import Matrix +from sympy.physics.wigner import (clebsch_gordan, wigner_9j, wigner_6j, gaunt, + real_gaunt, racah, dot_rot_grad_Ynm, wigner_3j, wigner_d_small, wigner_d) +from sympy.testing.pytest import raises + +# for test cases, refer : https://en.wikipedia.org/wiki/Table_of_Clebsch%E2%80%93Gordan_coefficients + +def test_clebsch_gordan_docs(): + assert clebsch_gordan(Rational(3, 2), S.Half, 2, Rational(3, 2), S.Half, 2) == 1 + assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(3, 2), Rational(-1, 2), 1) == sqrt(3)/2 + assert clebsch_gordan(Rational(3, 2), S.Half, 1, Rational(-1, 2), S.Half, 0) == -sqrt(2)/2 + + +def test_clebsch_gordan(): + # Argument order: (j_1, j_2, j, m_1, m_2, m) + + h = S.One + k = S.Half + l = Rational(3, 2) + i = Rational(-1, 2) + n = Rational(7, 2) + p = Rational(5, 2) + assert clebsch_gordan(k, k, 1, k, k, 1) == 1 + assert clebsch_gordan(k, k, 1, k, k, 0) == 0 + assert clebsch_gordan(k, k, 1, i, i, -1) == 1 + assert clebsch_gordan(k, k, 1, k, i, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 0, k, i, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 1, i, k, 0) == sqrt(2)/2 + assert clebsch_gordan(k, k, 0, i, k, 0) == -sqrt(2)/2 + assert clebsch_gordan(h, k, l, 1, k, l) == 1 + assert clebsch_gordan(h, k, l, 1, i, k) == 1/sqrt(3) + assert clebsch_gordan(h, k, k, 1, i, k) == sqrt(2)/sqrt(3) + assert clebsch_gordan(h, k, k, 0, k, k) == -1/sqrt(3) + assert clebsch_gordan(h, k, l, 0, k, k) == sqrt(2)/sqrt(3) + assert clebsch_gordan(h, h, S(2), 1, 1, S(2)) == 1 + assert clebsch_gordan(h, h, S(2), 1, 0, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, S(2), 0, 1, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, 1, 1, 0, 1) == 1/sqrt(2) + assert clebsch_gordan(h, h, 1, 0, 1, 1) == -1/sqrt(2) + assert clebsch_gordan(l, l, S(3), l, l, S(3)) == 1 + assert clebsch_gordan(l, l, S(2), l, k, S(2)) == 1/sqrt(2) + assert clebsch_gordan(l, l, S(3), l, k, S(2)) == 1/sqrt(2) + assert clebsch_gordan(S(2), S(2), S(4), S(2), S(2), S(4)) == 1 + assert clebsch_gordan(S(2), S(2), S(3), S(2), 1, S(3)) == 1/sqrt(2) + assert clebsch_gordan(S(2), S(2), S(3), 1, 1, S(2)) == 0 + assert clebsch_gordan(p, h, n, p, 1, n) == 1 + assert clebsch_gordan(p, h, p, p, 0, p) == sqrt(5)/sqrt(7) + assert clebsch_gordan(p, h, l, k, 1, l) == 1/sqrt(15) + + +def test_wigner(): + def tn(a, b): + return (a - b).n(64) < S('1e-64') + assert tn(wigner_9j(1, 1, 1, 1, 1, 1, 1, 1, 0, prec=64), Rational(1, 18)) + assert wigner_9j(3, 3, 2, 3, 3, 2, 3, 3, 2) == 3221*sqrt( + 70)/(246960*sqrt(105)) - 365/(3528*sqrt(70)*sqrt(105)) + assert wigner_6j(5, 5, 5, 5, 5, 5) == Rational(1, 52) + assert tn(wigner_6j(8, 8, 8, 8, 8, 8, prec=64), Rational(-12219, 965770)) + # regression test for #8747 + half = S.Half + assert wigner_9j(0, 0, 0, 0, half, half, 0, half, half) == half + assert (wigner_9j(3, 5, 4, + 7 * half, 5 * half, 4, + 9 * half, 9 * half, 0) + == -sqrt(Rational(361, 205821000))) + assert (wigner_9j(1, 4, 3, + 5 * half, 4, 5 * half, + 5 * half, 2, 7 * half) + == -sqrt(Rational(3971, 373403520))) + assert (wigner_9j(4, 9 * half, 5 * half, + 2, 4, 4, + 5, 7 * half, 7 * half) + == -sqrt(Rational(3481, 5042614500))) + + +def test_gaunt(): + def tn(a, b): + return (a - b).n(64) < S('1e-64') + assert gaunt(1, 0, 1, 1, 0, -1) == -1/(2*sqrt(pi)) + assert isinstance(gaunt(1, 1, 0, -1, 1, 0).args[0], Rational) + assert isinstance(gaunt(0, 1, 1, 0, -1, 1).args[0], Rational) + + assert tn(gaunt( + 10, 10, 12, 9, 3, -12, prec=64), (Rational(-98, 62031)) * sqrt(6279)/sqrt(pi)) + def gaunt_ref(l1, l2, l3, m1, m2, m3): + return ( + sqrt((2 * l1 + 1) * (2 * l2 + 1) * (2 * l3 + 1) / (4 * pi)) * + wigner_3j(l1, l2, l3, 0, 0, 0) * + wigner_3j(l1, l2, l3, m1, m2, m3) + ) + threshold = 1e-10 + l_max = 3 + l3_max = 24 + for l1 in range(l_max + 1): + for l2 in range(l_max + 1): + for l3 in range(l3_max + 1): + for m1 in range(-l1, l1 + 1): + for m2 in range(-l2, l2 + 1): + for m3 in range(-l3, l3 + 1): + args = l1, l2, l3, m1, m2, m3 + g = gaunt(*args) + g0 = gaunt_ref(*args) + assert abs(g - g0) < threshold + if m1 + m2 + m3 != 0: + assert abs(g) < threshold + if (l1 + l2 + l3) % 2: + assert abs(g) < threshold + assert gaunt(1, 1, 0, 0, 2, -2) is S.Zero + + +def test_realgaunt(): + # All non-zero values corresponding to l values from 0 to 2 + for l in range(3): + for m in range(-l, l+1): + assert real_gaunt(0, l, l, 0, m, m) == 1/(2*sqrt(pi)) + assert real_gaunt(1, 1, 2, 0, 0, 0) == sqrt(5)/(5*sqrt(pi)) + assert real_gaunt(1, 1, 2, 1, 1, 0) == -sqrt(5)/(10*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 0, 0) == sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 2, 2) == -sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(2, 2, 2, -2, -2, 0) == -sqrt(5)/(7*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, 0, -1) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, 0, 1, 1) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, 1, 1, 2) == sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, 1, -2) == -sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(1, 1, 2, -1, -1, 2) == -sqrt(15)/(10*sqrt(pi)) + assert real_gaunt(2, 2, 2, 0, 1, 1) == sqrt(5)/(14*sqrt(pi)) + assert real_gaunt(2, 2, 2, 1, 1, 2) == sqrt(15)/(14*sqrt(pi)) + assert real_gaunt(2, 2, 2, -1, -1, 2) == -sqrt(15)/(14*sqrt(pi)) + + assert real_gaunt(-2, -2, -2, -2, -2, 0) is S.Zero # m test + assert real_gaunt(-2, 1, 0, 1, 1, 1) is S.Zero # l test + assert real_gaunt(-2, -1, -2, -1, -1, 0) is S.Zero # m and l test + assert real_gaunt(-2, -2, -2, -2, -2, -2) is S.Zero # m and k test + assert real_gaunt(-2, -1, -2, -1, -1, -1) is S.Zero # m, l and k test + + x = symbols('x', integer=True) + v = [0]*6 + for i in range(len(v)): + v[i] = x # non literal ints fail + raises(ValueError, lambda: real_gaunt(*v)) + v[i] = 0 + + +def test_racah(): + assert racah(3,3,3,3,3,3) == Rational(-1,14) + assert racah(2,2,2,2,2,2) == Rational(-3,70) + assert racah(7,8,7,1,7,7, prec=4).is_Float + assert racah(5.5,7.5,9.5,6.5,8,9) == -719*sqrt(598)/1158924 + assert abs(racah(5.5,7.5,9.5,6.5,8,9, prec=4) - (-0.01517)) < S('1e-4') + + +def test_dot_rota_grad_SH(): + theta, phi = symbols("theta phi") + assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0) != \ + sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi)) + assert dot_rot_grad_Ynm(1, 1, 1, 1, 1, 0).doit() == \ + sqrt(30)*Ynm(2, 2, 1, 0)/(10*sqrt(pi)) + assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2) != \ + 0 + assert dot_rot_grad_Ynm(1, 5, 1, 1, 1, 2).doit() == \ + 0 + assert dot_rot_grad_Ynm(3, 3, 3, 3, theta, phi).doit() == \ + 15*sqrt(3003)*Ynm(6, 6, theta, phi)/(143*sqrt(pi)) + assert dot_rot_grad_Ynm(3, 3, 1, 1, theta, phi).doit() == \ + sqrt(3)*Ynm(4, 4, theta, phi)/sqrt(pi) + assert dot_rot_grad_Ynm(3, 2, 2, 0, theta, phi).doit() == \ + 3*sqrt(55)*Ynm(5, 2, theta, phi)/(11*sqrt(pi)) + assert dot_rot_grad_Ynm(3, 2, 3, 2, theta, phi).doit().expand() == \ + -sqrt(70)*Ynm(4, 4, theta, phi)/(11*sqrt(pi)) + \ + 45*sqrt(182)*Ynm(6, 4, theta, phi)/(143*sqrt(pi)) + + +def test_wigner_d(): + half = S(1)/2 + alpha, beta, gamma = symbols("alpha, beta, gamma", real=True) + d = wigner_d_small(half, beta).subs({beta: pi/2}) + d_ = Matrix([[1, 1], [-1, 1]])/sqrt(2) + assert d == d_ + + D = wigner_d(half, alpha, beta, gamma) + assert D[0, 0] == exp(I*alpha/2)*exp(I*gamma/2)*cos(beta/2) + assert D[0, 1] == exp(I*alpha/2)*exp(-I*gamma/2)*sin(beta/2) + assert D[1, 0] == -exp(-I*alpha/2)*exp(I*gamma/2)*sin(beta/2) + assert D[1, 1] == exp(-I*alpha/2)*exp(-I*gamma/2)*cos(beta/2) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py new file mode 100644 index 0000000000000000000000000000000000000000..eb11744dd8e731f24fcd6f6be2a92ada4fffc554 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_hydrogen.py @@ -0,0 +1,126 @@ +from sympy.core.numbers import (I, Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (cos, sin) +from sympy.integrals.integrals import integrate +from sympy.simplify.simplify import simplify +from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac, Psi_nlm +from sympy.testing.pytest import raises + +n, r, Z = symbols('n r Z') + + +def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12): + a = float(a) + b = float(b) + # if the numbers are close enough (absolutely), then they are equal + if abs(a - b) < max_absolute_error: + return True + # if not, they can still be equal if their relative error is small + if abs(b) > abs(a): + relative_error = abs((a - b)/b) + else: + relative_error = abs((a - b)/a) + return relative_error <= max_relative_error + + +def test_wavefunction(): + a = 1/Z + R = { + (1, 0): 2*sqrt(1/a**3) * exp(-r/a), + (2, 0): sqrt(1/(2*a**3)) * exp(-r/(2*a)) * (1 - r/(2*a)), + (2, 1): S.Half * sqrt(1/(6*a**3)) * exp(-r/(2*a)) * r/a, + (3, 0): Rational(2, 3) * sqrt(1/(3*a**3)) * exp(-r/(3*a)) * + (1 - 2*r/(3*a) + Rational(2, 27) * (r/a)**2), + (3, 1): Rational(4, 27) * sqrt(2/(3*a**3)) * exp(-r/(3*a)) * + (1 - r/(6*a)) * r/a, + (3, 2): Rational(2, 81) * sqrt(2/(15*a**3)) * exp(-r/(3*a)) * (r/a)**2, + (4, 0): Rational(1, 4) * sqrt(1/a**3) * exp(-r/(4*a)) * + (1 - 3*r/(4*a) + Rational(1, 8) * (r/a)**2 - Rational(1, 192) * (r/a)**3), + (4, 1): Rational(1, 16) * sqrt(5/(3*a**3)) * exp(-r/(4*a)) * + (1 - r/(4*a) + Rational(1, 80) * (r/a)**2) * (r/a), + (4, 2): Rational(1, 64) * sqrt(1/(5*a**3)) * exp(-r/(4*a)) * + (1 - r/(12*a)) * (r/a)**2, + (4, 3): Rational(1, 768) * sqrt(1/(35*a**3)) * exp(-r/(4*a)) * (r/a)**3, + } + for n, l in R: + assert simplify(R_nl(n, l, r, Z) - R[(n, l)]) == 0 + + +def test_norm(): + # Maximum "n" which is tested: + n_max = 2 # it works, but is slow, for n_max > 2 + for n in range(n_max + 1): + for l in range(n): + assert integrate(R_nl(n, l, r)**2 * r**2, (r, 0, oo)) == 1 + +def test_psi_nlm(): + r=S('r') + phi=S('phi') + theta=S('theta') + assert (Psi_nlm(1, 0, 0, r, phi, theta) == exp(-r) / sqrt(pi)) + assert (Psi_nlm(2, 1, -1, r, phi, theta)) == S.Half * exp(-r / (2)) * r \ + * (sin(theta) * exp(-I * phi) / (4 * sqrt(pi))) + assert (Psi_nlm(3, 2, 1, r, phi, theta, 2) == -sqrt(2) * sin(theta) \ + * exp(I * phi) * cos(theta) / (4 * sqrt(pi)) * S(2) / 81 \ + * sqrt(2 * 2 ** 3) * exp(-2 * r / (3)) * (r * 2) ** 2) + +def test_hydrogen_energies(): + assert E_nl(n, Z) == -Z**2/(2*n**2) + assert E_nl(n) == -1/(2*n**2) + + assert E_nl(1, 47) == -S(47)**2/(2*1**2) + assert E_nl(2, 47) == -S(47)**2/(2*2**2) + + assert E_nl(1) == -S.One/(2*1**2) + assert E_nl(2) == -S.One/(2*2**2) + assert E_nl(3) == -S.One/(2*3**2) + assert E_nl(4) == -S.One/(2*4**2) + assert E_nl(100) == -S.One/(2*100**2) + + raises(ValueError, lambda: E_nl(0)) + + +def test_hydrogen_energies_relat(): + # First test exact formulas for small "c" so that we get nice expressions: + assert E_nl_dirac(2, 0, Z=1, c=1) == 1/sqrt(2) - 1 + assert simplify(E_nl_dirac(2, 0, Z=1, c=2) - ( (8*sqrt(3) + 16) + / sqrt(16*sqrt(3) + 32) - 4)) == 0 + assert simplify(E_nl_dirac(2, 0, Z=1, c=3) - ( (54*sqrt(2) + 81) + / sqrt(108*sqrt(2) + 162) - 9)) == 0 + + # Now test for almost the correct speed of light, without floating point + # numbers: + assert simplify(E_nl_dirac(2, 0, Z=1, c=137) - ( (352275361 + 10285412 * + sqrt(1173)) / sqrt(704550722 + 20570824 * sqrt(1173)) - 18769)) == 0 + assert simplify(E_nl_dirac(2, 0, Z=82, c=137) - ( (352275361 + 2571353 * + sqrt(12045)) / sqrt(704550722 + 5142706*sqrt(12045)) - 18769)) == 0 + + # Test using exact speed of light, and compare against the nonrelativistic + # energies: + for n in range(1, 5): + for l in range(n): + assert feq(E_nl_dirac(n, l), E_nl(n), 1e-5, 1e-5) + if l > 0: + assert feq(E_nl_dirac(n, l, False), E_nl(n), 1e-5, 1e-5) + + Z = 2 + for n in range(1, 5): + for l in range(n): + assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-4, 1e-4) + if l > 0: + assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-4, 1e-4) + + Z = 3 + for n in range(1, 5): + for l in range(n): + assert feq(E_nl_dirac(n, l, Z=Z), E_nl(n, Z), 1e-3, 1e-3) + if l > 0: + assert feq(E_nl_dirac(n, l, False, Z), E_nl(n, Z), 1e-3, 1e-3) + + # Test the exceptions: + raises(ValueError, lambda: E_nl_dirac(0, 0)) + raises(ValueError, lambda: E_nl_dirac(1, -1)) + raises(ValueError, lambda: E_nl_dirac(1, 0, False)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py new file mode 100644 index 0000000000000000000000000000000000000000..f773470a1802f2864b79f56d38be1de030ff86dc --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_paulialgebra.py @@ -0,0 +1,57 @@ +from sympy.core.numbers import I +from sympy.core.symbol import symbols +from sympy.physics.paulialgebra import Pauli +from sympy.testing.pytest import XFAIL +from sympy.physics.quantum import TensorProduct + +sigma1 = Pauli(1) +sigma2 = Pauli(2) +sigma3 = Pauli(3) + +tau1 = symbols("tau1", commutative = False) + + +def test_Pauli(): + + assert sigma1 == sigma1 + assert sigma1 != sigma2 + + assert sigma1*sigma2 == I*sigma3 + assert sigma3*sigma1 == I*sigma2 + assert sigma2*sigma3 == I*sigma1 + + assert sigma1*sigma1 == 1 + assert sigma2*sigma2 == 1 + assert sigma3*sigma3 == 1 + + assert sigma1**0 == 1 + assert sigma1**1 == sigma1 + assert sigma1**2 == 1 + assert sigma1**3 == sigma1 + assert sigma1**4 == 1 + + assert sigma3**2 == 1 + + assert sigma1*2*sigma1 == 2 + + +def test_evaluate_pauli_product(): + from sympy.physics.paulialgebra import evaluate_pauli_product + + assert evaluate_pauli_product(I*sigma2*sigma3) == -sigma1 + + # Check issue 6471 + assert evaluate_pauli_product(-I*4*sigma1*sigma2) == 4*sigma3 + + assert evaluate_pauli_product( + 1 + I*sigma1*sigma2*sigma1*sigma2 + \ + I*sigma1*sigma2*tau1*sigma1*sigma3 + \ + ((tau1**2).subs(tau1, I*sigma1)) + \ + sigma3*((tau1**2).subs(tau1, I*sigma1)) + \ + TensorProduct(I*sigma1*sigma2*sigma1*sigma2, 1) + ) == 1 -I + I*sigma3*tau1*sigma2 - 1 - sigma3 - I*TensorProduct(1,1) + + +@XFAIL +def test_Pauli_should_work(): + assert sigma1*sigma3*sigma1 == -sigma3 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..14fa47668d0760826e0354c8cafae787a24256eb --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_physics_matrices.py @@ -0,0 +1,84 @@ +from sympy.physics.matrices import msigma, mgamma, minkowski_tensor, pat_matrix, mdft +from sympy.core.numbers import (I, Rational) +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.matrices.dense import (Matrix, eye, zeros) +from sympy.testing.pytest import warns_deprecated_sympy + + +def test_parallel_axis_theorem(): + # This tests the parallel axis theorem matrix by comparing to test + # matrices. + + # First case, 1 in all directions. + mat1 = Matrix(((2, -1, -1), (-1, 2, -1), (-1, -1, 2))) + assert pat_matrix(1, 1, 1, 1) == mat1 + assert pat_matrix(2, 1, 1, 1) == 2*mat1 + + # Second case, 1 in x, 0 in all others + mat2 = Matrix(((0, 0, 0), (0, 1, 0), (0, 0, 1))) + assert pat_matrix(1, 1, 0, 0) == mat2 + assert pat_matrix(2, 1, 0, 0) == 2*mat2 + + # Third case, 1 in y, 0 in all others + mat3 = Matrix(((1, 0, 0), (0, 0, 0), (0, 0, 1))) + assert pat_matrix(1, 0, 1, 0) == mat3 + assert pat_matrix(2, 0, 1, 0) == 2*mat3 + + # Fourth case, 1 in z, 0 in all others + mat4 = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 0))) + assert pat_matrix(1, 0, 0, 1) == mat4 + assert pat_matrix(2, 0, 0, 1) == 2*mat4 + + +def test_Pauli(): + #this and the following test are testing both Pauli and Dirac matrices + #and also that the general Matrix class works correctly in a real world + #situation + sigma1 = msigma(1) + sigma2 = msigma(2) + sigma3 = msigma(3) + + assert sigma1 == sigma1 + assert sigma1 != sigma2 + + # sigma*I -> I*sigma (see #354) + assert sigma1*sigma2 == sigma3*I + assert sigma3*sigma1 == sigma2*I + assert sigma2*sigma3 == sigma1*I + + assert sigma1*sigma1 == eye(2) + assert sigma2*sigma2 == eye(2) + assert sigma3*sigma3 == eye(2) + + assert sigma1*2*sigma1 == 2*eye(2) + assert sigma1*sigma3*sigma1 == -sigma3 + + +def test_Dirac(): + gamma0 = mgamma(0) + gamma1 = mgamma(1) + gamma2 = mgamma(2) + gamma3 = mgamma(3) + gamma5 = mgamma(5) + + # gamma*I -> I*gamma (see #354) + assert gamma5 == gamma0 * gamma1 * gamma2 * gamma3 * I + assert gamma1 * gamma2 + gamma2 * gamma1 == zeros(4) + assert gamma0 * gamma0 == eye(4) * minkowski_tensor[0, 0] + assert gamma2 * gamma2 != eye(4) * minkowski_tensor[0, 0] + assert gamma2 * gamma2 == eye(4) * minkowski_tensor[2, 2] + + assert mgamma(5, True) == \ + mgamma(0, True)*mgamma(1, True)*mgamma(2, True)*mgamma(3, True)*I + +def test_mdft(): + with warns_deprecated_sympy(): + assert mdft(1) == Matrix([[1]]) + with warns_deprecated_sympy(): + assert mdft(2) == 1/sqrt(2)*Matrix([[1,1],[1,-1]]) + with warns_deprecated_sympy(): + assert mdft(4) == Matrix([[S.Half, S.Half, S.Half, S.Half], + [S.Half, -I/2, Rational(-1,2), I/2], + [S.Half, Rational(-1,2), S.Half, Rational(-1,2)], + [S.Half, I/2, Rational(-1,2), -I/2]]) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_pring.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_pring.py new file mode 100644 index 0000000000000000000000000000000000000000..ed7398eac4a8bb1cd4af810825caf3fcefb5f18f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_pring.py @@ -0,0 +1,41 @@ +from sympy.physics.pring import wavefunction, energy +from sympy.core.numbers import (I, pi) +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.integrals.integrals import integrate +from sympy.simplify.simplify import simplify +from sympy.abc import m, x, r +from sympy.physics.quantum.constants import hbar + + +def test_wavefunction(): + Psi = { + 0: (1/sqrt(2 * pi)), + 1: (1/sqrt(2 * pi)) * exp(I * x), + 2: (1/sqrt(2 * pi)) * exp(2 * I * x), + 3: (1/sqrt(2 * pi)) * exp(3 * I * x) + } + for n in Psi: + assert simplify(wavefunction(n, x) - Psi[n]) == 0 + + +def test_norm(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + assert integrate( + wavefunction(i, x) * wavefunction(-i, x), (x, 0, 2 * pi)) == 1 + + +def test_orthogonality(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + for j in range(i+1, n+1): + assert integrate( + wavefunction(i, x) * wavefunction(j, x), (x, 0, 2 * pi)) == 0 + + +def test_energy(n=1): + # Maximum "n" which is tested: + for i in range(n+1): + assert simplify( + energy(i, m, r) - ((i**2 * hbar**2) / (2 * m * r**2))) == 0 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py new file mode 100644 index 0000000000000000000000000000000000000000..34e52c9e3a721496fc61f7d2b31414db15caa7a8 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_qho_1d.py @@ -0,0 +1,50 @@ +from sympy.core.numbers import (Rational, oo, pi) +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.exponential import exp +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.integrals.integrals import integrate +from sympy.simplify.simplify import simplify +from sympy.abc import omega, m, x +from sympy.physics.qho_1d import psi_n, E_n, coherent_state +from sympy.physics.quantum.constants import hbar + +nu = m * omega / hbar + + +def test_wavefunction(): + Psi = { + 0: (nu/pi)**Rational(1, 4) * exp(-nu * x**2 /2), + 1: (nu/pi)**Rational(1, 4) * sqrt(2*nu) * x * exp(-nu * x**2 /2), + 2: (nu/pi)**Rational(1, 4) * (2 * nu * x**2 - 1)/sqrt(2) * exp(-nu * x**2 /2), + 3: (nu/pi)**Rational(1, 4) * sqrt(nu/3) * (2 * nu * x**3 - 3 * x) * exp(-nu * x**2 /2) + } + for n in Psi: + assert simplify(psi_n(n, x, m, omega) - Psi[n]) == 0 + + +def test_norm(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + assert integrate(psi_n(i, x, 1, 1)**2, (x, -oo, oo)) == 1 + + +def test_orthogonality(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + for j in range(i + 1, n + 1): + assert integrate( + psi_n(i, x, 1, 1)*psi_n(j, x, 1, 1), (x, -oo, oo)) == 0 + + +def test_energies(n=1): + # Maximum "n" which is tested: + for i in range(n + 1): + assert E_n(i, omega) == hbar * omega * (i + S.Half) + +def test_coherent_state(n=10): + # Maximum "n" which is tested: + # test whether coherent state is the eigenstate of annihilation operator + alpha = Symbol("alpha") + for i in range(n + 1): + assert simplify(sqrt(n + 1) * coherent_state(n + 1, alpha)) == simplify(alpha * coherent_state(n, alpha)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9f4a499a7bee96d5fb5c76e83d84a72db5db8a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_secondquant.py @@ -0,0 +1,1280 @@ +from sympy.physics.secondquant import ( + Dagger, Bd, VarBosonicBasis, BBra, B, BKet, FixedBosonicBasis, + matrix_rep, apply_operators, InnerProduct, Commutator, KroneckerDelta, + AnnihilateBoson, CreateBoson, BosonicOperator, + F, Fd, FKet, BosonState, CreateFermion, AnnihilateFermion, + evaluate_deltas, AntiSymmetricTensor, contraction, NO, wicks, + PermutationOperator, simplify_index_permutations, + _sort_anticommuting_fermions, _get_ordered_dummies, + substitute_dummies, FockStateBosonKet, + ContractionAppliesOnlyToFermions +) + +from sympy.concrete.summations import Sum +from sympy.core.function import (Function, expand) +from sympy.core.numbers import (I, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import (Dummy, Symbol, symbols) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.printing.repr import srepr +from sympy.simplify.simplify import simplify + +from sympy.testing.pytest import slow, raises +from sympy.printing.latex import latex + + +def test_PermutationOperator(): + p, q, r, s = symbols('p,q,r,s') + f, g, h, i = map(Function, 'fghi') + P = PermutationOperator + assert P(p, q).get_permuted(f(p)*g(q)) == -f(q)*g(p) + assert P(p, q).get_permuted(f(p, q)) == -f(q, p) + assert P(p, q).get_permuted(f(p)) == f(p) + expr = (f(p)*g(q)*h(r)*i(s) + - f(q)*g(p)*h(r)*i(s) + - f(p)*g(q)*h(s)*i(r) + + f(q)*g(p)*h(s)*i(r)) + perms = [P(p, q), P(r, s)] + assert (simplify_index_permutations(expr, perms) == + P(p, q)*P(r, s)*f(p)*g(q)*h(r)*i(s)) + assert latex(P(p, q)) == 'P(pq)' + + +def test_index_permutations_with_dummies(): + a, b, c, d = symbols('a b c d') + p, q, r, s = symbols('p q r s', cls=Dummy) + f, g = map(Function, 'fg') + P = PermutationOperator + + # No dummy substitution necessary + expr = f(a, b, p, q) - f(b, a, p, q) + assert simplify_index_permutations( + expr, [P(a, b)]) == P(a, b)*f(a, b, p, q) + + # Cases where dummy substitution is needed + expected = P(a, b)*substitute_dummies(f(a, b, p, q)) + + expr = f(a, b, p, q) - f(b, a, q, p) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + expr = f(a, b, q, p) - f(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expected == substitute_dummies(result) + + # A case where nothing can be done + expr = f(a, b, q, p) - g(b, a, p, q) + result = simplify_index_permutations(expr, [P(a, b)]) + assert expr == result + + +def test_dagger(): + i, j, n, m = symbols('i,j,n,m') + assert Dagger(1) == 1 + assert Dagger(1.0) == 1.0 + assert Dagger(2*I) == -2*I + assert Dagger(S.Half*I/3.0) == I*Rational(-1, 2)/3.0 + assert Dagger(BKet([n])) == BBra([n]) + assert Dagger(B(0)) == Bd(0) + assert Dagger(Bd(0)) == B(0) + assert Dagger(B(n)) == Bd(n) + assert Dagger(Bd(n)) == B(n) + assert Dagger(B(0) + B(1)) == Bd(0) + Bd(1) + assert Dagger(n*m) == Dagger(n)*Dagger(m) # n, m commute + assert Dagger(B(n)*B(m)) == Bd(m)*Bd(n) + assert Dagger(B(n)**10) == Dagger(B(n))**10 + assert Dagger('a') == Dagger(Symbol('a')) + assert Dagger(Dagger('a')) == Symbol('a') + + +def test_operator(): + i, j = symbols('i,j') + o = BosonicOperator(i) + assert o.state == i + assert o.is_symbolic + o = BosonicOperator(1) + assert o.state == 1 + assert not o.is_symbolic + + +def test_create(): + i, j, n, m = symbols('i,j,n,m') + o = Bd(i) + assert latex(o) == "{b^\\dagger_{i}}" + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate(): + i, j, n, m = symbols('i,j,n,m') + o = B(i) + assert latex(o) == "b_{i}" + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + assert o.apply_operator(BKet([n])) == sqrt(n)*BKet([n - 1]) + o = B(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_basic_state(): + i, j, n, m = symbols('i,j,n,m') + s = BosonState([0, 1, 2, 3, 4]) + assert len(s) == 5 + assert s.args[0] == tuple(range(5)) + assert s.up(0) == BosonState([1, 1, 2, 3, 4]) + assert s.down(4) == BosonState([0, 1, 2, 3, 3]) + for i in range(5): + assert s.up(i).down(i) == s + assert s.down(0) == 0 + for i in range(5): + assert s[i] == i + s = BosonState([n, m]) + assert s.down(0) == BosonState([n - 1, m]) + assert s.up(0) == BosonState([n + 1, m]) + + +def test_basic_apply(): + n = symbols("n") + e = B(0)*BKet([n]) + assert apply_operators(e) == sqrt(n)*BKet([n - 1]) + e = Bd(0)*BKet([n]) + assert apply_operators(e) == sqrt(n + 1)*BKet([n + 1]) + + +def test_complex_apply(): + n, m = symbols("n,m") + o = Bd(0)*B(0)*Bd(1)*B(0) + e = apply_operators(o*BKet([n, m])) + answer = sqrt(n)*sqrt(m + 1)*(-1 + n)*BKet([-1 + n, 1 + m]) + assert expand(e) == expand(answer) + + +def test_number_operator(): + n = symbols("n") + o = Bd(0)*B(0) + e = apply_operators(o*BKet([n])) + assert e == n*BKet([n]) + + +def test_inner_product(): + i, j, k, l = symbols('i,j,k,l') + s1 = BBra([0]) + s2 = BKet([1]) + assert InnerProduct(s1, Dagger(s1)) == 1 + assert InnerProduct(s1, s2) == 0 + s1 = BBra([i, j]) + s2 = BKet([k, l]) + r = InnerProduct(s1, s2) + assert r == KroneckerDelta(i, k)*KroneckerDelta(j, l) + + +def test_symbolic_matrix_elements(): + n, m = symbols('n,m') + s1 = BBra([n]) + s2 = BKet([m]) + o = B(0) + e = apply_operators(s1*o*s2) + assert e == sqrt(m)*KroneckerDelta(n, m - 1) + + +def test_matrix_elements(): + b = VarBosonicBasis(5) + o = B(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i, i + 1] == sqrt(i + 1) + o = Bd(0) + m = matrix_rep(o, b) + for i in range(4): + assert m[i + 1, i] == sqrt(i + 1) + + +def test_fixed_bosonic_basis(): + b = FixedBosonicBasis(2, 2) + # assert b == [FockState((2, 0)), FockState((1, 1)), FockState((0, 2))] + state = b.state(1) + assert state == FockStateBosonKet((1, 1)) + assert b.index(state) == 1 + assert b.state(1) == b[1] + assert len(b) == 3 + assert str(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert repr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + assert srepr(b) == '[FockState((2, 0)), FockState((1, 1)), FockState((0, 2))]' + + +@slow +def test_sho(): + n, m = symbols('n,m') + h_n = Bd(n)*B(n)*(n + S.Half) + H = Sum(h_n, (n, 0, 5)) + o = H.doit(deep=False) + b = FixedBosonicBasis(2, 6) + m = matrix_rep(o, b) + # We need to double check these energy values to make sure that they + # are correct and have the proper degeneracies! + diag = [1, 2, 3, 3, 4, 5, 4, 5, 6, 7, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 11] + for i in range(len(diag)): + assert diag[i] == m[i, i] + + +def test_commutation(): + n, m = symbols("n,m", above_fermi=True) + c = Commutator(B(0), Bd(0)) + assert c == 1 + c = Commutator(Bd(0), B(0)) + assert c == -1 + c = Commutator(B(n), Bd(0)) + assert c == KroneckerDelta(n, 0) + c = Commutator(B(0), B(0)) + assert c == 0 + c = Commutator(B(0), Bd(0)) + e = simplify(apply_operators(c*BKet([n]))) + assert e == BKet([n]) + c = Commutator(B(0), B(1)) + e = simplify(apply_operators(c*BKet([n, m]))) + assert e == 0 + + c = Commutator(F(m), Fd(m)) + assert c == +1 - 2*NO(Fd(m)*F(m)) + c = Commutator(Fd(m), F(m)) + assert c.expand() == -1 + 2*NO(Fd(m)*F(m)) + + C = Commutator + X, Y, Z = symbols('X,Y,Z', commutative=False) + assert C(C(X, Y), Z) != 0 + assert C(C(X, Z), Y) != 0 + assert C(Y, C(X, Z)) != 0 + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + D = KroneckerDelta + + assert C(Fd(a), F(i)) == -2*NO(F(i)*Fd(a)) + assert C(Fd(j), NO(Fd(a)*F(i))).doit(wicks=True) == -D(j, i)*Fd(a) + assert C(Fd(a)*F(i), Fd(b)*F(j)).doit(wicks=True) == 0 + + c1 = Commutator(F(a), Fd(a)) + assert Commutator.eval(c1, c1) == 0 + c = Commutator(Fd(a)*F(i),Fd(b)*F(j)) + assert latex(c) == r'\left[{a^\dagger_{a}} a_{i},{a^\dagger_{b}} a_{j}\right]' + assert repr(c) == 'Commutator(CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j))' + assert str(c) == '[CreateFermion(a)*AnnihilateFermion(i),CreateFermion(b)*AnnihilateFermion(j)]' + + +def test_create_f(): + i, j, n, m = symbols('i,j,n,m') + o = Fd(i) + assert isinstance(o, CreateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Fd(1) + assert o.apply_operator(FKet([n])) == FKet([1, n]) + assert o.apply_operator(FKet([n])) == -FKet([n, 1]) + o = Fd(n) + assert o.apply_operator(FKet([])) == FKet([n]) + + vacuum = FKet([], fermi_level=4) + assert vacuum == FKet([], fermi_level=4) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + + assert Fd(i).apply_operator(FKet([i, j, k], 4)) == FKet([j, k], 4) + assert Fd(a).apply_operator(FKet([i, b, k], 4)) == FKet([a, i, b, k], 4) + + assert Dagger(B(p)).apply_operator(q) == q*CreateBoson(p) + assert repr(Fd(p)) == 'CreateFermion(p)' + assert srepr(Fd(p)) == "CreateFermion(Symbol('p'))" + assert latex(Fd(p)) == r'{a^\dagger_{p}}' + + +def test_annihilate_f(): + i, j, n, m = symbols('i,j,n,m') + o = F(i) + assert isinstance(o, AnnihilateFermion) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = F(1) + assert o.apply_operator(FKet([1, n])) == FKet([n]) + assert o.apply_operator(FKet([n, 1])) == -FKet([n]) + o = F(n) + assert o.apply_operator(FKet([n])) == FKet([]) + + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + assert F(i).apply_operator(FKet([i, j, k], 4)) == 0 + assert F(a).apply_operator(FKet([i, b, k], 4)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 3)) == 0 + assert F(l).apply_operator(FKet([i, j, k], 4)) == FKet([l, i, j, k], 4) + assert str(F(p)) == 'f(p)' + assert repr(F(p)) == 'AnnihilateFermion(p)' + assert srepr(F(p)) == "AnnihilateFermion(Symbol('p'))" + assert latex(F(p)) == 'a_{p}' + + +def test_create_b(): + i, j, n, m = symbols('i,j,n,m') + o = Bd(i) + assert isinstance(o, CreateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = Bd(0) + assert o.apply_operator(BKet([n])) == sqrt(n + 1)*BKet([n + 1]) + o = Bd(n) + assert o.apply_operator(BKet([n])) == o*BKet([n]) + + +def test_annihilate_b(): + i, j, n, m = symbols('i,j,n,m') + o = B(i) + assert isinstance(o, AnnihilateBoson) + o = o.subs(i, j) + assert o.atoms(Symbol) == {j} + o = B(0) + + +def test_wicks(): + p, q, r, s = symbols('p,q,r,s', above_fermi=True) + + # Testing for particles only + + str = F(p)*Fd(q) + assert wicks(str) == NO(F(p)*Fd(q)) + KroneckerDelta(p, q) + str = Fd(p)*F(q) + assert wicks(str) == NO(Fd(p)*F(q)) + + str = F(p)*Fd(q)*F(r)*Fd(s) + nstr = wicks(str) + fasit = NO( + KroneckerDelta(p, q)*KroneckerDelta(r, s) + + KroneckerDelta(p, q)*AnnihilateFermion(r)*CreateFermion(s) + + KroneckerDelta(r, s)*AnnihilateFermion(p)*CreateFermion(q) + - KroneckerDelta(p, s)*AnnihilateFermion(r)*CreateFermion(q) + - AnnihilateFermion(p)*AnnihilateFermion(r)*CreateFermion(q)*CreateFermion(s)) + assert nstr == fasit + + assert (p*q*nstr).expand() == wicks(p*q*str) + assert (nstr*p*q*2).expand() == wicks(str*p*q*2) + + # Testing CC equations particles and holes + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (wicks(F(a)*NO(F(i)*F(j))*Fd(b)) == + NO(F(a)*F(i)*F(j)*Fd(b)) + + KroneckerDelta(a, b)*NO(F(i)*F(j))) + assert (wicks(F(a)*NO(F(i)*F(j)*F(k))*Fd(b)) == + NO(F(a)*F(i)*F(j)*F(k)*Fd(b)) - + KroneckerDelta(a, b)*NO(F(i)*F(j)*F(k))) + + expr = wicks(Fd(i)*NO(Fd(j)*F(k))*F(l)) + assert (expr == + -KroneckerDelta(i, k)*NO(Fd(j)*F(l)) - + KroneckerDelta(j, l)*NO(Fd(i)*F(k)) - + KroneckerDelta(i, k)*KroneckerDelta(j, l) + + KroneckerDelta(i, l)*NO(Fd(j)*F(k)) + + NO(Fd(i)*Fd(j)*F(k)*F(l))) + expr = wicks(F(a)*NO(F(b)*Fd(c))*Fd(d)) + assert (expr == + -KroneckerDelta(a, c)*NO(F(b)*Fd(d)) - + KroneckerDelta(b, d)*NO(F(a)*Fd(c)) - + KroneckerDelta(a, c)*KroneckerDelta(b, d) + + KroneckerDelta(a, d)*NO(F(b)*Fd(c)) + + NO(F(a)*F(b)*Fd(c)*Fd(d))) + + +def test_NO(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + assert (NO(Fd(p)*F(q) + Fd(a)*F(b)) == + NO(Fd(p)*F(q)) + NO(Fd(a)*F(b))) + assert (NO(Fd(i)*NO(F(j)*Fd(a))) == + NO(Fd(i)*F(j)*Fd(a))) + assert NO(1) == 1 + assert NO(i) == i + assert (NO(Fd(a)*Fd(b)*(F(c) + F(d))) == + NO(Fd(a)*Fd(b)*F(c)) + + NO(Fd(a)*Fd(b)*F(d))) + + assert NO(Fd(a)*F(b))._remove_brackets() == Fd(a)*F(b) + assert NO(F(j)*Fd(i))._remove_brackets() == F(j)*Fd(i) + + assert (NO(Fd(p)*F(q)).subs(Fd(p), Fd(a) + Fd(i)) == + NO(Fd(a)*F(q)) + NO(Fd(i)*F(q))) + assert (NO(Fd(p)*F(q)).subs(F(q), F(a) + F(i)) == + NO(Fd(p)*F(a)) + NO(Fd(p)*F(i))) + + expr = NO(Fd(p)*F(q))._remove_brackets() + assert wicks(expr) == NO(expr) + + assert NO(Fd(a)*F(b)) == - NO(F(b)*Fd(a)) + + no = NO(Fd(a)*F(i)*F(b)*Fd(j)) + l1 = list(no.iter_q_creators()) + assert l1 == [0, 1] + l2 = list(no.iter_q_annihilators()) + assert l2 == [3, 2] + no = NO(Fd(a)*Fd(i)) + assert no.has_q_creators == 1 + assert no.has_q_annihilators == -1 + assert str(no) == ':CreateFermion(a)*CreateFermion(i):' + assert repr(no) == 'NO(CreateFermion(a)*CreateFermion(i))' + assert latex(no) == r'\left\{{a^\dagger_{a}} {a^\dagger_{i}}\right\}' + raises(NotImplementedError, lambda: NO(Bd(p)*F(q))) + + +def test_sorting(): + i, j = symbols('i,j', below_fermi=True) + a, b = symbols('a,b', above_fermi=True) + p, q = symbols('p,q') + + # p, q + assert _sort_anticommuting_fermions([Fd(p), F(q)]) == ([Fd(p), F(q)], 0) + assert _sort_anticommuting_fermions([F(p), Fd(q)]) == ([Fd(q), F(p)], 1) + + # i, p + assert _sort_anticommuting_fermions([F(p), Fd(i)]) == ([F(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), F(p)]) == ([F(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([Fd(p), Fd(i)]) == ([Fd(p), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(p)]) == ([Fd(p), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(p), F(i)]) == ([F(i), F(p)], 1) + assert _sort_anticommuting_fermions([F(i), F(p)]) == ([F(i), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), F(i)]) == ([F(i), Fd(p)], 1) + assert _sort_anticommuting_fermions([F(i), Fd(p)]) == ([F(i), Fd(p)], 0) + + # a, p + assert _sort_anticommuting_fermions([F(p), Fd(a)]) == ([Fd(a), F(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), F(p)]) == ([Fd(a), F(p)], 0) + assert _sort_anticommuting_fermions([Fd(p), Fd(a)]) == ([Fd(a), Fd(p)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(p)]) == ([Fd(a), Fd(p)], 0) + assert _sort_anticommuting_fermions([F(p), F(a)]) == ([F(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), F(p)]) == ([F(p), F(a)], 1) + assert _sort_anticommuting_fermions([Fd(p), F(a)]) == ([Fd(p), F(a)], 0) + assert _sort_anticommuting_fermions([F(a), Fd(p)]) == ([Fd(p), F(a)], 1) + + # i, a + assert _sort_anticommuting_fermions([F(i), Fd(j)]) == ([F(i), Fd(j)], 0) + assert _sort_anticommuting_fermions([Fd(j), F(i)]) == ([F(i), Fd(j)], 1) + assert _sort_anticommuting_fermions([Fd(a), Fd(i)]) == ([Fd(a), Fd(i)], 0) + assert _sort_anticommuting_fermions([Fd(i), Fd(a)]) == ([Fd(a), Fd(i)], 1) + assert _sort_anticommuting_fermions([F(a), F(i)]) == ([F(i), F(a)], 1) + assert _sort_anticommuting_fermions([F(i), F(a)]) == ([F(i), F(a)], 0) + + +def test_contraction(): + i, j, k, l = symbols('i,j,k,l', below_fermi=True) + a, b, c, d = symbols('a,b,c,d', above_fermi=True) + p, q, r, s = symbols('p,q,r,s') + assert contraction(Fd(i), F(j)) == KroneckerDelta(i, j) + assert contraction(F(a), Fd(b)) == KroneckerDelta(a, b) + assert contraction(F(a), Fd(i)) == 0 + assert contraction(Fd(a), F(i)) == 0 + assert contraction(F(i), Fd(a)) == 0 + assert contraction(Fd(i), F(a)) == 0 + assert contraction(Fd(i), F(p)) == KroneckerDelta(i, p) + restr = evaluate_deltas(contraction(Fd(p), F(q))) + assert restr.is_only_below_fermi + restr = evaluate_deltas(contraction(F(p), Fd(q))) + assert restr.is_only_above_fermi + raises(ContractionAppliesOnlyToFermions, lambda: contraction(B(a), Fd(b))) + + +def test_evaluate_deltas(): + i, j, k = symbols('i,j,k') + + r = KroneckerDelta(i, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(i, 0) * KroneckerDelta(j, k) + + r = KroneckerDelta(1, j) * KroneckerDelta(j, k) + assert evaluate_deltas(r) == KroneckerDelta(1, k) + + r = KroneckerDelta(j, 2) * KroneckerDelta(k, j) + assert evaluate_deltas(r) == KroneckerDelta(2, k) + + r = KroneckerDelta(i, 0) * KroneckerDelta(i, j) * KroneckerDelta(j, 1) + assert evaluate_deltas(r) == 0 + + r = (KroneckerDelta(0, i) * KroneckerDelta(0, j) + * KroneckerDelta(1, j) * KroneckerDelta(1, j)) + assert evaluate_deltas(r) == 0 + + +def test_Tensors(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + p, q, r, s = symbols('p q r s') + + AT = AntiSymmetricTensor + assert AT('t', (a, b), (i, j)) == -AT('t', (b, a), (i, j)) + assert AT('t', (a, b), (i, j)) == AT('t', (b, a), (j, i)) + assert AT('t', (a, b), (i, j)) == -AT('t', (a, b), (j, i)) + assert AT('t', (a, a), (i, j)) == 0 + assert AT('t', (a, b), (i, i)) == 0 + assert AT('t', (a, b, c), (i, j)) == -AT('t', (b, a, c), (i, j)) + assert AT('t', (a, b, c), (i, j, k)) == AT('t', (b, a, c), (i, k, j)) + + tabij = AT('t', (a, b), (i, j)) + assert tabij.has(a) + assert tabij.has(b) + assert tabij.has(i) + assert tabij.has(j) + assert tabij.subs(b, c) == AT('t', (a, c), (i, j)) + assert (2*tabij).subs(i, c) == 2*AT('t', (a, b), (c, j)) + assert tabij.symbol == Symbol('t') + assert latex(tabij) == '{t^{ab}_{ij}}' + assert str(tabij) == 't((_a, _b),(_i, _j))' + + assert AT('t', (a, a), (i, j)).subs(a, b) == AT('t', (b, b), (i, j)) + assert AT('t', (a, i), (a, j)).subs(a, b) == AT('t', (b, i), (b, j)) + + +def test_fully_contracted(): + i, j, k, l = symbols('i j k l', below_fermi=True) + a, b, c, d = symbols('a b c d', above_fermi=True) + p, q, r, s = symbols('p q r s', cls=Dummy) + + Fock = (AntiSymmetricTensor('f', (p,), (q,))* + NO(Fd(p)*F(q))) + V = (AntiSymmetricTensor('v', (p, q), (r, s))* + NO(Fd(p)*Fd(q)*F(s)*F(r)))/4 + + Fai = wicks(NO(Fd(i)*F(a))*Fock, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Fai == AntiSymmetricTensor('f', (a,), (i,)) + Vabij = wicks(NO(Fd(i)*Fd(j)*F(b)*F(a))*V, + keep_only_fully_contracted=True, + simplify_kronecker_deltas=True) + assert Vabij == AntiSymmetricTensor('v', (a, b), (i, j)) + + +def test_substitute_dummies_without_dummies(): + i, j = symbols('i,j') + assert substitute_dummies(att(i, j) + 2) == att(i, j) + 2 + assert substitute_dummies(att(i, j) + 1) == att(i, j) + 1 + + +def test_substitute_dummies_NO_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*NO(Fd(i)*F(j)) + - att(j, i)*NO(Fd(j)*F(i))) == 0 + + +def test_substitute_dummies_SQ_operator(): + i, j = symbols('i j', cls=Dummy) + assert substitute_dummies(att(i, j)*Fd(i)*F(j) + - att(j, i)*Fd(j)*F(i)) == 0 + + +def test_substitute_dummies_new_indices(): + i, j = symbols('i j', below_fermi=True, cls=Dummy) + a, b = symbols('a b', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + f = Function('f') + assert substitute_dummies(f(i, a, p) - f(j, b, q), new_indices=True) == 0 + + +def test_substitute_dummies_substitution_order(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + f = Function('f') + from sympy.utilities.iterables import variations + for permut in variations([i, j, k, l], 4): + assert substitute_dummies(f(*permut) - f(i, j, k, l)) == 0 + + +def test_dummy_order_inner_outer_lines_VT1T1T1(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + v(k, l, c, d)*t(c, ii)*t(d, l)*t(aa, k), + v(l, k, c, d)*t(c, ii)*t(d, k)*t(aa, l), + v(k, l, d, c)*t(d, ii)*t(c, l)*t(aa, k), + v(l, k, d, c)*t(d, ii)*t(c, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + exprs = [ + # permut t <=> swapping external lines, not equivalent + # except if v has certain symmetries. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(k, l, c, d)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut v <=> swapping external lines, not equivalent + # except if v has certain symmetries. + # + # Note that in contrast to above, these permutations have identical + # dummy order. That is because the proximity to external indices + # has higher influence on the canonical dummy ordering than the + # position of a dummy on the factors. In fact, the terms here are + # similar in structure as the result of the dummy substitutions above. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(l, k, d, c)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + exprs = [ + # permut t and v <=> swapping internal lines, equivalent. + # Canonical dummy order is different, and a consistent + # substitution reveals the equivalence. + v(k, l, c, d)*t(c, ii)*t(d, jj)*t(aa, k)*t(bb, l), + v(k, l, d, c)*t(c, jj)*t(d, ii)*t(aa, k)*t(bb, l), + v(l, k, c, d)*t(c, ii)*t(d, jj)*t(bb, k)*t(aa, l), + v(l, k, d, c)*t(c, jj)*t(d, ii)*t(bb, k)*t(aa, l), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_get_subNO(): + p, q, r = symbols('p,q,r') + assert NO(F(p)*F(q)*F(r)).get_subNO(1) == NO(F(p)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(0) == NO(F(q)*F(r)) + assert NO(F(p)*F(q)*F(r)).get_subNO(2) == NO(F(p)*F(q)) + + +def test_equivalent_internal_lines_VT1T1(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ # permute v. Different dummy order. Not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, i)*t(b, j), + v(i, j, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, b, a)*t(a, i)*t(b, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + v(i, j, a, b)*t(a, i)*t(b, j), + v(i, j, a, b)*t(b, i)*t(a, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + v(i, j, a, b)*t(a, i)*t(b, j), + v(j, i, a, b)*t(a, j)*t(b, i), + v(i, j, b, a)*t(b, i)*t(a, j), + v(j, i, b, a)*t(b, j)*t(a, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(ijcd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + # v(abcd)t(abij)t(jicd) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + # v(abcd)t(abij)t(cdij) + template = v(p1, p2, p3, p4)*t(p1, p2, i, j)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + template = v(p1, p2, p3, p4)*t(p1, p2, j, i)*t(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert dums(base) != dums(expr) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + exprs = [ + # permute v. Same dummy order, not equivalent. + # + # This test show that the dummy order may not be sensitive to all + # index permutations. The following expressions have identical + # structure as the resulting terms from of the dummy substitutions + # in the test above. Here, all expressions have the same dummy + # order, so they cannot be simplified by means of dummy + # substitution. In order to simplify further, it is necessary to + # exploit symmetries in the objects, for instance if t or v is + # antisymmetric. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, i, j), + v(i, j, b, a)*t(a, b, i, j), + v(j, i, b, a)*t(a, b, i, j), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) == dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + v(i, j, a, b)*t(a, b, i, j), + v(i, j, a, b)*t(b, a, i, j), + v(i, j, a, b)*t(a, b, j, i), + v(i, j, a, b)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + v(i, j, a, b)*t(a, b, i, j), + v(j, i, a, b)*t(a, b, j, i), + v(i, j, b, a)*t(b, a, i, j), + v(j, i, b, a)*t(b, a, j, i), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(d, bb, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(d, bb, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(c, bb, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + v(k, l, c, d)*t(c, aa, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(c, aa, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(d, aa, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(d, aa, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + v = Function('v') + t = Function('t') + dums = _get_ordered_dummies + + exprs = [ + v(k, l, c, d)*t(aa, c, ii, k)*t(bb, d, jj, l), + v(l, k, c, d)*t(aa, c, ii, l)*t(bb, d, jj, k), + v(k, l, d, c)*t(aa, d, ii, k)*t(bb, c, jj, l), + v(l, k, d, c)*t(aa, d, ii, l)*t(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert dums(exprs[0]) != dums(permut) + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_well_defined(): + aa, bb = symbols('a b', above_fermi=True) + k, l, m = symbols('k l m', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + + A = Function('A') + B = Function('B') + C = Function('C') + dums = _get_ordered_dummies + + # We go through all key components in the order of increasing priority, + # and consider only fully orderable expressions. Non-orderable expressions + # are tested elsewhere. + + # pos in first factor determines sort order + assert dums(A(k, l)*B(l, k)) == [k, l] + assert dums(A(l, k)*B(l, k)) == [l, k] + assert dums(A(k, l)*B(k, l)) == [k, l] + assert dums(A(l, k)*B(k, l)) == [l, k] + + # factors involving the index + assert dums(A(k, l)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(l, m)*C(m, k)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(k, l)*B(m, l)*C(m, k)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(k, m)) == [l, k, m] + assert dums(A(l, k)*B(m, l)*C(m, k)) == [l, k, m] + + # same, but with factor order determined by non-dummies + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(k, aa, l)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(l, bb, m)*A(bb, m, k)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, k, m)) == [l, k, m] + assert dums(A(l, aa, k)*A(m, bb, l)*A(bb, m, k)) == [l, k, m] + + # index range + assert dums(A(p, c, k)*B(p, c, k)) == [k, c, p] + assert dums(A(p, k, c)*B(p, c, k)) == [k, c, p] + assert dums(A(c, k, p)*B(p, c, k)) == [k, c, p] + assert dums(A(c, p, k)*B(p, c, k)) == [k, c, p] + assert dums(A(k, c, p)*B(p, c, k)) == [k, c, p] + assert dums(A(k, p, c)*B(p, c, k)) == [k, c, p] + assert dums(B(p, c, k)*A(p, c, k)) == [k, c, p] + assert dums(B(p, k, c)*A(p, c, k)) == [k, c, p] + assert dums(B(c, k, p)*A(p, c, k)) == [k, c, p] + assert dums(B(c, p, k)*A(p, c, k)) == [k, c, p] + assert dums(B(k, c, p)*A(p, c, k)) == [k, c, p] + assert dums(B(k, p, c)*A(p, c, k)) == [k, c, p] + + +def test_dummy_order_ambiguous(): + aa, bb = symbols('a b', above_fermi=True) + i, j, k, l, m = symbols('i j k l m', below_fermi=True, cls=Dummy) + a, b, c, d, e = symbols('a b c d e', above_fermi=True, cls=Dummy) + p, q = symbols('p q', cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + p5, p6, p7, p8 = symbols('p5 p6 p7 p8', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + h5, h6, h7, h8 = symbols('h5 h6 h7 h8', below_fermi=True, cls=Dummy) + + A = Function('A') + B = Function('B') + + from sympy.utilities.iterables import variations + + # A*A*A*A*B -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*B(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A*A*A -- an arbitrary index is assigned and the rest are figured out + template = A(p1, p2)*A(p4, p1)*A(p2, p3)*A(p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # A*A*A -- ordering of p5 and p4 is used to figure out the rest + template = A(p1, p2, p4, p1)*A(p2, p3, p3, p5)*A(p5, p4) + permutator = variations([a, b, c, d, e], 5) + base = template.subs(zip([p1, p2, p3, p4, p5], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4, p5], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def atv(*args): + return AntiSymmetricTensor('v', args[:2], args[2:] ) + + +def att(*args): + if len(args) == 4: + return AntiSymmetricTensor('t', args[:2], args[2:] ) + elif len(args) == 2: + return AntiSymmetricTensor('t', (args[0],), (args[1],)) + + +def test_dummy_order_inner_outer_lines_VT1T1T1_AT(): + ii = symbols('i', below_fermi=True) + aa = symbols('a', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T1 terms with V*T1*T1*T1 + # t^{a}_{k} t^{c}_{i} t^{d}_{l} v^{lk}_{dc} + exprs = [ + # permut v and t <=> swapping internal lines, equivalent + # irrespective of symmetries in v + atv(k, l, c, d)*att(c, ii)*att(d, l)*att(aa, k), + atv(l, k, c, d)*att(c, ii)*att(d, k)*att(aa, l), + atv(k, l, d, c)*att(d, ii)*att(c, l)*att(aa, k), + atv(l, k, d, c)*att(d, ii)*att(c, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_dummy_order_inner_outer_lines_VT1T1T1T1_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + # Coupled-Cluster T2 terms with V*T1*T1*T1*T1 + # non-equivalent substitutions (change of sign) + exprs = [ + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(aa, k)*att(bb, l), + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == -substitute_dummies(permut) + + # equivalent substitutions + exprs = [ + atv(k, l, c, d)*att(c, ii)*att(d, jj)*att(aa, k)*att(bb, l), + # permut t <=> swapping external lines + atv(k, l, c, d)*att(c, jj)*att(d, ii)*att(bb, k)*att(aa, l), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT1T1_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ # permute v. Different dummy order. Not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, i)*att(b, j), + atv(i, j, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v. Different dummy order. Equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, b, a)*att(a, i)*att(b, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + exprs = [ # permute t. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(i, j, a, b)*att(b, i)*att(a, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Different dummy order, equivalent + atv(i, j, a, b)*att(a, i)*att(b, j), + atv(j, i, a, b)*att(a, j)*att(b, i), + atv(i, j, b, a)*att(b, i)*att(a, j), + atv(j, i, b, a)*att(b, j)*att(a, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_equivalent_internal_lines_VT2conjT2_AT(): + # this diagram requires special handling in TCE + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(ijcd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + # atv(abcd)att(abij)att(jicd) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(j, i, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(i, j, p3, p4) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2conjT2_ambiguous_order_AT(): + # These diagrams invokes _determine_ambiguous() because the + # dummies can not be ordered unambiguously by the key alone + i, j, k, l, m, n = symbols('i j k l m n', below_fermi=True, cls=Dummy) + a, b, c, d, e, f = symbols('a b c d e f', above_fermi=True, cls=Dummy) + p1, p2, p3, p4 = symbols('p1 p2 p3 p4', above_fermi=True, cls=Dummy) + h1, h2, h3, h4 = symbols('h1 h2 h3 h4', below_fermi=True, cls=Dummy) + + from sympy.utilities.iterables import variations + + # atv(abcd)att(abij)att(cdij) + template = atv(p1, p2, p3, p4)*att(p1, p2, i, j)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + template = atv(p1, p2, p3, p4)*att(p1, p2, j, i)*att(p3, p4, i, j) + permutator = variations([a, b, c, d], 4) + base = template.subs(zip([p1, p2, p3, p4], next(permutator))) + for permut in permutator: + subslist = zip([p1, p2, p3, p4], permut) + expr = template.subs(subslist) + assert substitute_dummies(expr) == substitute_dummies(base) + + +def test_equivalent_internal_lines_VT2_AT(): + i, j, k, l = symbols('i j k l', below_fermi=True, cls=Dummy) + a, b, c, d = symbols('a b c d', above_fermi=True, cls=Dummy) + + exprs = [ + # permute v. Same dummy order, not equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, i, j), + atv(i, j, b, a)*att(a, b, i, j), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ + # permute t. + atv(i, j, a, b)*att(a, b, i, j), + atv(i, j, a, b)*att(b, a, i, j), + atv(i, j, a, b)*att(a, b, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) != substitute_dummies(permut) + + exprs = [ # permute v and t. Relabelling of dummies should be equivalent. + atv(i, j, a, b)*att(a, b, i, j), + atv(j, i, a, b)*att(a, b, j, i), + atv(i, j, b, a)*att(b, a, i, j), + atv(j, i, b, a)*att(b, a, j, i), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_VT2T2_AT(): + ii, jj = symbols('i j', below_fermi=True) + aa, bb = symbols('a b', above_fermi=True) + k, l = symbols('k l', below_fermi=True, cls=Dummy) + c, d = symbols('c d', above_fermi=True, cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(d, bb, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(d, bb, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(c, bb, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(c, bb, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + exprs = [ + atv(k, l, c, d)*att(c, aa, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(c, aa, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(d, aa, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(d, aa, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_internal_external_pqrs_AT(): + ii, jj = symbols('i j') + aa, bb = symbols('a b') + k, l = symbols('k l', cls=Dummy) + c, d = symbols('c d', cls=Dummy) + + exprs = [ + atv(k, l, c, d)*att(aa, c, ii, k)*att(bb, d, jj, l), + atv(l, k, c, d)*att(aa, c, ii, l)*att(bb, d, jj, k), + atv(k, l, d, c)*att(aa, d, ii, k)*att(bb, c, jj, l), + atv(l, k, d, c)*att(aa, d, ii, l)*att(bb, c, jj, k), + ] + for permut in exprs[1:]: + assert substitute_dummies(exprs[0]) == substitute_dummies(permut) + + +def test_issue_19661(): + a = Symbol('0') + assert latex(Commutator(Bd(a)**2, B(a)) + ) == '- \\left[b_{0},{b^\\dagger_{0}}^{2}\\right]' + + +def test_canonical_ordering_AntiSymmetricTensor(): + v = symbols("v") + + c, d = symbols(('c','d'), above_fermi=True, + cls=Dummy) + k, l = symbols(('k','l'), below_fermi=True, + cls=Dummy) + + # formerly, the left gave either the left or the right + assert AntiSymmetricTensor(v, (k, l), (d, c) + ) == -AntiSymmetricTensor(v, (l, k), (d, c)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_sho.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_sho.py new file mode 100644 index 0000000000000000000000000000000000000000..7248838b4bb9ad280fd4211bbe208063b65adcf5 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/tests/test_sho.py @@ -0,0 +1,21 @@ +from sympy.core import symbols, Rational, Function, diff +from sympy.physics.sho import R_nl, E_nl +from sympy.simplify.simplify import simplify + + +def test_sho_R_nl(): + omega, r = symbols('omega r') + l = symbols('l', integer=True) + u = Function('u') + + # check that it obeys the Schrodinger equation + for n in range(5): + schreq = ( -diff(u(r), r, 2)/2 + ((l*(l + 1))/(2*r**2) + + omega**2*r**2/2 - E_nl(n, l, omega))*u(r) ) + result = schreq.subs(u(r), r*R_nl(n, l, omega/2, r)) + assert simplify(result.doit()) == 0 + + +def test_energy(): + n, l, hw = symbols('n l hw') + assert simplify(E_nl(n, l, hw) - (2*n + l + Rational(3, 2))*hw) == 0 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..759889695d38c6e78237cc64974da3ecca6425cd --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__init__.py @@ -0,0 +1,265 @@ +from .unit_definitions import ( + percent, percents, + permille, + rad, radian, radians, + deg, degree, degrees, + sr, steradian, steradians, + mil, angular_mil, angular_mils, + m, meter, meters, + kg, kilogram, kilograms, + s, second, seconds, + A, ampere, amperes, + K, kelvin, kelvins, + mol, mole, moles, + cd, candela, candelas, + g, gram, grams, + mg, milligram, milligrams, + ug, microgram, micrograms, + t, tonne, metric_ton, + newton, newtons, N, + joule, joules, J, + watt, watts, W, + pascal, pascals, Pa, pa, + hertz, hz, Hz, + coulomb, coulombs, C, + volt, volts, v, V, + ohm, ohms, + siemens, S, mho, mhos, + farad, farads, F, + henry, henrys, H, + tesla, teslas, T, + weber, webers, Wb, wb, + optical_power, dioptre, D, + lux, lx, + katal, kat, + gray, Gy, + becquerel, Bq, + km, kilometer, kilometers, + dm, decimeter, decimeters, + cm, centimeter, centimeters, + mm, millimeter, millimeters, + um, micrometer, micrometers, micron, microns, + nm, nanometer, nanometers, + pm, picometer, picometers, + ft, foot, feet, + inch, inches, + yd, yard, yards, + mi, mile, miles, + nmi, nautical_mile, nautical_miles, + ha, hectare, + l, L, liter, liters, + dl, dL, deciliter, deciliters, + cl, cL, centiliter, centiliters, + ml, mL, milliliter, milliliters, + ms, millisecond, milliseconds, + us, microsecond, microseconds, + ns, nanosecond, nanoseconds, + ps, picosecond, picoseconds, + minute, minutes, + h, hour, hours, + day, days, + anomalistic_year, anomalistic_years, + sidereal_year, sidereal_years, + tropical_year, tropical_years, + common_year, common_years, + julian_year, julian_years, + draconic_year, draconic_years, + gaussian_year, gaussian_years, + full_moon_cycle, full_moon_cycles, + year, years, + G, gravitational_constant, + c, speed_of_light, + elementary_charge, + hbar, + planck, + eV, electronvolt, electronvolts, + avogadro_number, + avogadro, avogadro_constant, + boltzmann, boltzmann_constant, + stefan, stefan_boltzmann_constant, + R, molar_gas_constant, + faraday_constant, + josephson_constant, + von_klitzing_constant, + Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant, + me, electron_rest_mass, + gee, gees, acceleration_due_to_gravity, + u0, magnetic_constant, vacuum_permeability, + e0, electric_constant, vacuum_permittivity, + Z0, vacuum_impedance, + coulomb_constant, coulombs_constant, electric_force_constant, + atmosphere, atmospheres, atm, + kPa, kilopascal, + bar, bars, + pound, pounds, + psi, + dHg0, + mmHg, torr, + mmu, mmus, milli_mass_unit, + quart, quarts, + angstrom, angstroms, + ly, lightyear, lightyears, + au, astronomical_unit, astronomical_units, + planck_mass, + planck_time, + planck_temperature, + planck_length, + planck_charge, + planck_area, + planck_volume, + planck_momentum, + planck_energy, + planck_force, + planck_power, + planck_density, + planck_energy_density, + planck_intensity, + planck_angular_frequency, + planck_pressure, + planck_current, + planck_voltage, + planck_impedance, + planck_acceleration, + bit, bits, + byte, + kibibyte, kibibytes, + mebibyte, mebibytes, + gibibyte, gibibytes, + tebibyte, tebibytes, + pebibyte, pebibytes, + exbibyte, exbibytes, + curie, rutherford +) + +__all__ = [ + 'percent', 'percents', + 'permille', + 'rad', 'radian', 'radians', + 'deg', 'degree', 'degrees', + 'sr', 'steradian', 'steradians', + 'mil', 'angular_mil', 'angular_mils', + 'm', 'meter', 'meters', + 'kg', 'kilogram', 'kilograms', + 's', 'second', 'seconds', + 'A', 'ampere', 'amperes', + 'K', 'kelvin', 'kelvins', + 'mol', 'mole', 'moles', + 'cd', 'candela', 'candelas', + 'g', 'gram', 'grams', + 'mg', 'milligram', 'milligrams', + 'ug', 'microgram', 'micrograms', + 't', 'tonne', 'metric_ton', + 'newton', 'newtons', 'N', + 'joule', 'joules', 'J', + 'watt', 'watts', 'W', + 'pascal', 'pascals', 'Pa', 'pa', + 'hertz', 'hz', 'Hz', + 'coulomb', 'coulombs', 'C', + 'volt', 'volts', 'v', 'V', + 'ohm', 'ohms', + 'siemens', 'S', 'mho', 'mhos', + 'farad', 'farads', 'F', + 'henry', 'henrys', 'H', + 'tesla', 'teslas', 'T', + 'weber', 'webers', 'Wb', 'wb', + 'optical_power', 'dioptre', 'D', + 'lux', 'lx', + 'katal', 'kat', + 'gray', 'Gy', + 'becquerel', 'Bq', + 'km', 'kilometer', 'kilometers', + 'dm', 'decimeter', 'decimeters', + 'cm', 'centimeter', 'centimeters', + 'mm', 'millimeter', 'millimeters', + 'um', 'micrometer', 'micrometers', 'micron', 'microns', + 'nm', 'nanometer', 'nanometers', + 'pm', 'picometer', 'picometers', + 'ft', 'foot', 'feet', + 'inch', 'inches', + 'yd', 'yard', 'yards', + 'mi', 'mile', 'miles', + 'nmi', 'nautical_mile', 'nautical_miles', + 'ha', 'hectare', + 'l', 'L', 'liter', 'liters', + 'dl', 'dL', 'deciliter', 'deciliters', + 'cl', 'cL', 'centiliter', 'centiliters', + 'ml', 'mL', 'milliliter', 'milliliters', + 'ms', 'millisecond', 'milliseconds', + 'us', 'microsecond', 'microseconds', + 'ns', 'nanosecond', 'nanoseconds', + 'ps', 'picosecond', 'picoseconds', + 'minute', 'minutes', + 'h', 'hour', 'hours', + 'day', 'days', + 'anomalistic_year', 'anomalistic_years', + 'sidereal_year', 'sidereal_years', + 'tropical_year', 'tropical_years', + 'common_year', 'common_years', + 'julian_year', 'julian_years', + 'draconic_year', 'draconic_years', + 'gaussian_year', 'gaussian_years', + 'full_moon_cycle', 'full_moon_cycles', + 'year', 'years', + 'G', 'gravitational_constant', + 'c', 'speed_of_light', + 'elementary_charge', + 'hbar', + 'planck', + 'eV', 'electronvolt', 'electronvolts', + 'avogadro_number', + 'avogadro', 'avogadro_constant', + 'boltzmann', 'boltzmann_constant', + 'stefan', 'stefan_boltzmann_constant', + 'R', 'molar_gas_constant', + 'faraday_constant', + 'josephson_constant', + 'von_klitzing_constant', + 'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant', + 'me', 'electron_rest_mass', + 'gee', 'gees', 'acceleration_due_to_gravity', + 'u0', 'magnetic_constant', 'vacuum_permeability', + 'e0', 'electric_constant', 'vacuum_permittivity', + 'Z0', 'vacuum_impedance', + 'coulomb_constant', 'coulombs_constant', 'electric_force_constant', + 'atmosphere', 'atmospheres', 'atm', + 'kPa', 'kilopascal', + 'bar', 'bars', + 'pound', 'pounds', + 'psi', + 'dHg0', + 'mmHg', 'torr', + 'mmu', 'mmus', 'milli_mass_unit', + 'quart', 'quarts', + 'angstrom', 'angstroms', + 'ly', 'lightyear', 'lightyears', + 'au', 'astronomical_unit', 'astronomical_units', + 'planck_mass', + 'planck_time', + 'planck_temperature', + 'planck_length', + 'planck_charge', + 'planck_area', + 'planck_volume', + 'planck_momentum', + 'planck_energy', + 'planck_force', + 'planck_power', + 'planck_density', + 'planck_energy_density', + 'planck_intensity', + 'planck_angular_frequency', + 'planck_pressure', + 'planck_current', + 'planck_voltage', + 'planck_impedance', + 'planck_acceleration', + 'bit', 'bits', + 'byte', + 'kibibyte', 'kibibytes', + 'mebibyte', 'mebibytes', + 'gibibyte', 'gibibytes', + 'tebibyte', 'tebibytes', + 'pebibyte', 'pebibytes', + 'exbibyte', 'exbibytes', + 'curie', 'rutherford', +] diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27f2e78733412933bc42c1de7804772992137a1b Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e022011cf68275096e6ce28515fcaec60744c19f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/dimension_definitions.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..989f70baf5fd42369c5fab6dbb972d56e0a082b3 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/__pycache__/unit_definitions.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..c9950d5855eea63f803cf42e68d944f18db90608 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/dimension_definitions.py @@ -0,0 +1,43 @@ +from sympy.physics.units import Dimension + + +angle = Dimension(name="angle") # type: Dimension + +# base dimensions (MKS) +length = Dimension(name="length", symbol="L") +mass = Dimension(name="mass", symbol="M") +time = Dimension(name="time", symbol="T") + +# base dimensions (MKSA not in MKS) +current = Dimension(name='current', symbol='I') # type: Dimension + +# other base dimensions: +temperature = Dimension("temperature", "T") # type: Dimension +amount_of_substance = Dimension("amount_of_substance") # type: Dimension +luminous_intensity = Dimension("luminous_intensity") # type: Dimension + +# derived dimensions (MKS) +velocity = Dimension(name="velocity") +acceleration = Dimension(name="acceleration") +momentum = Dimension(name="momentum") +force = Dimension(name="force", symbol="F") +energy = Dimension(name="energy", symbol="E") +power = Dimension(name="power") +pressure = Dimension(name="pressure") +frequency = Dimension(name="frequency", symbol="f") +action = Dimension(name="action", symbol="A") +area = Dimension("area") +volume = Dimension("volume") + +# derived dimensions (MKSA not in MKS) +voltage = Dimension(name='voltage', symbol='U') # type: Dimension +impedance = Dimension(name='impedance', symbol='Z') # type: Dimension +conductance = Dimension(name='conductance', symbol='G') # type: Dimension +capacitance = Dimension(name='capacitance') # type: Dimension +inductance = Dimension(name='inductance') # type: Dimension +charge = Dimension(name='charge', symbol='Q') # type: Dimension +magnetic_density = Dimension(name='magnetic_density', symbol='B') # type: Dimension +magnetic_flux = Dimension(name='magnetic_flux') # type: Dimension + +# Dimensions in information theory: +information = Dimension(name='information') # type: Dimension diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf443875250917f567d82d5033bd26167ad4905 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/definitions/unit_definitions.py @@ -0,0 +1,400 @@ +from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \ + luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \ + magnetic_flux, information + +from sympy.core.numbers import (Rational, pi) +from sympy.core.singleton import S as S_singleton +from sympy.physics.units.prefixes import kilo, mega, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi +from sympy.physics.units.quantities import PhysicalConstant, Quantity + +One = S_singleton.One + +#### UNITS #### + +# Dimensionless: +percent = percents = Quantity("percent", latex_repr=r"\%") +percent.set_global_relative_scale_factor(Rational(1, 100), One) + +permille = Quantity("permille") +permille.set_global_relative_scale_factor(Rational(1, 1000), One) + + +# Angular units (dimensionless) +rad = radian = radians = Quantity("radian", abbrev="rad") +radian.set_global_dimension(angle) +deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ") +degree.set_global_relative_scale_factor(pi/180, radian) +sr = steradian = steradians = Quantity("steradian", abbrev="sr") +mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil") + +# Base units: +m = meter = meters = Quantity("meter", abbrev="m") + +# gram; used to define its prefixed units +g = gram = grams = Quantity("gram", abbrev="g") + +# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but +# nonetheless we are trying to be compatible with the `kilo` prefix. In a +# similar manner, people using CGS or gaussian units could argue that the +# `centimeter` rather than `meter` is the fundamental unit for length, but the +# scale factor of `centimeter` will be kept as 1/100 to be compatible with the +# `centi` prefix. The current state of the code assumes SI unit dimensions, in +# the future this module will be modified in order to be unit system-neutral +# (that is, support all kinds of unit systems). +kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg") +kg.set_global_relative_scale_factor(kilo, gram) + +s = second = seconds = Quantity("second", abbrev="s") +A = ampere = amperes = Quantity("ampere", abbrev='A') +ampere.set_global_dimension(current) +K = kelvin = kelvins = Quantity("kelvin", abbrev='K') +kelvin.set_global_dimension(temperature) +mol = mole = moles = Quantity("mole", abbrev="mol") +mole.set_global_dimension(amount_of_substance) +cd = candela = candelas = Quantity("candela", abbrev="cd") +candela.set_global_dimension(luminous_intensity) + +# derived units +newton = newtons = N = Quantity("newton", abbrev="N") +joule = joules = J = Quantity("joule", abbrev="J") +watt = watts = W = Quantity("watt", abbrev="W") +pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa") +hertz = hz = Hz = Quantity("hertz", abbrev="Hz") + +# CGS derived units: +dyne = Quantity("dyne") +dyne.set_global_relative_scale_factor(One/10**5, newton) +erg = Quantity("erg") +erg.set_global_relative_scale_factor(One/10**7, joule) + +# MKSA extension to MKS: derived units +coulomb = coulombs = C = Quantity("coulomb", abbrev='C') +coulomb.set_global_dimension(charge) +volt = volts = v = V = Quantity("volt", abbrev='V') +volt.set_global_dimension(voltage) +ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega") +ohm.set_global_dimension(impedance) +siemens = S = mho = mhos = Quantity("siemens", abbrev='S') +siemens.set_global_dimension(conductance) +farad = farads = F = Quantity("farad", abbrev='F') +farad.set_global_dimension(capacitance) +henry = henrys = H = Quantity("henry", abbrev='H') +henry.set_global_dimension(inductance) +tesla = teslas = T = Quantity("tesla", abbrev='T') +tesla.set_global_dimension(magnetic_density) +weber = webers = Wb = wb = Quantity("weber", abbrev='Wb') +weber.set_global_dimension(magnetic_flux) + +# CGS units for electromagnetic quantities: +statampere = Quantity("statampere") +statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC") +statvolt = Quantity("statvolt") +gauss = Quantity("gauss") +maxwell = Quantity("maxwell") +debye = Quantity("debye") +oersted = Quantity("oersted") + +# Other derived units: +optical_power = dioptre = diopter = D = Quantity("dioptre") +lux = lx = Quantity("lux", abbrev="lx") + +# katal is the SI unit of catalytic activity +katal = kat = Quantity("katal", abbrev="kat") + +# gray is the SI unit of absorbed dose +gray = Gy = Quantity("gray") + +# becquerel is the SI unit of radioactivity +becquerel = Bq = Quantity("becquerel", abbrev="Bq") + + +# Common mass units + +mg = milligram = milligrams = Quantity("milligram", abbrev="mg") +mg.set_global_relative_scale_factor(milli, gram) + +ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}") +ug.set_global_relative_scale_factor(micro, gram) + +# Atomic mass constant +Da = dalton = amu = amus = atomic_mass_unit = atomic_mass_constant = PhysicalConstant("atomic_mass_constant") + +t = metric_ton = tonne = Quantity("tonne", abbrev="t") +tonne.set_global_relative_scale_factor(mega, gram) + +# Electron rest mass +me = electron_rest_mass = Quantity("electron_rest_mass", abbrev="me") + + +# Common length units + +km = kilometer = kilometers = Quantity("kilometer", abbrev="km") +km.set_global_relative_scale_factor(kilo, meter) + +dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm") +dm.set_global_relative_scale_factor(deci, meter) + +cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm") +cm.set_global_relative_scale_factor(centi, meter) + +mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm") +mm.set_global_relative_scale_factor(milli, meter) + +um = micrometer = micrometers = micron = microns = \ + Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}') +um.set_global_relative_scale_factor(micro, meter) + +nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm") +nm.set_global_relative_scale_factor(nano, meter) + +pm = picometer = picometers = Quantity("picometer", abbrev="pm") +pm.set_global_relative_scale_factor(pico, meter) + +ft = foot = feet = Quantity("foot", abbrev="ft") +ft.set_global_relative_scale_factor(Rational(3048, 10000), meter) + +inch = inches = Quantity("inch") +inch.set_global_relative_scale_factor(Rational(1, 12), foot) + +yd = yard = yards = Quantity("yard", abbrev="yd") +yd.set_global_relative_scale_factor(3, feet) + +mi = mile = miles = Quantity("mile") +mi.set_global_relative_scale_factor(5280, feet) + +nmi = nautical_mile = nautical_miles = Quantity("nautical_mile") +nmi.set_global_relative_scale_factor(6076, feet) + +angstrom = angstroms = Quantity("angstrom", latex_repr=r'\r{A}') +angstrom.set_global_relative_scale_factor(Rational(1, 10**10), meter) + + +# Common volume and area units + +ha = hectare = Quantity("hectare", abbrev="ha") + +l = L = liter = liters = Quantity("liter") + +dl = dL = deciliter = deciliters = Quantity("deciliter") +dl.set_global_relative_scale_factor(Rational(1, 10), liter) + +cl = cL = centiliter = centiliters = Quantity("centiliter") +cl.set_global_relative_scale_factor(Rational(1, 100), liter) + +ml = mL = milliliter = milliliters = Quantity("milliliter") +ml.set_global_relative_scale_factor(Rational(1, 1000), liter) + + +# Common time units + +ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms") +millisecond.set_global_relative_scale_factor(milli, second) + +us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}') +microsecond.set_global_relative_scale_factor(micro, second) + +ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns") +nanosecond.set_global_relative_scale_factor(nano, second) + +ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps") +picosecond.set_global_relative_scale_factor(pico, second) + +minute = minutes = Quantity("minute") +minute.set_global_relative_scale_factor(60, second) + +h = hour = hours = Quantity("hour") +hour.set_global_relative_scale_factor(60, minute) + +day = days = Quantity("day") +day.set_global_relative_scale_factor(24, hour) + +anomalistic_year = anomalistic_years = Quantity("anomalistic_year") +anomalistic_year.set_global_relative_scale_factor(365.259636, day) + +sidereal_year = sidereal_years = Quantity("sidereal_year") +sidereal_year.set_global_relative_scale_factor(31558149.540, seconds) + +tropical_year = tropical_years = Quantity("tropical_year") +tropical_year.set_global_relative_scale_factor(365.24219, day) + +common_year = common_years = Quantity("common_year") +common_year.set_global_relative_scale_factor(365, day) + +julian_year = julian_years = Quantity("julian_year") +julian_year.set_global_relative_scale_factor((365 + One/4), day) + +draconic_year = draconic_years = Quantity("draconic_year") +draconic_year.set_global_relative_scale_factor(346.62, day) + +gaussian_year = gaussian_years = Quantity("gaussian_year") +gaussian_year.set_global_relative_scale_factor(365.2568983, day) + +full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle") +full_moon_cycle.set_global_relative_scale_factor(411.78443029, day) + +year = years = tropical_year + + +#### CONSTANTS #### + +# Newton constant +G = gravitational_constant = PhysicalConstant("gravitational_constant", abbrev="G") + +# speed of light +c = speed_of_light = PhysicalConstant("speed_of_light", abbrev="c") + +# elementary charge +elementary_charge = PhysicalConstant("elementary_charge", abbrev="e") + +# Planck constant +planck = PhysicalConstant("planck", abbrev="h") + +# Reduced Planck constant +hbar = PhysicalConstant("hbar", abbrev="hbar") + +# Electronvolt +eV = electronvolt = electronvolts = PhysicalConstant("electronvolt", abbrev="eV") + +# Avogadro number +avogadro_number = PhysicalConstant("avogadro_number") + +# Avogadro constant +avogadro = avogadro_constant = PhysicalConstant("avogadro_constant") + +# Boltzmann constant +boltzmann = boltzmann_constant = PhysicalConstant("boltzmann_constant") + +# Stefan-Boltzmann constant +stefan = stefan_boltzmann_constant = PhysicalConstant("stefan_boltzmann_constant") + +# Molar gas constant +R = molar_gas_constant = PhysicalConstant("molar_gas_constant", abbrev="R") + +# Faraday constant +faraday_constant = PhysicalConstant("faraday_constant") + +# Josephson constant +josephson_constant = PhysicalConstant("josephson_constant", abbrev="K_j") + +# Von Klitzing constant +von_klitzing_constant = PhysicalConstant("von_klitzing_constant", abbrev="R_k") + +# Acceleration due to gravity (on the Earth surface) +gee = gees = acceleration_due_to_gravity = PhysicalConstant("acceleration_due_to_gravity", abbrev="g") + +# magnetic constant: +u0 = magnetic_constant = vacuum_permeability = PhysicalConstant("magnetic_constant") + +# electric constat: +e0 = electric_constant = vacuum_permittivity = PhysicalConstant("vacuum_permittivity") + +# vacuum impedance: +Z0 = vacuum_impedance = PhysicalConstant("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}') + +# Coulomb's constant: +coulomb_constant = coulombs_constant = electric_force_constant = \ + PhysicalConstant("coulomb_constant", abbrev="k_e") + + +atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm") + +kPa = kilopascal = Quantity("kilopascal", abbrev="kPa") +kilopascal.set_global_relative_scale_factor(kilo, Pa) + +bar = bars = Quantity("bar", abbrev="bar") + +pound = pounds = Quantity("pound") # exact + +psi = Quantity("psi") + +dHg0 = 13.5951 # approx value at 0 C +mmHg = torr = Quantity("mmHg") + +atmosphere.set_global_relative_scale_factor(101325, pascal) +bar.set_global_relative_scale_factor(100, kPa) +pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg) + +mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit") + +quart = quarts = Quantity("quart") + + +# Other convenient units and magnitudes + +ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly") + +au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU") + + +# Fundamental Planck units: +planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}') + +planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}') + +planck_temperature = Quantity("planck_temperature", abbrev="T_P", + latex_repr=r'T_\text{P}') + +planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}') + +planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}') + + +# Derived Planck units: +planck_area = Quantity("planck_area") + +planck_volume = Quantity("planck_volume") + +planck_momentum = Quantity("planck_momentum") + +planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}') + +planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}') + +planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}') + +planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}') + +planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P") + +planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}') + +planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P", + latex_repr=r'\omega_\text{P}') + +planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}') + +planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}') + +planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}') + +planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}') + +planck_acceleration = Quantity("planck_acceleration", abbrev="a_P", + latex_repr=r'a_\text{P}') + + +# Information theory units: +bit = bits = Quantity("bit") +bit.set_global_dimension(information) + +byte = bytes = Quantity("byte") + +kibibyte = kibibytes = Quantity("kibibyte") +mebibyte = mebibytes = Quantity("mebibyte") +gibibyte = gibibytes = Quantity("gibibyte") +tebibyte = tebibytes = Quantity("tebibyte") +pebibyte = pebibytes = Quantity("pebibyte") +exbibyte = exbibytes = Quantity("exbibyte") + +byte.set_global_relative_scale_factor(8, bit) +kibibyte.set_global_relative_scale_factor(kibi, byte) +mebibyte.set_global_relative_scale_factor(mebi, byte) +gibibyte.set_global_relative_scale_factor(gibi, byte) +tebibyte.set_global_relative_scale_factor(tebi, byte) +pebibyte.set_global_relative_scale_factor(pebi, byte) +exbibyte.set_global_relative_scale_factor(exbi, byte) + +# Older units for radioactivity +curie = Ci = Quantity("curie", abbrev="Ci") + +rutherford = Rd = Quantity("rutherford", abbrev="Rd") diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__init__.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32ac3f63d84187e07d107d794605dc0a95ea8e5d Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..659ba766574de14f7b6dea781f4af2c295c84219 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensions.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5c3f68c88e4c64eba54e2addc047631cc3519bc Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_dimensionsystem.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_prefixes.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_prefixes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1c5ffb91fb5f09c7e674371316e66e402ba976f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_prefixes.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_quantities.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_quantities.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24936b84f88d62dbb383034c8f7b8c2a22128b6a Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_quantities.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unit_system_cgs_gauss.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unit_system_cgs_gauss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1be844e7c3bbb8bacb2a2d662b7baf499f5314 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unit_system_cgs_gauss.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unitsystem.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unitsystem.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8e428f1ceb23b56be9bbe24a37f14486969baf8 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_unitsystem.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_util.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83fdd1ac66bcc95b6766624103ee1f2495de29a1 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/__pycache__/test_util.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensions.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensions.py new file mode 100644 index 0000000000000000000000000000000000000000..6455df41068a07c966c5f3e782e561fec4d16a97 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensions.py @@ -0,0 +1,150 @@ +from sympy.physics.units.systems.si import dimsys_SI + +from sympy.core.numbers import pi +from sympy.core.singleton import S +from sympy.core.symbol import Symbol +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import log +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import (acos, atan2, cos) +from sympy.physics.units.dimensions import Dimension +from sympy.physics.units.definitions.dimension_definitions import ( + length, time, mass, force, pressure, angle +) +from sympy.physics.units import foot +from sympy.testing.pytest import raises + + +def test_Dimension_definition(): + assert dimsys_SI.get_dimensional_dependencies(length) == {length: 1} + assert length.name == Symbol("length") + assert length.symbol == Symbol("L") + + halflength = sqrt(length) + assert dimsys_SI.get_dimensional_dependencies(halflength) == {length: S.Half} + + +def test_Dimension_error_definition(): + # tuple with more or less than two entries + raises(TypeError, lambda: Dimension(("length", 1, 2))) + raises(TypeError, lambda: Dimension(["length"])) + + # non-number power + raises(TypeError, lambda: Dimension({"length": "a"})) + + # non-number with named argument + raises(TypeError, lambda: Dimension({"length": (1, 2)})) + + # symbol should by Symbol or str + raises(AssertionError, lambda: Dimension("length", symbol=1)) + + +def test_str(): + assert str(Dimension("length")) == "Dimension(length)" + assert str(Dimension("length", "L")) == "Dimension(length, L)" + + +def test_Dimension_properties(): + assert dimsys_SI.is_dimensionless(length) is False + assert dimsys_SI.is_dimensionless(length/length) is True + assert dimsys_SI.is_dimensionless(Dimension("undefined")) is False + + assert length.has_integer_powers(dimsys_SI) is True + assert (length**(-1)).has_integer_powers(dimsys_SI) is True + assert (length**1.5).has_integer_powers(dimsys_SI) is False + + +def test_Dimension_add_sub(): + assert length + length == length + assert length - length == length + assert -length == length + + raises(TypeError, lambda: length + foot) + raises(TypeError, lambda: foot + length) + raises(TypeError, lambda: length - foot) + raises(TypeError, lambda: foot - length) + + # issue 14547 - only raise error for dimensional args; allow + # others to pass + x = Symbol('x') + e = length + x + assert e == x + length and e.is_Add and set(e.args) == {length, x} + e = length + 1 + assert e == 1 + length == 1 - length and e.is_Add and set(e.args) == {length, 1} + + assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force) == \ + {length: 1, mass: 1, time: -2} + assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force - + pressure * length**2) == \ + {length: 1, mass: 1, time: -2} + + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + pressure)) + +def test_Dimension_mul_div_exp(): + assert 2*length == length*2 == length/2 == length + assert 2/length == 1/length + x = Symbol('x') + m = x*length + assert m == length*x and m.is_Mul and set(m.args) == {x, length} + d = x/length + assert d == x*length**-1 and d.is_Mul and set(d.args) == {x, 1/length} + d = length/x + assert d == length*x**-1 and d.is_Mul and set(d.args) == {1/x, length} + + velo = length / time + + assert (length * length) == length ** 2 + + assert dimsys_SI.get_dimensional_dependencies(length * length) == {length: 2} + assert dimsys_SI.get_dimensional_dependencies(length ** 2) == {length: 2} + assert dimsys_SI.get_dimensional_dependencies(length * time) == {length: 1, time: 1} + assert dimsys_SI.get_dimensional_dependencies(velo) == {length: 1, time: -1} + assert dimsys_SI.get_dimensional_dependencies(velo ** 2) == {length: 2, time: -2} + + assert dimsys_SI.get_dimensional_dependencies(length / length) == {} + assert dimsys_SI.get_dimensional_dependencies(velo / length * time) == {} + assert dimsys_SI.get_dimensional_dependencies(length ** -1) == {length: -1} + assert dimsys_SI.get_dimensional_dependencies(velo ** -1.5) == {length: -1.5, time: 1.5} + + length_a = length**"a" + assert dimsys_SI.get_dimensional_dependencies(length_a) == {length: Symbol("a")} + + assert dimsys_SI.get_dimensional_dependencies(length**pi) == {length: pi} + assert dimsys_SI.get_dimensional_dependencies(length**(length/length)) == {length: Dimension(1)} + + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(length**length)) + + assert length != 1 + assert length / length != 1 + + length_0 = length ** 0 + assert dimsys_SI.get_dimensional_dependencies(length_0) == {} + + # issue 18738 + a = Symbol('a') + b = Symbol('b') + c = sqrt(a**2 + b**2) + c_dim = c.subs({a: length, b: length}) + assert dimsys_SI.equivalent_dims(c_dim, length) + +def test_Dimension_functions(): + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(cos(length))) + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(acos(angle))) + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(atan2(length, time))) + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length))) + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(100, length))) + raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length, 10))) + + assert dimsys_SI.get_dimensional_dependencies(pi) == {} + + assert dimsys_SI.get_dimensional_dependencies(cos(1)) == {} + assert dimsys_SI.get_dimensional_dependencies(cos(angle)) == {} + + assert dimsys_SI.get_dimensional_dependencies(atan2(length, length)) == {} + + assert dimsys_SI.get_dimensional_dependencies(log(length / length, length / length)) == {} + + assert dimsys_SI.get_dimensional_dependencies(Abs(length)) == {length: 1} + assert dimsys_SI.get_dimensional_dependencies(Abs(length / length)) == {} + + assert dimsys_SI.get_dimensional_dependencies(sqrt(-1)) == {} diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensionsystem.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensionsystem.py new file mode 100644 index 0000000000000000000000000000000000000000..8a55ac398c38adf24d93bfa376c9cc51c1ec40fe --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_dimensionsystem.py @@ -0,0 +1,95 @@ +from sympy.core.symbol import symbols +from sympy.matrices.dense import (Matrix, eye) +from sympy.physics.units.definitions.dimension_definitions import ( + action, current, length, mass, time, + velocity) +from sympy.physics.units.dimensions import DimensionSystem + + +def test_extend(): + ms = DimensionSystem((length, time), (velocity,)) + + mks = ms.extend((mass,), (action,)) + + res = DimensionSystem((length, time, mass), (velocity, action)) + assert mks.base_dims == res.base_dims + assert mks.derived_dims == res.derived_dims + + +def test_list_dims(): + dimsys = DimensionSystem((length, time, mass)) + + assert dimsys.list_can_dims == (length, mass, time) + + +def test_dim_can_vector(): + dimsys = DimensionSystem( + [length, mass, time], + [velocity, action], + { + velocity: {length: 1, time: -1} + } + ) + + assert dimsys.dim_can_vector(length) == Matrix([1, 0, 0]) + assert dimsys.dim_can_vector(velocity) == Matrix([1, 0, -1]) + + dimsys = DimensionSystem( + (length, velocity, action), + (mass, time), + { + time: {length: 1, velocity: -1} + } + ) + + assert dimsys.dim_can_vector(length) == Matrix([0, 1, 0]) + assert dimsys.dim_can_vector(velocity) == Matrix([0, 0, 1]) + assert dimsys.dim_can_vector(time) == Matrix([0, 1, -1]) + + dimsys = DimensionSystem( + (length, mass, time), + (velocity, action), + {velocity: {length: 1, time: -1}, + action: {mass: 1, length: 2, time: -1}}) + + assert dimsys.dim_vector(length) == Matrix([1, 0, 0]) + assert dimsys.dim_vector(velocity) == Matrix([1, 0, -1]) + + +def test_inv_can_transf_matrix(): + dimsys = DimensionSystem((length, mass, time)) + assert dimsys.inv_can_transf_matrix == eye(3) + + +def test_can_transf_matrix(): + dimsys = DimensionSystem((length, mass, time)) + assert dimsys.can_transf_matrix == eye(3) + + dimsys = DimensionSystem((length, velocity, action)) + assert dimsys.can_transf_matrix == eye(3) + + dimsys = DimensionSystem((length, time), (velocity,), {velocity: {length: 1, time: -1}}) + assert dimsys.can_transf_matrix == eye(2) + + +def test_is_consistent(): + assert DimensionSystem((length, time)).is_consistent is True + + +def test_print_dim_base(): + mksa = DimensionSystem( + (length, time, mass, current), + (action,), + {action: {mass: 1, length: 2, time: -1}}) + L, M, T = symbols("L M T") + assert mksa.print_dim_base(action) == L**2*M/T + + +def test_dim(): + dimsys = DimensionSystem( + (length, mass, time), + (velocity, action), + {velocity: {length: 1, time: -1}, + action: {mass: 1, length: 2, time: -1}} + ) + assert dimsys.dim == 3 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_prefixes.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_prefixes.py new file mode 100644 index 0000000000000000000000000000000000000000..8a7ae3a2c4974819bee447f8d42e83ea3d8434b6 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_prefixes.py @@ -0,0 +1,85 @@ +from sympy.core.mul import Mul +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.physics.units import Quantity, length, meter +from sympy.physics.units.prefixes import PREFIXES, Prefix, prefix_unit, kilo, \ + kibi +from sympy.physics.units.systems import SI + +x = Symbol('x') + + +def test_prefix_operations(): + m = PREFIXES['m'] + k = PREFIXES['k'] + M = PREFIXES['M'] + + dodeca = Prefix('dodeca', 'dd', 1, base=12) + + assert m * k == 1 + assert k * k == M + assert 1 / m == k + assert k / m == M + + assert dodeca * dodeca == 144 + assert 1 / dodeca == S.One / 12 + assert k / dodeca == S(1000) / 12 + assert dodeca / dodeca == 1 + + m = Quantity("fake_meter") + SI.set_quantity_dimension(m, S.One) + SI.set_quantity_scale_factor(m, S.One) + + assert dodeca * m == 12 * m + assert dodeca / m == 12 / m + + expr1 = kilo * 3 + assert isinstance(expr1, Mul) + assert expr1.args == (3, kilo) + + expr2 = kilo * x + assert isinstance(expr2, Mul) + assert expr2.args == (x, kilo) + + expr3 = kilo / 3 + assert isinstance(expr3, Mul) + assert expr3.args == (Rational(1, 3), kilo) + assert expr3.args == (S.One/3, kilo) + + expr4 = kilo / x + assert isinstance(expr4, Mul) + assert expr4.args == (1/x, kilo) + + +def test_prefix_unit(): + m = Quantity("fake_meter", abbrev="m") + m.set_global_relative_scale_factor(1, meter) + + pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]} + + q1 = Quantity("millifake_meter", abbrev="mm") + q2 = Quantity("centifake_meter", abbrev="cm") + q3 = Quantity("decifake_meter", abbrev="dm") + + SI.set_quantity_dimension(q1, length) + + SI.set_quantity_scale_factor(q1, PREFIXES["m"]) + SI.set_quantity_scale_factor(q1, PREFIXES["c"]) + SI.set_quantity_scale_factor(q1, PREFIXES["d"]) + + res = [q1, q2, q3] + + prefs = prefix_unit(m, pref) + assert set(prefs) == set(res) + assert {v.abbrev for v in prefs} == set(symbols("mm,cm,dm")) + + +def test_bases(): + assert kilo.base == 10 + assert kibi.base == 2 + + +def test_repr(): + assert eval(repr(kilo)) == kilo + assert eval(repr(kibi)) == kibi diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_quantities.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_quantities.py new file mode 100644 index 0000000000000000000000000000000000000000..20c4d217d2c3e3fdaadeb21502c7b4e47a4b994e --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_quantities.py @@ -0,0 +1,581 @@ +import warnings + +from sympy.core.add import Add +from sympy.core.function import (Function, diff) +from sympy.core.numbers import (Number, Rational) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.exponential import (exp, log) +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.functions.elementary.trigonometric import sin +from sympy.integrals.integrals import integrate +from sympy.physics.units import (amount_of_substance, area, convert_to, find_unit, + volume, kilometer, joule, molar_gas_constant, + vacuum_permittivity, elementary_charge, volt, + ohm) +from sympy.physics.units.definitions import (amu, au, centimeter, coulomb, + day, foot, grams, hour, inch, kg, km, m, meter, millimeter, + minute, quart, s, second, speed_of_light, bit, + byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte, + kilogram, gravitational_constant, electron_rest_mass) + +from sympy.physics.units.definitions.dimension_definitions import ( + Dimension, charge, length, time, temperature, pressure, + energy, mass +) +from sympy.physics.units.prefixes import PREFIXES, kilo +from sympy.physics.units.quantities import PhysicalConstant, Quantity +from sympy.physics.units.systems import SI +from sympy.testing.pytest import raises + +k = PREFIXES["k"] + + +def test_str_repr(): + assert str(kg) == "kilogram" + + +def test_eq(): + # simple test + assert 10*m == 10*m + assert 10*m != 10*s + + +def test_convert_to(): + q = Quantity("q1") + q.set_global_relative_scale_factor(S(5000), meter) + + assert q.convert_to(m) == 5000*m + + assert speed_of_light.convert_to(m / s) == 299792458 * m / s + # TODO: eventually support this kind of conversion: + # assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s + assert day.convert_to(s) == 86400*s + + # Wrong dimension to convert: + assert q.convert_to(s) == q + assert speed_of_light.convert_to(m) == speed_of_light + + expr = joule*second + conv = convert_to(expr, joule) + assert conv == joule*second + + +def test_Quantity_definition(): + q = Quantity("s10", abbrev="sabbr") + q.set_global_relative_scale_factor(10, second) + u = Quantity("u", abbrev="dam") + u.set_global_relative_scale_factor(10, meter) + km = Quantity("km") + km.set_global_relative_scale_factor(kilo, meter) + v = Quantity("u") + v.set_global_relative_scale_factor(5*kilo, meter) + + assert q.scale_factor == 10 + assert q.dimension == time + assert q.abbrev == Symbol("sabbr") + + assert u.dimension == length + assert u.scale_factor == 10 + assert u.abbrev == Symbol("dam") + + assert km.scale_factor == 1000 + assert km.func(*km.args) == km + assert km.func(*km.args).args == km.args + + assert v.dimension == length + assert v.scale_factor == 5000 + + +def test_abbrev(): + u = Quantity("u") + u.set_global_relative_scale_factor(S.One, meter) + + assert u.name == Symbol("u") + assert u.abbrev == Symbol("u") + + u = Quantity("u", abbrev="om") + u.set_global_relative_scale_factor(S(2), meter) + + assert u.name == Symbol("u") + assert u.abbrev == Symbol("om") + assert u.scale_factor == 2 + assert isinstance(u.scale_factor, Number) + + u = Quantity("u", abbrev="ikm") + u.set_global_relative_scale_factor(3*kilo, meter) + + assert u.abbrev == Symbol("ikm") + assert u.scale_factor == 3000 + + +def test_print(): + u = Quantity("unitname", abbrev="dam") + assert repr(u) == "unitname" + assert str(u) == "unitname" + + +def test_Quantity_eq(): + u = Quantity("u", abbrev="dam") + v = Quantity("v1") + assert u != v + v = Quantity("v2", abbrev="ds") + assert u != v + v = Quantity("v3", abbrev="dm") + assert u != v + + +def test_add_sub(): + u = Quantity("u") + v = Quantity("v") + w = Quantity("w") + + u.set_global_relative_scale_factor(S(10), meter) + v.set_global_relative_scale_factor(S(5), meter) + w.set_global_relative_scale_factor(S(2), second) + + assert isinstance(u + v, Add) + assert (u + v.convert_to(u)) == (1 + S.Half)*u + # TODO: eventually add this: + # assert (u + v).convert_to(u) == (1 + S.Half)*u + assert isinstance(u - v, Add) + assert (u - v.convert_to(u)) == S.Half*u + # TODO: eventually add this: + # assert (u - v).convert_to(u) == S.Half*u + + +def test_quantity_abs(): + v_w1 = Quantity('v_w1') + v_w2 = Quantity('v_w2') + v_w3 = Quantity('v_w3') + + v_w1.set_global_relative_scale_factor(1, meter/second) + v_w2.set_global_relative_scale_factor(1, meter/second) + v_w3.set_global_relative_scale_factor(1, meter/second) + + expr = v_w3 - Abs(v_w1 - v_w2) + + assert SI.get_dimensional_expr(v_w1) == (length/time).name + + Dq = Dimension(SI.get_dimensional_expr(expr)) + + assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { + length: 1, + time: -1, + } + assert meter == sqrt(meter**2) + + +def test_check_unit_consistency(): + u = Quantity("u") + v = Quantity("v") + w = Quantity("w") + + u.set_global_relative_scale_factor(S(10), meter) + v.set_global_relative_scale_factor(S(5), meter) + w.set_global_relative_scale_factor(S(2), second) + + def check_unit_consistency(expr): + SI._collect_factor_and_dimension(expr) + + raises(ValueError, lambda: check_unit_consistency(u + w)) + raises(ValueError, lambda: check_unit_consistency(u - w)) + raises(ValueError, lambda: check_unit_consistency(u + 1)) + raises(ValueError, lambda: check_unit_consistency(u - 1)) + raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w))) + + +def test_mul_div(): + u = Quantity("u") + v = Quantity("v") + t = Quantity("t") + ut = Quantity("ut") + v2 = Quantity("v") + + u.set_global_relative_scale_factor(S(10), meter) + v.set_global_relative_scale_factor(S(5), meter) + t.set_global_relative_scale_factor(S(2), second) + ut.set_global_relative_scale_factor(S(20), meter*second) + v2.set_global_relative_scale_factor(S(5), meter/second) + + assert 1 / u == u**(-1) + assert u / 1 == u + + v1 = u / t + v2 = v + + # Pow only supports structural equality: + assert v1 != v2 + assert v1 == v2.convert_to(v1) + + # TODO: decide whether to allow such expression in the future + # (requires somehow manipulating the core). + # assert u / Quantity('l2', dimension=length, scale_factor=2) == 5 + + assert u * 1 == u + + ut1 = u * t + ut2 = ut + + # Mul only supports structural equality: + assert ut1 != ut2 + assert ut1 == ut2.convert_to(ut1) + + # Mul only supports structural equality: + lp1 = Quantity("lp1") + lp1.set_global_relative_scale_factor(S(2), 1/meter) + assert u * lp1 != 20 + + assert u**0 == 1 + assert u**1 == u + + # TODO: Pow only support structural equality: + u2 = Quantity("u2") + u3 = Quantity("u3") + u2.set_global_relative_scale_factor(S(100), meter**2) + u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter) + + assert u ** 2 != u2 + assert u ** -1 != u3 + + assert u ** 2 == u2.convert_to(u) + assert u ** -1 == u3.convert_to(u) + + +def test_units(): + assert convert_to((5*m/s * day) / km, 1) == 432 + assert convert_to(foot / meter, meter) == Rational(3048, 10000) + # amu is a pure mass so mass/mass gives a number, not an amount (mol) + # TODO: need better simplification routine: + assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23' + + # Light from the sun needs about 8.3 minutes to reach earth + t = (1*au / speed_of_light) / minute + # TODO: need a better way to simplify expressions containing units: + t = convert_to(convert_to(t, meter / minute), meter) + assert t.simplify() == Rational(49865956897, 5995849160) + + # TODO: fix this, it should give `m` without `Abs` + assert sqrt(m**2) == m + assert (sqrt(m))**2 == m + + t = Symbol('t') + assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s + assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s + + +def test_issue_quart(): + assert convert_to(4 * quart / inch ** 3, meter) == 231 + assert convert_to(4 * quart / inch ** 3, millimeter) == 231 + +def test_electron_rest_mass(): + assert convert_to(electron_rest_mass, kilogram) == 9.1093837015e-31*kilogram + assert convert_to(electron_rest_mass, grams) == 9.1093837015e-28*grams + +def test_issue_5565(): + assert (m < s).is_Relational + + +def test_find_unit(): + assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant'] + assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] + assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] + assert find_unit(inch) == [ + 'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um', 'yd', + 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles', 'yards', + 'inches', 'meters', 'micron', 'microns', 'angstrom', 'angstroms', 'decimeter', + 'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter', 'decimeters', + 'kilometers', 'lightyears', 'micrometer', 'millimeter', 'nanometers', 'picometers', + 'centimeters', 'micrometers', 'millimeters', 'nautical_mile', 'planck_length', + 'nautical_miles', 'astronomical_unit', 'astronomical_units'] + assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power'] + assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power'] + assert find_unit(inch ** 2) == ['ha', 'hectare', 'planck_area'] + assert find_unit(inch ** 3) == [ + 'L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter', 'quart', 'liters', 'quarts', + 'deciliter', 'centiliter', 'deciliters', 'milliliter', + 'centiliters', 'milliliters', 'planck_volume'] + assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage'] + assert find_unit(grams) == ['g', 't', 'Da', 'kg', 'me', 'mg', 'ug', 'amu', 'mmu', 'amus', + 'gram', 'mmus', 'grams', 'pound', 'tonne', 'dalton', 'pounds', + 'kilogram', 'kilograms', 'microgram', 'milligram', 'metric_ton', + 'micrograms', 'milligrams', 'planck_mass', 'milli_mass_unit', 'atomic_mass_unit', + 'electron_rest_mass', 'atomic_mass_constant'] + + +def test_Quantity_derivative(): + x = symbols("x") + assert diff(x*meter, x) == meter + assert diff(x**3*meter**2, x) == 3*x**2*meter**2 + assert diff(meter, meter) == 1 + assert diff(meter**2, meter) == 2*meter + + +def test_quantity_postprocessing(): + q1 = Quantity('q1') + q2 = Quantity('q2') + + SI.set_quantity_dimension(q1, length*pressure**2*temperature/time) + SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time)) + + assert q1 + q2 + q = q1 + q2 + Dq = Dimension(SI.get_dimensional_expr(q)) + assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == { + length: -1, + mass: 2, + temperature: 1, + time: -5, + } + + +def test_factor_and_dimension(): + assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000) + assert (1001, length) == SI._collect_factor_and_dimension(meter + km) + assert (2, length/time) == SI._collect_factor_and_dimension( + meter/second + 36*km/(10*hour)) + + x, y = symbols('x y') + assert (x + y/100, length) == SI._collect_factor_and_dimension( + x*m + y*centimeter) + + cH = Quantity('cH') + SI.set_quantity_dimension(cH, amount_of_substance/volume) + + pH = -log(cH) + + assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension( + exp(pH)) + + v_w1 = Quantity('v_w1') + v_w2 = Quantity('v_w2') + + v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second) + v_w2.set_global_relative_scale_factor(2, meter/second) + + expr = Abs(v_w1/2 - v_w2) + assert (Rational(5, 4), length/time) == \ + SI._collect_factor_and_dimension(expr) + + expr = Rational(5, 2)*second/meter*v_w1 - 3000 + assert (-(2996 + Rational(1, 4)), Dimension(1)) == \ + SI._collect_factor_and_dimension(expr) + + expr = v_w1**(v_w2/v_w1) + assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \ + SI._collect_factor_and_dimension(expr) + + +def test_dimensional_expr_of_derivative(): + l = Quantity('l') + t = Quantity('t') + t1 = Quantity('t1') + l.set_global_relative_scale_factor(36, km) + t.set_global_relative_scale_factor(1, hour) + t1.set_global_relative_scale_factor(1, second) + x = Symbol('x') + y = Symbol('y') + f = Function('f') + dfdx = f(x, y).diff(x, y) + dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1}) + assert SI.get_dimensional_expr(dl_dt) ==\ + SI.get_dimensional_expr(l / t / t1) ==\ + Symbol("length")/Symbol("time")**2 + assert SI._collect_factor_and_dimension(dl_dt) ==\ + SI._collect_factor_and_dimension(l / t / t1) ==\ + (10, length/time**2) + + +def test_get_dimensional_expr_with_function(): + v_w1 = Quantity('v_w1') + v_w2 = Quantity('v_w2') + v_w1.set_global_relative_scale_factor(1, meter/second) + v_w2.set_global_relative_scale_factor(1, meter/second) + + assert SI.get_dimensional_expr(sin(v_w1)) == \ + sin(SI.get_dimensional_expr(v_w1)) + assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1 + + +def test_binary_information(): + assert convert_to(kibibyte, byte) == 1024*byte + assert convert_to(mebibyte, byte) == 1024**2*byte + assert convert_to(gibibyte, byte) == 1024**3*byte + assert convert_to(tebibyte, byte) == 1024**4*byte + assert convert_to(pebibyte, byte) == 1024**5*byte + assert convert_to(exbibyte, byte) == 1024**6*byte + + assert kibibyte.convert_to(bit) == 8*1024*bit + assert byte.convert_to(bit) == 8*bit + + a = 10*kibibyte*hour + + assert convert_to(a, byte) == 10240*byte*hour + assert convert_to(a, minute) == 600*kibibyte*minute + assert convert_to(a, [byte, minute]) == 614400*byte*minute + + +def test_conversion_with_2_nonstandard_dimensions(): + good_grade = Quantity("good_grade") + kilo_good_grade = Quantity("kilo_good_grade") + centi_good_grade = Quantity("centi_good_grade") + + kilo_good_grade.set_global_relative_scale_factor(1000, good_grade) + centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade) + + charity_points = Quantity("charity_points") + milli_charity_points = Quantity("milli_charity_points") + missions = Quantity("missions") + + milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points) + missions.set_global_relative_scale_factor(251, charity_points) + + assert convert_to( + kilo_good_grade*milli_charity_points*millimeter, + [centi_good_grade, missions, centimeter] + ) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter + + +def test_eval_subs(): + energy, mass, force = symbols('energy mass force') + expr1 = energy/mass + units = {energy: kilogram*meter**2/second**2, mass: kilogram} + assert expr1.subs(units) == meter**2/second**2 + expr2 = force/mass + units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram} + assert expr2.subs(units) == gravitational_constant*kilogram/meter**2 + + +def test_issue_14932(): + assert (log(inch) - log(2)).simplify() == log(inch/2) + assert (log(inch) - log(foot)).simplify() == -log(12) + p = symbols('p', positive=True) + assert (log(inch) - log(p)).simplify() == log(inch/p) + + +def test_issue_14547(): + # the root issue is that an argument with dimensions should + # not raise an error when the `arg - 1` calculation is + # performed in the assumptions system + from sympy.physics.units import foot, inch + from sympy.core.relational import Eq + assert log(foot).is_zero is None + assert log(foot).is_positive is None + assert log(foot).is_nonnegative is None + assert log(foot).is_negative is None + assert log(foot).is_algebraic is None + assert log(foot).is_rational is None + # doesn't raise error + assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated + + x = Symbol('x') + e = foot + x + assert e.is_Add and set(e.args) == {foot, x} + e = foot + 1 + assert e.is_Add and set(e.args) == {foot, 1} + + +def test_issue_22164(): + warnings.simplefilter("error") + dm = Quantity("dm") + SI.set_quantity_dimension(dm, length) + SI.set_quantity_scale_factor(dm, 1) + + bad_exp = Quantity("bad_exp") + SI.set_quantity_dimension(bad_exp, length) + SI.set_quantity_scale_factor(bad_exp, 1) + + expr = dm ** bad_exp + + # deprecation warning is not expected here + SI._collect_factor_and_dimension(expr) + + +def test_issue_22819(): + from sympy.physics.units import tonne, gram, Da + from sympy.physics.units.systems.si import dimsys_SI + assert tonne.convert_to(gram) == 1000000*gram + assert dimsys_SI.get_dimensional_dependencies(area) == {length: 2} + assert Da.scale_factor == 1.66053906660000e-24 + + +def test_issue_20288(): + from sympy.core.numbers import E + from sympy.physics.units import energy + u = Quantity('u') + v = Quantity('v') + SI.set_quantity_dimension(u, energy) + SI.set_quantity_dimension(v, energy) + u.set_global_relative_scale_factor(1, joule) + v.set_global_relative_scale_factor(1, joule) + expr = 1 + exp(u**2/v**2) + assert SI._collect_factor_and_dimension(expr) == (1 + E, Dimension(1)) + + +def test_issue_24062(): + from sympy.core.numbers import E + from sympy.physics.units import impedance, capacitance, time, ohm, farad, second + + R = Quantity('R') + C = Quantity('C') + T = Quantity('T') + SI.set_quantity_dimension(R, impedance) + SI.set_quantity_dimension(C, capacitance) + SI.set_quantity_dimension(T, time) + R.set_global_relative_scale_factor(1, ohm) + C.set_global_relative_scale_factor(1, farad) + T.set_global_relative_scale_factor(1, second) + expr = T / (R * C) + dim = SI._collect_factor_and_dimension(expr)[1] + assert SI.get_dimension_system().is_dimensionless(dim) + + exp_expr = 1 + exp(expr) + assert SI._collect_factor_and_dimension(exp_expr) == (1 + E, Dimension(1)) + +def test_issue_24211(): + from sympy.physics.units import time, velocity, acceleration, second, meter + V1 = Quantity('V1') + SI.set_quantity_dimension(V1, velocity) + SI.set_quantity_scale_factor(V1, 1 * meter / second) + A1 = Quantity('A1') + SI.set_quantity_dimension(A1, acceleration) + SI.set_quantity_scale_factor(A1, 1 * meter / second**2) + T1 = Quantity('T1') + SI.set_quantity_dimension(T1, time) + SI.set_quantity_scale_factor(T1, 1 * second) + + expr = A1*T1 + V1 + # should not throw ValueError here + SI._collect_factor_and_dimension(expr) + + +def test_prefixed_property(): + assert not meter.is_prefixed + assert not joule.is_prefixed + assert not day.is_prefixed + assert not second.is_prefixed + assert not volt.is_prefixed + assert not ohm.is_prefixed + assert centimeter.is_prefixed + assert kilometer.is_prefixed + assert kilogram.is_prefixed + assert pebibyte.is_prefixed + +def test_physics_constant(): + from sympy.physics.units import definitions + + for name in dir(definitions): + quantity = getattr(definitions, name) + if not isinstance(quantity, Quantity): + continue + if name.endswith('_constant'): + assert isinstance(quantity, PhysicalConstant), f"{quantity} must be PhysicalConstant, but is {type(quantity)}" + assert quantity.is_physical_constant, f"{name} is not marked as physics constant when it should be" + + for const in [gravitational_constant, molar_gas_constant, vacuum_permittivity, speed_of_light, elementary_charge]: + assert isinstance(const, PhysicalConstant), f"{const} must be PhysicalConstant, but is {type(const)}" + assert const.is_physical_constant, f"{const} is not marked as physics constant when it should be" + + assert not meter.is_physical_constant + assert not joule.is_physical_constant diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unit_system_cgs_gauss.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unit_system_cgs_gauss.py new file mode 100644 index 0000000000000000000000000000000000000000..12629280785c94fa8be33bc97bdd714140a3e346 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unit_system_cgs_gauss.py @@ -0,0 +1,55 @@ +from sympy.concrete.tests.test_sums_products import NS + +from sympy.core.singleton import S +from sympy.functions.elementary.miscellaneous import sqrt +from sympy.physics.units import convert_to, coulomb_constant, elementary_charge, gravitational_constant, planck +from sympy.physics.units.definitions.unit_definitions import angstrom, statcoulomb, coulomb, second, gram, centimeter, erg, \ + newton, joule, dyne, speed_of_light, meter, farad, henry, statvolt, volt, ohm +from sympy.physics.units.systems import SI +from sympy.physics.units.systems.cgs import cgs_gauss + + +def test_conversion_to_from_si(): + assert convert_to(statcoulomb, coulomb, cgs_gauss) == coulomb/2997924580 + assert convert_to(coulomb, statcoulomb, cgs_gauss) == 2997924580*statcoulomb + assert convert_to(statcoulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == centimeter**(S(3)/2)*sqrt(gram)/second + assert convert_to(coulomb, sqrt(gram*centimeter**3)/second, cgs_gauss) == 2997924580*centimeter**(S(3)/2)*sqrt(gram)/second + + # SI units have an additional base unit, no conversion in case of electromagnetism: + assert convert_to(coulomb, statcoulomb, SI) == coulomb + assert convert_to(statcoulomb, coulomb, SI) == statcoulomb + + # SI without electromagnetism: + assert convert_to(erg, joule, SI) == joule/10**7 + assert convert_to(erg, joule, cgs_gauss) == joule/10**7 + assert convert_to(joule, erg, SI) == 10**7*erg + assert convert_to(joule, erg, cgs_gauss) == 10**7*erg + + + assert convert_to(dyne, newton, SI) == newton/10**5 + assert convert_to(dyne, newton, cgs_gauss) == newton/10**5 + assert convert_to(newton, dyne, SI) == 10**5*dyne + assert convert_to(newton, dyne, cgs_gauss) == 10**5*dyne + + +def test_cgs_gauss_convert_constants(): + + assert convert_to(speed_of_light, centimeter/second, cgs_gauss) == 29979245800*centimeter/second + + assert convert_to(coulomb_constant, 1, cgs_gauss) == 1 + assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, cgs_gauss) == 22468879468420441*meter**2*newton/(2500000*coulomb**2) + assert convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI) == 22468879468420441*meter**2*newton/(2500000*coulomb**2) + assert convert_to(coulomb_constant, dyne*centimeter**2/statcoulomb**2, cgs_gauss) == centimeter**2*dyne/statcoulomb**2 + assert convert_to(coulomb_constant, 1, SI) == coulomb_constant + assert NS(convert_to(coulomb_constant, newton*meter**2/coulomb**2, SI)) == '8987551787.36818*meter**2*newton/coulomb**2' + + assert convert_to(elementary_charge, statcoulomb, cgs_gauss) + assert convert_to(angstrom, centimeter, cgs_gauss) == 1*centimeter/10**8 + assert convert_to(gravitational_constant, dyne*centimeter**2/gram**2, cgs_gauss) + assert NS(convert_to(planck, erg*second, cgs_gauss)) == '6.62607015e-27*erg*second' + + spc = 25000*second/(22468879468420441*centimeter) + assert convert_to(ohm, second/centimeter, cgs_gauss) == spc + assert convert_to(henry, second**2/centimeter, cgs_gauss) == spc*second + assert convert_to(volt, statvolt, cgs_gauss) == 10**6*statvolt/299792458 + assert convert_to(farad, centimeter, cgs_gauss) == 299792458**2*centimeter/10**5 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unitsystem.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unitsystem.py new file mode 100644 index 0000000000000000000000000000000000000000..a04f3aabb6274bed4f1b82ac0719fa618b55eed7 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_unitsystem.py @@ -0,0 +1,86 @@ +from sympy.physics.units import DimensionSystem, joule, second, ampere + +from sympy.core.numbers import Rational +from sympy.core.singleton import S +from sympy.physics.units.definitions import c, kg, m, s +from sympy.physics.units.definitions.dimension_definitions import length, time +from sympy.physics.units.quantities import Quantity +from sympy.physics.units.unitsystem import UnitSystem +from sympy.physics.units.util import convert_to + + +def test_definition(): + # want to test if the system can have several units of the same dimension + dm = Quantity("dm") + base = (m, s) + # base_dim = (m.dimension, s.dimension) + ms = UnitSystem(base, (c, dm), "MS", "MS system") + ms.set_quantity_dimension(dm, length) + ms.set_quantity_scale_factor(dm, Rational(1, 10)) + + assert set(ms._base_units) == set(base) + assert set(ms._units) == {m, s, c, dm} + # assert ms._units == DimensionSystem._sort_dims(base + (velocity,)) + assert ms.name == "MS" + assert ms.descr == "MS system" + + +def test_str_repr(): + assert str(UnitSystem((m, s), name="MS")) == "MS" + assert str(UnitSystem((m, s))) == "UnitSystem((meter, second))" + + assert repr(UnitSystem((m, s))) == "" % (m, s) + + +def test_convert_to(): + A = Quantity("A") + A.set_global_relative_scale_factor(S.One, ampere) + + Js = Quantity("Js") + Js.set_global_relative_scale_factor(S.One, joule*second) + + mksa = UnitSystem((m, kg, s, A), (Js,)) + assert convert_to(Js, mksa._base_units) == m**2*kg*s**-1/1000 + + +def test_extend(): + ms = UnitSystem((m, s), (c,)) + Js = Quantity("Js") + Js.set_global_relative_scale_factor(1, joule*second) + mks = ms.extend((kg,), (Js,)) + + res = UnitSystem((m, s, kg), (c, Js)) + assert set(mks._base_units) == set(res._base_units) + assert set(mks._units) == set(res._units) + + +def test_dim(): + dimsys = UnitSystem((m, kg, s), (c,)) + assert dimsys.dim == 3 + + +def test_is_consistent(): + dimension_system = DimensionSystem([length, time]) + us = UnitSystem([m, s], dimension_system=dimension_system) + assert us.is_consistent == True + + +def test_get_units_non_prefixed(): + from sympy.physics.units import volt, ohm + unit_system = UnitSystem.get_unit_system("SI") + units = unit_system.get_units_non_prefixed() + for prefix in ["giga", "tera", "peta", "exa", "zetta", "yotta", "kilo", "hecto", "deca", "deci", "centi", "milli", "micro", "nano", "pico", "femto", "atto", "zepto", "yocto"]: + for unit in units: + assert isinstance(unit, Quantity), f"{unit} must be a Quantity, not {type(unit)}" + assert not unit.is_prefixed, f"{unit} is marked as prefixed" + assert not unit.is_physical_constant, f"{unit} is marked as physics constant" + assert not unit.name.name.startswith(prefix), f"Unit {unit.name} has prefix {prefix}" + assert volt in units + assert ohm in units + +def test_derived_units_must_exist_in_unit_system(): + for unit_system in UnitSystem._unit_systems.values(): + for preferred_unit in unit_system.derived_units.values(): + units = preferred_unit.atoms(Quantity) + for unit in units: + assert unit in unit_system._units, f"Unit {unit} is not in unit system {unit_system}" diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_util.py b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ab311e86ac468a7cf0173bfff6d10907750dc9a0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/physics/units/tests/test_util.py @@ -0,0 +1,162 @@ +from sympy.core.containers import Tuple +from sympy.core.numbers import pi +from sympy.core.power import Pow +from sympy.core.symbol import symbols +from sympy.core.sympify import sympify +from sympy.printing.str import sstr +from sympy.physics.units import ( + G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin, + kilogram, kilometer, length, meter, mile, minute, newton, planck, + planck_length, planck_mass, planck_temperature, planck_time, radians, + second, speed_of_light, steradian, time, km) +from sympy.physics.units.util import convert_to, check_dimensions +from sympy.testing.pytest import raises + + +def NS(e, n=15, **options): + return sstr(sympify(e).evalf(n, **options), full_prec=True) + + +L = length +T = time + + +def test_dim_simplify_add(): + # assert Add(L, L) == L + assert L + L == L + + +def test_dim_simplify_mul(): + # assert Mul(L, T) == L*T + assert L*T == L*T + + +def test_dim_simplify_pow(): + assert Pow(L, 2) == L**2 + + +def test_dim_simplify_rec(): + # assert Mul(Add(L, L), T) == L*T + assert (L + L) * T == L*T + + +def test_convert_to_quantities(): + assert convert_to(3, meter) == 3 + + assert convert_to(mile, kilometer) == 25146*kilometer/15625 + assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458 + assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light + assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light + assert convert_to(speed_of_light, meter/second) == 299792458*meter/second + assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second + assert convert_to(day, second) == 86400*second + assert convert_to(2*hour, minute) == 120*minute + assert convert_to(mile, meter) == 201168*meter/125 + assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour) + assert convert_to(3*newton, meter/second) == 3*newton + assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2 + assert convert_to(kilometer + mile, meter) == 326168*meter/125 + assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125 + assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000 + assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000 + assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second) + assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second) + assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2 + + assert convert_to(steradian, coulomb) == steradian + assert convert_to(radians, degree) == 180*degree/pi + assert convert_to(radians, [meter, degree]) == 180*degree/pi + assert convert_to(pi*radians, degree) == 180*degree + assert convert_to(pi, degree) == 180*degree + + +def test_convert_to_tuples_of_quantities(): + assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second + assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second + assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second + assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2 + assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2 + assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light + assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2 + # This doesn't make physically sense, but let's keep it as a conversion test: + assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second + assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G + + assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000/speed_of_light**1.500000' + assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram' + assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter' + assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second' + assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin' + assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter' + + +def test_eval_simplify(): + from sympy.physics.units import cm, mm, km, m, K, kilo + from sympy.core.symbol import symbols + + x, y = symbols('x y') + + assert (cm/mm).simplify() == 10 + assert (km/m).simplify() == 1000 + assert (km/cm).simplify() == 100000 + assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin + assert (cm/km/m).simplify() == 1/(10000000*centimeter) + + assert (3*kilo*meter).simplify() == 3000*meter + assert (4*kilo*meter/(2*kilometer)).simplify() == 2 + assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4 + + +def test_quantity_simplify(): + from sympy.physics.units.util import quantity_simplify + from sympy.physics.units import kilo, foot + from sympy.core.symbol import symbols + + x, y = symbols('x y') + + assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y) + assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12 + assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12 + assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12 + assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144 + +def test_quantity_simplify_across_dimensions(): + from sympy.physics.units.util import quantity_simplify + from sympy.physics.units import ampere, ohm, volt, joule, pascal, farad, second, watt, siemens, henry, tesla, weber, hour, newton + + assert quantity_simplify(ampere*ohm, across_dimensions=True, unit_system="SI") == volt + assert quantity_simplify(6*ampere*ohm, across_dimensions=True, unit_system="SI") == 6*volt + assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm + assert quantity_simplify(volt/ohm, across_dimensions=True, unit_system="SI") == ampere + assert quantity_simplify(joule/meter**3, across_dimensions=True, unit_system="SI") == pascal + assert quantity_simplify(farad*ohm, across_dimensions=True, unit_system="SI") == second + assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt + assert quantity_simplify(meter**3/second, across_dimensions=True, unit_system="SI") == meter**3/second + assert quantity_simplify(joule/second, across_dimensions=True, unit_system="SI") == watt + + assert quantity_simplify(joule/coulomb, across_dimensions=True, unit_system="SI") == volt + assert quantity_simplify(volt/ampere, across_dimensions=True, unit_system="SI") == ohm + assert quantity_simplify(ampere/volt, across_dimensions=True, unit_system="SI") == siemens + assert quantity_simplify(coulomb/volt, across_dimensions=True, unit_system="SI") == farad + assert quantity_simplify(volt*second/ampere, across_dimensions=True, unit_system="SI") == henry + assert quantity_simplify(volt*second/meter**2, across_dimensions=True, unit_system="SI") == tesla + assert quantity_simplify(joule/ampere, across_dimensions=True, unit_system="SI") == weber + + assert quantity_simplify(5*kilometer/hour, across_dimensions=True, unit_system="SI") == 25*meter/(18*second) + assert quantity_simplify(5*kilogram*meter/second**2, across_dimensions=True, unit_system="SI") == 5*newton + +def test_check_dimensions(): + x = symbols('x') + assert check_dimensions(inch + x) == inch + x + assert check_dimensions(length + x) == length + x + # after subs we get 2*length; check will clear the constant + assert check_dimensions((length + x).subs(x, length)) == length + assert check_dimensions(newton*meter + joule) == joule + meter*newton + raises(ValueError, lambda: check_dimensions(inch + 1)) + raises(ValueError, lambda: check_dimensions(length + 1)) + raises(ValueError, lambda: check_dimensions(length + time)) + raises(ValueError, lambda: check_dimensions(meter + second)) + raises(ValueError, lambda: check_dimensions(2 * meter + second)) + raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second)) + raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter)) + raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km)) diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/py.typed b/llmeval-env/lib/python3.10/site-packages/sympy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/release.py b/llmeval-env/lib/python3.10/site-packages/sympy/release.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0cd9f51b685e98781a28872c4984338e242104 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/release.py @@ -0,0 +1 @@ +__version__ = "1.12" diff --git a/llmeval-env/lib/python3.10/site-packages/sympy/this.py b/llmeval-env/lib/python3.10/site-packages/sympy/this.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a5504ac42c7d57790d65524b066a6df86ab539 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/sympy/this.py @@ -0,0 +1,21 @@ +""" +The Zen of SymPy. +""" + +s = """The Zen of SymPy + +Unevaluated is better than evaluated. +The user interface matters. +Printing matters. +Pure Python can be fast enough. +If it's too slow, it's (probably) your fault. +Documentation matters. +Correctness is more important than speed. +Push it in now and improve upon it later. +Coverage by testing matters. +Smart tests are better than random tests. +But random tests sometimes find what your smartest test missed. +The Python way is probably the right way. +Community is more important than code.""" + +print(s)