K iA$ddlmZddlmZddlmZddlmZmZm Z ddl m Z ddl m Z ddlmZddlmZmZmZdd lmZdd lmZdd lmZdd lmZmZdd lmZddlm Z ddl!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(ddgZ)dZ*GddeZ+GddZ,y)wraps)Basic)ImmutableMatrix)Matrixeyezeros OrderedSet) ActuatorBase)BodyBase) Lagrangian_validate_coordinatesfind_dynamicsymbols)Joint) KanesMethod)LagrangesMethod) _parse_loadgravity)_Methods)Particle)PointReferenceFramedynamicsymbols)iterable) filldedentSymbolicSystemSystemc.tfd}|S)z;Decorator to reset the eom_method if a property is changed.c*d|_|g|i|SN _eom_method)selfargskwargsmethods d/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/physics/mechanics/system.pywrapperz"_reset_eom_method..wrappers d,T,V,,r)r'r)s` r(_reset_eom_methodr+s" 6]-- Nr*c8eZdZdZdCdZedZedZedZ edZ edZ ed Z ed Z e jed Z ed Zejed ZedZejedZedZejedZedZedZedZejedZedZejedZedZejedZedZejedZedZejedZedZejedZed Zejed!Zed"Zejed#Zed$Zejed%Zed&Zed'Z ed(Z! dDd)Z"e dEd+Z#ed,d-d.Z$ed,d-d/Z%ed0Z&ed1Z'ed2Z(ed3Z)ed4Z*ed5Z+ed6Z,ed7Z-ed8Z.d9Z/d:Z0d;Z1e2fd<Z3dFd=Z4ed>Z5ed?Z6ed@Z7edAZ8e2d*fdBZ9y)GraVClass to define a multibody system and form its equations of motion. Explanation =========== A ``System`` instance stores the different objects associated with a model, including bodies, joints, constraints, and other relevant information. With all the relationships between components defined, the ``System`` can be used to form the equations of motion using a backend, such as ``KanesMethod``. The ``System`` has been designed to be compatible with third-party libraries for greater flexibility and integration with other tools. Attributes ========== frame : ReferenceFrame Inertial reference frame of the system. fixed_point : Point A fixed point in the inertial reference frame. x : Vector Unit vector fixed in the inertial reference frame. y : Vector Unit vector fixed in the inertial reference frame. z : Vector Unit vector fixed in the inertial reference frame. q : ImmutableMatrix Matrix of all the generalized coordinates, i.e. the independent generalized coordinates stacked upon the dependent. u : ImmutableMatrix Matrix of all the generalized speeds, i.e. the independent generealized speeds stacked upon the dependent. q_ind : ImmutableMatrix Matrix of the independent generalized coordinates. q_dep : ImmutableMatrix Matrix of the dependent generalized coordinates. u_ind : ImmutableMatrix Matrix of the independent generalized speeds. u_dep : ImmutableMatrix Matrix of the dependent generalized speeds. u_aux : ImmutableMatrix Matrix of auxiliary generalized speeds. kdes : ImmutableMatrix Matrix of the kinematical differential equations as expressions equated to the zero matrix. bodies : tuple of BodyBase subclasses Tuple of all bodies that make up the system. joints : tuple of Joint Tuple of all joints that connect bodies in the system. loads : tuple of LoadBase subclasses Tuple of all loads that have been applied to the system. actuators : tuple of ActuatorBase subclasses Tuple of all actuators present in the system. holonomic_constraints : ImmutableMatrix Matrix with the holonomic constraints as expressions equated to the zero matrix. nonholonomic_constraints : ImmutableMatrix Matrix with the nonholonomic constraints as expressions equated to the zero matrix. velocity_constraints : ImmutableMatrix Matrix with the velocity constraints as expressions equated to the zero matrix. These are by default derived as the time derivatives of the holonomic constraints extended with the nonholonomic constraints. eom_method : subclass of KanesMethod or LagrangesMethod Backend for forming the equations of motion. Examples ======== In the example below a cart with a pendulum is created. The cart moves along the x axis of the rail and the pendulum rotates about the z axis. The length of the pendulum is ``l`` with the pendulum represented as a particle. To move the cart a time dependent force ``F`` is applied to the cart. We first need to import some functions and create some of our variables. >>> from sympy import symbols, simplify >>> from sympy.physics.mechanics import ( ... mechanics_printing, dynamicsymbols, RigidBody, Particle, ... ReferenceFrame, PrismaticJoint, PinJoint, System) >>> mechanics_printing(pretty_print=False) >>> g, l = symbols('g l') >>> F = dynamicsymbols('F') The next step is to create bodies. It is also useful to create a frame for locating the particle with respect to the pin joint later on, as a particle does not have a body-fixed frame. >>> rail = RigidBody('rail') >>> cart = RigidBody('cart') >>> bob = Particle('bob') >>> bob_frame = ReferenceFrame('bob_frame') Initialize the system, with the rail as the Newtonian reference. The body is also automatically added to the system. >>> system = System.from_newtonian(rail) >>> print(system.bodies[0]) rail Create the joints, while immediately also adding them to the system. >>> system.add_joints( ... PrismaticJoint('slider', rail, cart, joint_axis=rail.x), ... PinJoint('pin', cart, bob, joint_axis=cart.z, ... child_interframe=bob_frame, ... child_point=l * bob_frame.y) ... ) >>> system.joints (PrismaticJoint: slider parent: rail child: cart, PinJoint: pin parent: cart child: bob) While adding the joints, the associated generalized coordinates, generalized speeds, kinematic differential equations and bodies are also added to the system. >>> system.q Matrix([ [q_slider], [ q_pin]]) >>> system.u Matrix([ [u_slider], [ u_pin]]) >>> system.kdes Matrix([ [u_slider - q_slider'], [ u_pin - q_pin']]) >>> [body.name for body in system.bodies] ['rail', 'cart', 'bob'] With the kinematics established, we can now apply gravity and the cart force ``F``. >>> system.apply_uniform_gravity(-g * system.y) >>> system.add_loads((cart.masscenter, F * rail.x)) >>> system.loads ((rail_masscenter, - g*rail_mass*rail_frame.y), (cart_masscenter, - cart_mass*g*rail_frame.y), (bob_masscenter, - bob_mass*g*rail_frame.y), (cart_masscenter, F*rail_frame.x)) With the entire system defined, we can now form the equations of motion. Before forming the equations of motion, one can also run some checks that will try to identify some common errors. >>> system.validate_system() >>> system.form_eoms() Matrix([ [bob_mass*l*u_pin**2*sin(q_pin) - bob_mass*l*cos(q_pin)*u_pin' - (bob_mass + cart_mass)*u_slider' + F], [ -bob_mass*g*l*sin(q_pin) - bob_mass*l**2*u_pin' - bob_mass*l*cos(q_pin)*u_slider']]) >>> simplify(system.mass_matrix) Matrix([ [ bob_mass + cart_mass, bob_mass*l*cos(q_pin)], [bob_mass*l*cos(q_pin), bob_mass*l**2]]) >>> system.forcing Matrix([ [bob_mass*l*u_pin**2*sin(q_pin) + F], [ -bob_mass*g*l*sin(q_pin)]]) The complexity of the above example can be increased if we add a constraint to prevent the particle from moving in the horizontal (x) direction. This can be done by adding a holonomic constraint. After which we should also redefine what our (in)dependent generalized coordinates and speeds are. >>> system.add_holonomic_constraints( ... bob.masscenter.pos_from(rail.masscenter).dot(system.x) ... ) >>> system.q_ind = system.get_joint('pin').coordinates >>> system.q_dep = system.get_joint('slider').coordinates >>> system.u_ind = system.get_joint('pin').speeds >>> system.u_dep = system.get_joint('slider').speeds With the updated system the equations of motion can be formed again. >>> system.validate_system() >>> system.form_eoms() Matrix([[-bob_mass*g*l*sin(q_pin) - bob_mass*l**2*u_pin' - bob_mass*l*cos(q_pin)*u_slider' - l*(bob_mass*l*u_pin**2*sin(q_pin) - bob_mass*l*cos(q_pin)*u_pin' - (bob_mass + cart_mass)*u_slider')*cos(q_pin) - l*F*cos(q_pin)]]) >>> simplify(system.mass_matrix) Matrix([ [bob_mass*l**2*sin(q_pin)**2, -cart_mass*l*cos(q_pin)], [ l*cos(q_pin), 1]]) >>> simplify(system.forcing) Matrix([ [-l*(bob_mass*g*sin(q_pin) + bob_mass*l*u_pin**2*sin(2*q_pin)/2 + F*cos(q_pin))], [ l*u_pin**2*sin(q_pin)]]) Nc$| td}nt|ts td||_| t d}nt|ts td||_|j j |jdtddgj|_ tddgj|_ tddgj|_ tddgj|_ tddgj|_ tddgj|_tddgj|_tddgj|_d|_g|_g|_g|_g|_d|_y)aInitialize the system. Parameters ========== frame : ReferenceFrame, optional The inertial frame of the system. If none is supplied, a new frame will be created. fixed_point : Point, optional A fixed point in the inertial reference frame. If none is supplied, a new fixed_point will be created. Ninertial_framez,Frame must be an instance of ReferenceFrame.inertial_pointz)Fixed point must be an instance of Point.r)r isinstance TypeError_framer _fixed_pointset_velrT_q_ind_q_dep_u_ind_u_dep_u_aux_kdes _hol_coneqs_nonhol_coneqs _vel_constrs_bodies_joints_loads _actuatorsr#)r$frame fixed_points r(__init__zSystem.__init__sX ="#34EE>2JK K   01KK/GH H' !!$++q1%aB/11 %aB/11 %aB/11 %aB/11 %aB/11 $Q2.00 *1a466-aB799    r*ct|tr td||j|j}|j ||S)z7Constructs the system with respect to a Newtonian body.z7A Particle has no frame so cannot act as the Newtonian.)rDrE)r1rr2rD masscenter add_bodies)cls newtoniansystems r(from_newtonianzSystem.from_newtoniansI i *-. .9?? 8L8LM)$ r*c|jS)z,Fixed point in the inertial reference frame.)r4r$s r(rEzSystem.fixed_points   r*c|jS)z'Inertial reference frame of the system.)r3rOs r(rDz System.frame!{{r*c.|jjSz2Unit vector fixed in the inertial reference frame.)r3xrOs r(rTzSystem.x&{{}}r*c.|jjSrS)r3yrOs r(rWzSystem.y+rUr*c.|jjSrS)r3zrOs r(rYzSystem.z0rUr*c,t|jS)z7Tuple of all bodies that have been added to the system.)tupler@rOs r(bodiesz System.bodies5T\\""r*cf|j|}|j|gtdd||_y)NBodiesr\)_objects_to_list_check_objectsr r@r$r\s r(r\z System.bodies:s1&&v. FB(HE r*c,t|jS)z7Tuple of all joints that have been added to the system.)r[rArOs r(jointsz System.jointsAr]r*c|j|}|j|gtddg|_|j|y)NJointsrd)r`rarrA add_joints)r$rds r(rdz System.jointsFs?&&v. FBxB  r*c,t|jS)z4Tuple of loads that have been applied on the system.)r[rBrOs r(loadsz System.loadsNsT[[!!r*cl|j|}|Dcgc] }t|c}|_ycc}wr!)r`rrBr$riloads r(riz System.loadsSs.%%e,5:;T{4(; ;s1c,t|jS)z)Tuple of actuators present in the system.)r[rCrOs r( actuatorszSystem.actuatorsYsT__%%r*cf|j|}|j|gtdd||_y)N Actuatorsrn)r`rar rCr$rns r(rnzSystem.actuators^s4)))4  Ir<' )#r*cL|jj|jS)zbMatrix of all the generalized coordinates with the independent stacked upon the dependent.)r7col_joinr8rOs r(qzSystem.qf{{##DKK00r*cL|jj|jS)z]Matrix of all the generalized speeds with the independent stacked upon the dependent.)r9rsr:rOs r(uzSystem.ulrur*c|jS)z2Matrix of the independent generalized coordinates.)r7rOs r(q_indz System.q_indrrQr*cz|j|j|dg|jd\|_|_y)NT coordinates)_parse_coordinatesr`q_depr7r8)r$rys r(ryz System.q_indws8$(#:#:  ! !% ($DJJ $O  T[r*c|jS)z0Matrix of the dependent generalized coordinates.)r8rOs r(r}z System.q_dep}rQr*cz|j|j|d|jgd\|_|_y)NFr{)r|r`ryr7r8)r$r}s r(r}z System.q_deps8$(#:#:  ! !% (%R$P  T[r*c|jS)z-Matrix of the independent generalized speeds.)r9rOs r(u_indz System.u_indrQr*cz|j|j|dg|jd\|_|_y)NTspeeds)r|r`u_depr9r:)r$rs r(rz System.u_inds8$(#:#:  ! !% ($DJJ$J  T[r*c|jS)z+Matrix of the dependent generalized speeds.)r:rOs r(rz System.u_deprQr*cz|j|j|d|jgd\|_|_y)NFr)r|r`rr9r:)r$rs r(rz System.u_deps8$(#:#:  ! !% (%R$K  T[r*c|jS)z'Matrix of auxiliary generalized speeds.)r;rOs r(u_auxz System.u_auxrQr*c\|j|j|dggdd|_y)NT u_auxiliaryr)r|r`r;)r$rs r(rz System.u_auxs6--  ! !% ($B GGHJ r*c|jS)zKinematical differential equations as expressions equated to the zero matrix. These equations describe the coupling between the generalized coordinates and the generalized speeds.)r<rOs r(kdesz System.kdess zzr*cV|j|}|j|gd|_y)N kinematic differential equations)r`_parse_expressionsr<r$rs r(rz System.kdess.$$T*,, "8: r*c|jS)zXMatrix with the holonomic constraints as expressions equated to the zero matrix.)r=rOs r(holonomic_constraintszSystem.holonomic_constraintssr*cV|j|}|j|gd|_y)Nholonomic constraints)r`rr=r$ constraintss r(rzSystem.holonomic_constraintss/++K8 22 46r*c|jS)z[Matrix with the nonholonomic constraints as expressions equated to the zero matrix.)r>rOs r(nonholonomic_constraintszSystem.nonholonomic_constraintss"""r*cV|j|}|j|gd|_y)Nnonholonomic constraints)r`rr>rs r(rzSystem.nonholonomic_constraintss/++K8 "55 79r*c|jB|jjtjj |j S|jS)zMatrix with the velocity constraints as expressions equated to the zero matrix. The velocity constraints are by default derived from the holonomic and nonholonomic constraints unless they are explicitly set. )r?rdiffr_trsrrOs r(velocity_constraintszSystem.velocity_constraintssO    $--22>3D3DENN--/ /   r*cj|d|_y|j|}|j|gd|_y)Nzvelocity constraints)r?r`rrs r(rzSystem.velocity_constraintss@   $D  ++K8  33 35r*c|jS)z,Backend for forming the equations of motion.r"rOs r( eom_methodzSystem.eom_methodsr*c:t|s|gSt|ddS)z+Helper to convert passed objects to a list.N)rlist)lsts r(r`zSystem._objects_to_lists }5LCF|r*c*t|}t}t}|D]F}t||s|j|||vr|j|6|j|H|rt|d|d|d|rt |d|dy)aHelper to check the objects that are being added to the system. Explanation =========== This method checks that the objects that are being added to the system are of the correct type and have not already been added. If any of the objects are not of the correct type or have already been added, then an error is raised. Parameters ========== objects : iterable The objects that would be added to the system. obj_lst : list The list of objects that are already in the system. expected_type : type The type that the objects should be. obj_name : str The name of the category of objects. This string is used to formulate the error message for the user. type_name : str The name of the type that the objects should be. This string is used to formulate the error message for the user.  z are not .z' have already been added to the system.N)setr1addr2 ValueError) objectsobj_lst expected_typeobj_name type_nameseen duplicates wrong_typesobjs r(razSystem._check_objectss67|U e  Cc=1$d{s#   xj+i {!LM M z:,7./0 0 r*c |dd|dd}}t|s|gt|z}t||D]*\}} | r|j||j|,d|jdd|j ddzd|j dd|jddzd|jdd|||zi} tdi| tdt||jtdt||jfS)z'Helper to parse coordinates and speeds.Nr{rrr0) rlenzipappendryr}rrr;rrr6) r$ new_coords independentold_coords_indold_coords_dep coord_type coords_ind coords_depcoordindepcurrents r(r|zSystem._parse_coordinatess"0!2N14EJ  $&-#j/9K K8 )LE5!!%(!!%(  ) !$**Q-$**Q-"?TZZ]TZZ]: $++a.zJ68 ((3z?J?AA3z?J?AAC Cr*Fc,|dd}t|}|r||Dcgc]}| c}z}n|}tj||t|d|D]}|dk(s t d|dt dt |t |z||zjScc}w)z-Helper to parse expressions like constraints.N expressionsrzParsed z are zero.r0)rrrarrrrr6)new_expressionsold_expressionsnamecheck_negativesexpr check_exprss r(rzSystem._parse_expressions2s*!,/ ),OtdU,OOK)Ko{E4+ -# =Dqy 74& !;<< =q#o"6_9M"M.@BBC! D-Ps BT)rcp|j|||j|jd\|_|_y)aAdd generalized coordinate(s) to the system. Parameters ========== *coordinates : dynamicsymbols One or more generalized coordinates to be added to the system. independent : bool or list of bool, optional Boolean whether a coordinate is dependent or independent. The default is True, so the coordinates are added as independent by default. r{N)r|ryr}r7r8)r$rr{s r(add_coordinateszSystem.add_coordinatesDs1$(#:#: djj$**m$M  T[r*cp|j|||j|jd\|_|_y)aAdd generalized speed(s) to the system. Parameters ========== *speeds : dynamicsymbols One or more generalized speeds to be added to the system. independent : bool or list of bool, optional Boolean whether a speed is dependent or independent. The default is True, so the speeds are added as independent by default. rN)r|rrr9r:)r$rrs r( add_speedszSystem.add_speedsVs1$(#:#: KTZZ$C  T[r*cR|j|d|jgdd|_y)zAdd auxiliary speed(s) to the system. Parameters ========== *speeds : dynamicsymbols One or more auxiliary speeds to be added to the system. TrrN)r|r;)r$rs r(add_auxiliary_speedszSystem.add_auxiliary_speedsgs--- D$++r=::;= r*cL|j||jdd|_y)zAdd kinematic differential equation(s) to the system. Parameters ========== *kdes : Expr One or more kinematic differential equations. rTrN)rrr<rs r(add_kdeszSystem.add_kdesus*,, $))? -" r*cL|j||jdd|_y)zAdd holonomic constraint(s) to the system. Parameters ========== *constraints : Expr One or more holonomic constraints, which are expressions that should be zero. rTrN)rr=rs r(add_holonomic_constraintsz System.add_holonomic_constraintss- 22 ))+B 3"r*cL|j||jdd|_y)zAdd nonholonomic constraint(s) to the system. Parameters ========== *constraints : Expr One or more nonholonomic constraints, which are expressions that should be zero. rTrN)rr>rs r(add_nonholonomic_constraintsz#System.add_nonholonomic_constraintss-#55 ,,.H 6"r*c|j||jtdd|jj |y)zAdd body(ies) to the system. Parameters ========== bodies : Particle or RigidBody One or more bodies. r_r\N)rar\r r@extendrbs r(rIzSystem.add_bodiess0 FDKK8XN F#r*ct|Dcgc] }t|}}|jj|ycc}w)zAdd load(s) to the system. Parameters ========== *loads : Force or Torque One or more loads. N)rrBrrks r( add_loadszSystem.add_loadss3055tT"55 5!6s5cJ|jt|g|jy)zApply uniform gravity to all bodies in the system by adding loads. Parameters ========== acceleration : Vector The acceleration due to gravity. N)rrr\)r$ accelerations r(apply_uniform_gravityzSystem.apply_uniform_gravitys   ;t{{;z$System.add_joints..s,LaZ\,LsNc3,K|] }|dk(r |yw)rNr)rkdes r(rz$System.add_joints..sC#(Cs )rardrrArrangeupdater{rrparentchild differencertrwr\rr[rrrI)r$rdr{rrr\joints r(rgzSystem.add_jointssW6 FDKK(K F#,L58,L) VT6 7E   u00 1 MM%,, ' KK # MM5<<5 6  7 ",,TVV4 ""466*tyy| z1o=>""4;;/eK01v' CuT{CDv'r*cL|jD]}|j|k(s|cSy)a%Retrieve a body from the system by name. Parameters ========== name : str The name of the body to retrieve. Returns ======= RigidBody or Particle The body with the given name, or None if no such body exists. N)r@r)r$rbodys r(get_bodyzSystem.get_bodys( LL DyyD   r*cL|jD]}|j|k(s|cSy)a%Retrieve a joint from the system by name. Parameters ========== name : str The name of the joint to retrieve. Returns ======= subclass of Joint The joint with the given name, or None if no such joint exists. N)rAr)r$rrs r( get_jointzSystem.get_joints( \\ EzzT!  r*c"|jSr!) form_eomsrOs r( _form_eomszSystem._form_eoms0s~~r*c |jtd|jDz}|r|nd}t|trhd}|j |}|rt d|jd|d|j|j|j|j|j|j|j|j|j ||j"dd |}|di||_nt|t&rhd }|j |}|rt d|jd|d|j|j(||j"|j|j*d |}d |vrt-|d g|d |d <|di||_nt/|d|j0j3S)aForm the equations of motion of the system. Parameters ========== eom_method : subclass of KanesMethod or LagrangesMethod Backend class to be used for forming the equations of motion. The default is ``KanesMethod``. Returns ======== ImmutableMatrix 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, PrismaticJoint, Particle, ... RigidBody, System) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> wall = RigidBody('W') >>> system = System.from_newtonian(wall) >>> bob = Particle('P', mass=m) >>> bob.potential_energy = S.Half * k * q**2 >>> system.add_joints(PrismaticJoint('J', wall, bob, q, qd)) >>> system.add_loads((bob.masscenter, b * qd * system.x)) >>> system.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. >>> system.rhs() Matrix([ [ Derivative(q(t), t)], [(b*Derivative(q(t), t) - k*q(t))/m]]) c3JK|]}|jD]}|ywr!)to_loads)ractrls r(rz#System.form_eoms..bs1#Gs||~#G/3D#G #Gs!#N> rDryrr\kd_eqs forcelist q_dependentr u_dependentrconfiguration_constraintszEThe following keyword arguments are not allowed to be overwritten in z: rF) rDryrrrrrrrrr\explicit_kinematics>qsrDr\rr hol_coneqs nonhol_coneqs)rDrrr\rrrrDr\ has not been implemented.r)rir[rn issubclassr intersectionr__name__rDryrrr}rrrrr\r#rrtrrNotImplementedErrorrr)r$rr&ridisallowed_kwargs wrong_kwargss r(rzSystem.form_eoms3s^ U#G NN#GGGD j+ .!? -99&AL &&0&9&9%:"\N!MNN $zzDJJ#zzTYY%)ZZ 373M3M.2.G.G%)ZZ#(DKK-2>7=>F *3F3D   O 4!/ -99&AL &&0&9&9%:"\N!MNN $zze $ $($>$>'+'D'DPIOPF6)'1&/(E39(3C(E|$)3F3D % 4N&OP P))++r*c:|jj|S)aCompute the equations of motion in the explicit form. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrixbase.MatrixBase.inv` Returns ======== ImmutableMatrix Equations of motion in the explicit form. See Also ======== sympy.physics.mechanics.kane.KanesMethod.rhs: KanesMethod's ``rhs`` function. sympy.physics.mechanics.lagrange.LagrangesMethod.rhs: LagrangesMethod's ``rhs`` function. ) inv_method)rrhs)r$r s r(r z System.rhss4""j"99r*c.|jjS)abThe mass matrix of the system. Explanation =========== The mass matrix $M_d$ and the forcing vector $f_d$ of a system describe the system's dynamics according to the following equations: .. math:: M_d \dot{u} = f_d where $\dot{u}$ is the time derivative of the generalized speeds. )r mass_matrixrOs r(rzSystem.mass_matrixs ***r*c.|jjS)aThe mass matrix of the system, augmented by the kinematic differential equations in explicit or implicit form. Explanation =========== The full mass matrix $M_m$ and the full forcing vector $f_m$ of a system describe the dynamics and kinematics according to the following equation: .. math:: M_m \dot{x} = f_m where $x$ is the state vector stacking $q$ and $u$. )rmass_matrix_fullrOs r(rzSystem.mass_matrix_fulls$///r*c.|jjS)z!The forcing vector of the system.)rforcingrOs r(rzSystem.forcings&&&r*c.|jjS)zyThe forcing vector of the system, augmented by the kinematic differential equations in explicit or implicit form.)r forcing_fullrOs r(rzSystem.forcing_fulls+++r*c Z g}|jjd}|jjd}|jjd|jjd}}t |j t |j} }t|t| } } ||k7r!|jtd|d|dt } |jD]5} | jt | jj|7| r|jtd| dt|t rst|j"}t t }}|jD]} |jt | j$j| |jt | j"j|j"dd|j" ddz|r|jtd|d |r|jtd |d ||k7r!|jtd |d |d| | kDr!|jtd| d| d| |k7rM|jtd| d|dn*t|t&r t |jj|j j)t*j,}|jD]\} |jt | j$j|j j)t*j,^|r|jtd|d|j.r7|jtd|j.dnt1|d|rd|j fd|jfd|j.fd|j2fd|jfg}|D]X\}}t }|Dchc]}||vs|j5|s|}}|s8|jtd|d|dZ|rt7dj9|ycc}w)aValidates the system using some basic checks. Explanation =========== This method validates the system based on the following checks: - The number of dependent generalized coordinates should equal the number of holonomic constraints. - All generalized coordinates defined by the joints should also be known to the system. - If ``KanesMethod`` is used as a ``eom_method``: - All generalized speeds and kinematic differential equations defined by the joints should also be known to the system. - The number of dependent generalized speeds should equal the number of velocity constraints. - The number of generalized coordinates should be less than or equal to the number of generalized speeds. - The number of generalized coordinates should equal the number of kinematic differential equations. - If ``LagrangesMethod`` is used as ``eom_method``: - There should not be any generalized speeds that are not derivatives of the generalized coordinates (this includes the generalized speeds defined by the joints). Parameters ========== eom_method : subclass of KanesMethod or LagrangesMethod Backend class that will be used for forming the equations of motion. There are different checks for the different backends. The default is ``KanesMethod``. check_duplicates : bool Boolean whether the system should be checked for duplicate definitions. The default is False, because duplicates are already checked when adding objects to the system. Notes ===== This method is not guaranteed to be backwards compatible as it may improve over time. The method can become both more and less strict in certain areas. However a well-defined system should always pass all these tests. rz= The number of dependent generalized coordinates zD should be equal to the number of holonomic constraints rz) The generalized coordinates z8 used in joints are not added to the system.Nz( The generalized speeds z< used in joints are not added to the system.z6 The kinematic differential equations z< used in joints are not added to the system.z< The number of dependent generalized speeds zG should be equal to the number of velocity constraints z7 The number of generalized coordinates zR should be less than or equal to the number of generalized speeds z2 The number of generalized speeds zS should be equal to the number of kinematic differential equations z are not supported by this method. Only derivatives of the generalized coordinates are supported. If these symbols are used in your expressions, then this will result in wrong equations of motion.z This method does not support auxiliary speeds. If these symbols are used in your expressions, then this will result in wrong equations of motion. The auxiliary speeds are rzgeneralized coordinateszgeneralized speedszauxiliary speedsr\rdz The rz< exist multiple times within the system. )rshaperr}rrrtrwrrrrdrr{rrrrrrrrrrrr\rrjoin)r$rcheck_duplicatesmsgsn_hcn_vcn_q_depn_u_depq_setu_setn_qn_u missing_qrn_kdes missing_kdes missing_u not_qdotsduplicates_to_checkrrrrTrs r(validate_systemzSystem.validate_systems^))//2((..q1::++A. 0@0@0C466{CKuu:s5zS d? KK (==DIF::>q$DE FE [[ GE   S!2!23>>uE F G  KK ())2 4$  j+ .^F&)eSU)L 5  U\\!2!=!=e!DE##C O$>$>IIaLTYYJ?2%45 5 J,((1{3("#$ J,66B^D4(789$ J,<>AU!(GHIf} J,2257<;L;L/MNI N  LL""",*TVV[[9J9J-K"LN N J,((1{3?(BCD zz J,?@Dzzl!(OPQ & 4N&OP P $=tvv#F$8$&&#A$6 #C$,dkk#:$,dkk#: #<  1 ! cu),IAT TXXa[aI IKK 0a |,,! !  ! TYYt_- -  Js R(R()NN)r{)Fr!):r __module__ __qualname____doc__rF classmethodrMpropertyrErDrTrWrYr\setterr+rdrirnrtrwryr}rrrrrrrr staticmethodr`rar|rrrrrrrrIrrrrgrrrrrr rrrrr*rr*r(rr#s+DL& P!!## ]] ## ]]!! "" \\<<&&$$ 11 11  \\OO \\PP \\JJ \\KK \\JJ  [[::   !!6"6 ## $$9%9 !!  5!5   (0(0V7DC*+0DD"8<MM".2CC  = = " " " " " " $ $ " " = = * *)()(V(( $/X,t:8++"00&'',, *5u.r*c eZdZdZddddiddddf dZedZedZedZedZ edZ ed Z ed Z ed Z d Zed ZedZdZdZedZedZy)raB"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 Nc ~|it||_|d|_n"|D cgc]} ||  } } t| |_| d|_nm| D cgc]} ||  }} t||_nJt||_t||_|jj |j|_|+||_||_||_d|_d|_ d|_ nW|+d|_d|_d|_||_||_ d|_ n*d|_d|_d|_d|_d|_ ||_ |||D cgc]} | t|z}} ||_ ||_ t| ts | t| } t| ts | t| } | |_| |_ycc} wcc} wcc} w)z#Initializes a SymbolicSystem objectN)r_states _coordinates_speedsrs_kin_explicit_rhs_dyn_implicit_rhs_dyn_implicit_mat_comb_implicit_rhs_comb_implicit_mat_comb_explicit_rhsr_alg_con output_eqnsr1r[r@rB)r$ coord_statesright_hand_siderrcoordinate_derivativesalg_conr> coord_idxs speed_idxsr\riicoords speeds_inters r(rFzSymbolicSystem.__init__%s >!,/DL!$(!3=>a,q/>>$*6N!!# 9CDA QD D%l3 &| 4D !&>DL,,55dllCDL " -%;D "%4D "%0D "&*D #&*D #&*D #  $%)D "%)D "%)D "&5D #&1D #&*D #%)D "%)D "%)D "&*D #&*D #&5D #  #9#E@GH1q3566HGH &&%(V-?6]F%'E,=%LE  c? E@Is F0 F5F:cH|j td|jS)z8Returns the column matrix of the generalized coordinatesz#The coordinates were not specified.)r5AttributeErrorrOs r(r{zSymbolicSystem.coordinateses(    $ !FG G$$ $r*cH|j td|jS)z/Returns the column matrix of generalized speedszThe speeds were not specified.)r6rIrOs r(rzSymbolicSystem.speedsms$ <<  !AB B<< r*c|jS)z0Returns the column matrix of the state variables)r4rOs r(stateszSymbolicSystem.statesus||r*c|jS)zReturns a list with the indices of the rows containing algebraic constraints in the combined form of the equations of motion)r=rOs r(rBzSymbolicSystem.alg_conzs}}r*cH|j td|jS)zReturns the matrix, M, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not includedzJdyn_implicit_mat is not specified for equations of motion form [1] or [2].)r9rIrOs r(dyn_implicit_matzSymbolicSystem.dyn_implicit_mat3  ! ! ) "HI I)) )r*cH|j td|jS)zReturns the column matrix, F, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not includedzJdyn_implicit_rhs is not specified for equations of motion form [1] or [2].)r8rIrOs r(dyn_implicit_rhszSymbolicSystem.dyn_implicit_rhsrPr*c|j|jt|j}t|j}t ||}t ||}t |j|}|j|j}|j||_|jStd|jS)zReturns the matrix, M, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are includedzDcomb_implicit_mat is not specified for equations of motion form [1].) r;r9rr7r8r rrow_joinrsrI)r$ num_kin_eqns num_dyn_eqnszeros1zeros2inter1inter2s r(comb_implicit_matz SymbolicSystem.comb_implicit_mats  " " *%%1"4#9#9: "4#9#9: |\:|\:\*33F;)?)?@*0//&*A'...$&EFF** *r*c|jQ|j:|j}|j}|j||_|jSt d|jS)zReturns the column matrix, F, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are includedzGcomb_implicit_mat is not specified for equations of motion in form [1].)r:r8r7rsrI)r$ kin_inter dyn_inters r(comb_implicit_rhsz SymbolicSystem.comb_implicit_rhsst  " " *%%1 22  22 *3*<*|jj |j }|j |}||_y|jj |j}||_y)zIf 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.Nz$comb_explicit_rhs is already formed.kin_explicit_rhs) r<rIgetattrr9LUsolver8rsr;r:)r$rYrZouts r(compute_explicit_formz$SymbolicSystem.compute_explicit_forms  " " . !GH H148  ++33D4J4JKF//&)C#&))11$2I2IJC"%r*cH|j td|jS)zReturns the right hand side of the equations of motion in explicit form, x' = F, where the kinematical equations are includedzPPlease run .combute_explicit_form before attempting to access comb_explicit_rhs.)r<rIrOs r(comb_explicit_rhsz SymbolicSystem.comb_explicit_rhss3  " " * "KL L** *r*cH|j td|jS)zYReturns the right hand side of the kinematical equations in explicit form, q' = GzJkin_explicit_rhs is not specified for equations of motion form [1] or [2].)r7rIrOs r(razSymbolicSystem.kin_explicit_rhss3  ! ! ) "HI I)) )r*c|j |jdd|jddz}n|jdd}t}|D]}|j t |}|j |j }t|S)z_Returns a column matrix containing all of the symbols in the system that depend on timeN)r<r[r_runionrr4r[)r$eom_expressionsfunctions_of_timers r(dynamic_symbolszSymbolicSystem.dynamic_symbolss  " " *#55a8#55a8 9O $66q9OE# +D 1 7 7#D)!+  +.33DLLA&''r*c$|j |jdd|jddz}n|jdd}t}|D]}|j |j }|j tjt|S)zfReturns a column matrix containing all of the symbols in the system that do not depend on timeN) r<r[r_rrj free_symbolsremoverrr[)r$rk constantsrs r(constant_symbolszSymbolicSystem.constant_symbolss  " " *#55a8#55a8 9O $66q9OE # ;D!(9(9:I ;**+Yr*cH|j td|jS)z Returns the bodies in the systemz)bodies were not specified for the system.)r@rIrOs r(r\zSymbolicSystem.bodiess$ <<  !LM M<< r*cH|j td|jS)zReturns the loads in the systemz(loads were not specified for the system.)rBrIrOs r(rizSymbolicSystem.loads s$ ;;  !KL L;; r*)rr+r,r-rFr/r{rrLrBrOrRr[r_rergrarmrrr\rirr*r(rr\s'FP>B!$DT$>@%%   ****++(++ & ++**($ "  r*N)- functoolsrsympy.core.basicrsympy.matrices.immutablersympy.matrices.denserrr sympy.core.containersr sympy.physics.mechanics.actuatorr !sympy.physics.mechanics.body_baser !sympy.physics.mechanics.functionsrrrsympy.physics.mechanics.jointrsympy.physics.mechanics.kaner sympy.physics.mechanics.lagrangersympy.physics.mechanics.loadsrrsympy.physics.mechanics.methodr sympy.physics.mechanics.particlersympy.physics.vectorrrrsympy.utilities.iterablesrsympy.utilities.miscr__all__r+rrrr*r(rso"433,96<</4<>35FF.+ X &v.Xv.r!uur*