o
    ohA                     @   s  d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZmZ d dlmZ d dlm Z  d dl!m"Z"m#Z#m$Z$ d dl%m&Z& d dl'm(Z( ddgZ)dd Z*G dd deZ+G dd dZ,dS )    wraps)Basic)ImmutableMatrix)Matrixeyezeros
OrderedSet)ActuatorBase)BodyBase)
Lagrangian_validate_coordinatesfind_dynamicsymbols)Joint)KanesMethod)LagrangesMethod)_parse_loadgravity)_Methods)Particle)PointReferenceFramedynamicsymbols)iterable)
filldedentSymbolicSystemSystemc                    s   t   fdd}|S )z;Decorator to reset the eom_method if a property is changed.c                    s   d | _  | g|R i |S N_eom_method)selfargskwargsmethod r/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/sympy/physics/mechanics/system.pywrapper   s   z"_reset_eom_method.<locals>.wrapperr   )r%   r(   r&   r$   r'   _reset_eom_method   s   r)   c                   @   s<  e Zd ZdZdtddZedd Zedd Zed	d
 Z	edd Z
edd Zedd Zedd Zejedd Zedd Zejedd Zedd Zejedd Zedd Zejedd Zedd Zedd  Zed!d" Zejed#d" Zed$d% Zejed&d% Zed'd( Zejed)d( Zed*d+ Zejed,d+ Zed-d. Zejed/d. Zed0d1 Zejed2d1 Zed3d4 Zejed5d4 Zed6d7 Zejed8d7 Zed9d: Zejed;d: Zed<d= Zed>d? Z ed@dA Z!	BdudCdDZ"e	EdvdFdGZ#edHdIdJdKZ$edHdIdLdMZ%edNdO Z&edPdQ Z'edRdS Z(edTdU Z)edVdW Z*edXdY Z+edZd[ Z,ed\d] Z-ed^d_ Z.d`da Z/dbdc Z0ddde Z1e2fdfdgZ3dwdhdiZ4edjdk Z5edldm Z6edndo Z7edpdq Z8e2dEfdrdsZ9dS )xr   aV  Class 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                 C   s  |du r	t d}n	t|t std|| _|du rtd}n	t|ts'td|| _| j| jd tddg j| _	tddg j| _
tddg j| _tddg j| _tddg j| _tddg j| _tddg j| _tddg j| _d| _g | _g | _g | _g | _d| _dS )a  Initialize 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.

        Ninertial_framez,Frame must be an instance of ReferenceFrame.inertial_pointz)Fixed point must be an instance of Point.r      )r   
isinstance	TypeError_framer   _fixed_pointset_velr   T_q_ind_q_dep_u_ind_u_dep_u_aux_kdes_hol_coneqs_nonhol_coneqs_vel_constrs_bodies_joints_loads
_actuatorsr    )r!   framefixed_pointr&   r&   r'   __init__   s2   




zSystem.__init__c                 C   s0   t |tr	td| |j|jd}|| |S )z7Constructs the system with respect to a Newtonian body.z7A Particle has no frame so cannot act as the Newtonian.)r@   rA   )r-   r   r.   r@   
masscenter
add_bodies)cls	newtoniansystemr&   r&   r'   from_newtonian  s
   

zSystem.from_newtonianc                 C      | j S )z,Fixed point in the inertial reference frame.)r0   r!   r&   r&   r'   rA        zSystem.fixed_pointc                 C   rI   )z'Inertial reference frame of the system.)r/   rJ   r&   r&   r'   r@   !  rK   zSystem.framec                 C      | j jS z2Unit vector fixed in the inertial reference frame.)r/   xrJ   r&   r&   r'   rN   &     zSystem.xc                 C   rL   rM   )r/   yrJ   r&   r&   r'   rP   +  rO   zSystem.yc                 C   rL   rM   )r/   zrJ   r&   r&   r'   rQ   0  rO   zSystem.zc                 C   
   t | jS )z7Tuple of all bodies that have been added to the system.)tupler<   rJ   r&   r&   r'   bodies5     
zSystem.bodiesc                 C   &   |  |}| |g tdd || _d S )NBodiesrT   )_objects_to_list_check_objectsr   r<   r!   rT   r&   r&   r'   rT   :  s   

c                 C   rR   )z7Tuple of all joints that have been added to the system.)rS   r=   rJ   r&   r&   r'   jointsA  rU   zSystem.jointsc                 C   s0   |  |}| |g tdd g | _| j|  d S )NJointsr[   )rX   rY   r   r=   
add_joints)r!   r[   r&   r&   r'   r[   F  s   
c                 C   rR   )z4Tuple of loads that have been applied on the system.)rS   r>   rJ   r&   r&   r'   loadsN  rU   zSystem.loadsc                 C   s   |  |}dd |D | _d S )Nc                 S      g | ]}t |qS r&   r   .0loadr&   r&   r'   
<listcomp>W      z System.loads.<locals>.<listcomp>)rX   r>   r!   r^   r&   r&   r'   r^   S  s   
c                 C   rR   )z)Tuple of actuators present in the system.)rS   r?   rJ   r&   r&   r'   	actuatorsY  rU   zSystem.actuatorsc                 C   rV   )N	Actuatorsrg   )rX   rY   r   r?   r!   rg   r&   r&   r'   rg   ^  s
   

c                 C      | j | jS )zbMatrix of all the generalized coordinates with the independent
        stacked upon the dependent.)r3   col_joinr4   rJ   r&   r&   r'   qf     zSystem.qc                 C   rj   )z]Matrix of all the generalized speeds with the independent stacked
        upon the dependent.)r5   rk   r6   rJ   r&   r&   r'   ul  rm   zSystem.uc                 C   rI   )z2Matrix of the independent generalized coordinates.)r3   rJ   r&   r&   r'   q_indr  rK   zSystem.q_indc                 C   &   |  | |dg | jd\| _| _d S )NTcoordinates)_parse_coordinatesrX   q_depr3   r4   )r!   ro   r&   r&   r'   ro   w     c                 C   rI   )z0Matrix of the dependent generalized coordinates.)r4   rJ   r&   r&   r'   rs   }  rK   zSystem.q_depc                 C   &   |  | |d| jg d\| _| _d S )NFrq   )rr   rX   ro   r3   r4   )r!   rs   r&   r&   r'   rs     rt   c                 C   rI   )z-Matrix of the independent generalized speeds.)r5   rJ   r&   r&   r'   u_ind  rK   zSystem.u_indc                 C   rp   )NTspeeds)rr   rX   u_depr5   r6   )r!   rv   r&   r&   r'   rv     rt   c                 C   rI   )z+Matrix of the dependent generalized speeds.)r6   rJ   r&   r&   r'   rx     rK   zSystem.u_depc                 C   ru   )NFrw   )rr   rX   rv   r5   r6   )r!   rx   r&   r&   r'   rx     rt   c                 C   rI   )z'Matrix of auxiliary generalized speeds.)r7   rJ   r&   r&   r'   u_aux  rK   zSystem.u_auxc                 C   s"   |  | |dg g dd | _d S )NTu_auxiliaryr   )rr   rX   r7   )r!   ry   r&   r&   r'   ry     s
   
c                 C   rI   )zKinematical differential equations as expressions equated to the zero
        matrix. These equations describe the coupling between the generalized
        coordinates and the generalized speeds.)r8   rJ   r&   r&   r'   kdes  s   zSystem.kdesc                 C      |  |}| |g d| _d S )N kinematic differential equations)rX   _parse_expressionsr8   r!   r{   r&   r&   r'   r{        

c                 C   rI   )zXMatrix with the holonomic constraints as expressions equated to the
        zero matrix.)r9   rJ   r&   r&   r'   holonomic_constraints     zSystem.holonomic_constraintsc                 C   r|   )Nholonomic constraints)rX   r~   r9   r!   constraintsr&   r&   r'   r     r   c                 C   rI   )z[Matrix with the nonholonomic constraints as expressions equated to
        the zero matrix.)r:   rJ   r&   r&   r'   nonholonomic_constraints  r   zSystem.nonholonomic_constraintsc                 C   r|   )Nnonholonomic constraints)rX   r~   r:   r   r&   r&   r'   r     r   c                 C   s&   | j du r| jtj| jS | j S )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.
        N)r;   r   diffr   _trk   r   rJ   r&   r&   r'   velocity_constraints  s
   
zSystem.velocity_constraintsc                 C   s0   |d u r	d | _ d S | |}| |g d| _ d S )Nzvelocity constraints)r;   rX   r~   r   r&   r&   r'   r     s   

c                 C   rI   )z,Backend for forming the equations of motion.r   rJ   r&   r&   r'   
eom_method  rK   zSystem.eom_methodc                 C   s   t | s| gS t| dd S )z+Helper to convert passed objects to a list.N)r   list)lstr&   r&   r'   rX     s   zSystem._objects_to_listc           	      C   s   t |}t  }t  }| D ]}t||s|| ||v r"|| q|| q|r7t| d| d| d|rCt| d| ddS )a  Helper 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)setr-   addr.   
ValueError)	objectsobj_lstexpected_typeobj_name	type_nameseen
duplicateswrong_typesobjr&   r&   r'   rY     s   

zSystem._check_objectsrq   c              	   C   s   |dd |dd }}t |s|gt| }t||D ]\}}	|	r)|| q|| qd| jdd | jdd  d| jdd | jdd  d| jdd ||| i}
t	di |
 t
dt||jt
dt||jfS )z'Helper to parse coordinates and speeds.Nrq   rw   rz   r,   r&   )r   lenzipappendro   rs   rv   rx   r7   r   r   r2   )r!   
new_coordsindependentold_coords_indold_coords_dep
coord_type
coords_ind
coords_depcoordindepcurrentr&   r&   r'   rr     s    zSystem._parse_coordinatesFc                 C   s   |dd }t | } |r|dd |D  }n|}t| |t|d | D ]}|dkr1td| dq#tdt|t|  ||  jS )	z-Helper to parse expressions like constraints.Nc                 S   s   g | ]}| qS r&   r&   )rb   exprr&   r&   r'   rd   9  s    z-System._parse_expressions.<locals>.<listcomp>expressionsr   zParsed z
 are zero.r,   )r   r   rY   r   r   r   r   r2   )new_expressionsold_expressionsnamecheck_negativescheck_exprsr   r&   r&   r'   r~   2  s"   zSystem._parse_expressionsT)r   c                G   "   |  ||| j| jd\| _| _dS )a  Add 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.

        rq   N)rr   ro   rs   r3   r4   )r!   r   rq   r&   r&   r'   add_coordinatesD  s   zSystem.add_coordinatesc                G   r   )a  Add 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.

        rw   N)rr   rv   rx   r5   r6   )r!   r   rw   r&   r&   r'   
add_speedsV  s   zSystem.add_speedsc                 G   s   |  |d| jg dd | _dS )zAdd auxiliary speed(s) to the system.

        Parameters
        ==========

        *speeds : dynamicsymbols
            One or more auxiliary speeds to be added to the system.

        Trz   r   N)rr   r7   )r!   rw   r&   r&   r'   add_auxiliary_speedsg  s
   
zSystem.add_auxiliary_speedsc                 G   s   | j || jddd| _dS )zAdd kinematic differential equation(s) to the system.

        Parameters
        ==========

        *kdes : Expr
            One or more kinematic differential equations.

        r}   Tr   N)r~   r{   r8   r   r&   r&   r'   add_kdesu  s   zSystem.add_kdesc                 G      | j || jddd| _dS )zAdd holonomic constraint(s) to the system.

        Parameters
        ==========

        *constraints : Expr
            One or more holonomic constraints, which are expressions that should
            be zero.

        r   Tr   N)r~   r9   r   r&   r&   r'   add_holonomic_constraints     z System.add_holonomic_constraintsc                 G   r   )zAdd nonholonomic constraint(s) to the system.

        Parameters
        ==========

        *constraints : Expr
            One or more nonholonomic constraints, which are expressions that
            should be zero.

        r   Tr   N)r~   r:   r   r&   r&   r'   add_nonholonomic_constraints  r   z#System.add_nonholonomic_constraintsc                 G   $   |  || jtdd | j| dS )zAdd body(ies) to the system.

        Parameters
        ==========

        bodies : Particle or RigidBody
            One or more bodies.

        rW   rT   N)rY   rT   r   r<   extendrZ   r&   r&   r'   rD     s   zSystem.add_bodiesc                 G   s   dd |D }| j | dS )zAdd load(s) to the system.

        Parameters
        ==========

        *loads : Force or Torque
            One or more loads.

        c                 S   r_   r&   r`   ra   r&   r&   r'   rd     re   z$System.add_loads.<locals>.<listcomp>N)r>   r   rf   r&   r&   r'   	add_loads  s   zSystem.add_loadsc                 C   s   | j t|g| jR    dS )zApply uniform gravity to all bodies in the system by adding loads.

        Parameters
        ==========

        acceleration : Vector
            The acceleration due to gravity.

        N)r   r   rT   )r!   accelerationr&   r&   r'   apply_uniform_gravity  s   zSystem.apply_uniform_gravityc                 G   r   )zAdd actuator(s) to the system.

        Parameters
        ==========

        *actuators : subclass of ActuatorBase
            One or more actuators.

        rh   rg   N)rY   rg   r   r?   r   ri   r&   r&   r'   add_actuators  s   zSystem.add_actuatorsc                 G   s  |  || jtdd | j| dd tdD \}}}}|D ]}||j ||j ||j	 ||j
|jf q|| j}|| j}|| j	dd | j	 dd  }|| j}| jt|  | jt|  | jdd t|D   | jt|  dS )a  Add joint(s) to the system.

        Explanation
        ===========

        This methods adds one or more joints to the system including its
        associated objects, i.e. generalized coordinates, generalized speeds,
        kinematic differential equations and the bodies.

        Parameters
        ==========

        *joints : subclass of Joint
            One or more joints.

        Notes
        =====

        For the generalized coordinates, generalized speeds and bodies it is
        checked whether they are already known by the system instance. If they
        are, then they are not added. The kinematic differential equations are
        however always added to the system, so you should not also manually add
        those on beforehand.

        r\   r[   c                 s   s    | ]}t  V  qd S r   r	   )rb   _r&   r&   r'   	<genexpr>  s    z$System.add_joints.<locals>.<genexpr>   Nc                 s   s    | ]	}|d ks|V  qdS )r   Nr&   )rb   kder&   r&   r'   r     s    )rY   r[   r   r=   r   rangeupdaterq   rw   r{   parentchild
differencerl   rn   rT   r   rS   r   r   rD   )r!   r[   rq   rw   r{   rT   jointr&   r&   r'   r]     s    $zSystem.add_jointsc                 C   "   | j D ]}|j|kr|  S qdS )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!   r   bodyr&   r&   r'   get_body  
   

zSystem.get_bodyc                 C   r   )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)r=   r   )r!   r   r   r&   r&   r'   	get_joint  r   zSystem.get_jointc                 C   s   |   S r   )	form_eomsrJ   r&   r&   r'   
_form_eoms0  s   zSystem._form_eomsc                 K   sL  | j tdd | jD  }|r|nd}t|trSh d}||}|r/td|j d| d| j| j	| j
| j| j| j| j| j| j|| jdd	|}|di || _nNt|trh d
}||}|rotd|j d| d| j| j|| j| j| jd|}d|vrt|d g|d R  |d< |di || _nt| d| j S )a  Form 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]])

        c                 s   s"    | ]}|  D ]}|V  qqd S r   )to_loads)rb   actrc   r&   r&   r'   r   b  s    z#System.form_eoms.<locals>.<genexpr>N>   r@   ro   rv   rT   kd_eqs	forcelistq_dependentrz   u_dependentr   configuration_constraintszEThe following keyword arguments are not allowed to be overwritten in z: r   F)r@   ro   rv   r   r   r   r   r   rz   r   rT   explicit_kinematics>   qsr@   rT   r   r   
hol_coneqsnonhol_coneqs)r@   r   r   rT   r   r   r   r@   rT    has not been implemented.r&   )r^   rS   rg   
issubclassr   intersectionr   __name__r@   ro   rv   r{   rs   rx   r   r   ry   rT   r    r   rl   r   r   NotImplementedErrorr   r   )r!   r   r#   r^   disallowed_kwargswrong_kwargsr&   r&   r'   r   3  sh   /







zSystem.form_eomsc                 C   s   | j j|dS )a  Compute 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)r   rhs)r!   r   r&   r&   r'   r     s   z
System.rhsc                 C   rL   )ab  The 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_matrixrJ   r&   r&   r'   r     s   zSystem.mass_matrixc                 C   rL   )a  The 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$.

        )r   mass_matrix_fullrJ   r&   r&   r'   r     s   zSystem.mass_matrix_fullc                 C   rL   )z!The forcing vector of the system.)r   forcingrJ   r&   r&   r'   r     rO   zSystem.forcingc                 C   rL   )zyThe forcing vector of the system, augmented by the kinematic
        differential equations in explicit or implicit form.)r   forcing_fullrJ   r&   r&   r'   r     s   zSystem.forcing_fullc              	      s  g }| j jd }| jjd }| jjd | jjd }}t| jt| j}}	t|t|	}
}||krA|	t
d| d| d t }| jD ]}|t|j| qG|rb|	t
d| d t|trt| j}t t }}| jD ]%}|t|j|	 |t|j| jdd | j dd   qv|r|	t
d| d	 |r|	t
d
| d ||kr|	t
d| d| d |
|kr|	t
d|
 d| d ||kr|	t
d| d| d nPt|tr6t| j| jtj}| jD ]}|t|j| jtj q|r%|	t
d| d | jr5|	t
d| j d nt| d|r{d| jfd| jfd| jfd| jfd| jfg}|D ]"\}}t   fdd|D }|ry|	t
d| d| d qX|rtd|dS ) a  Validates 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.

        r   z=
            The number of dependent generalized coordinates zD should be
            equal to the number of holonomic constraints r   z)
            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 r   zgeneralized coordinateszgeneralized speedszauxiliary speedsrT   r[   c                    s"   h | ]}| v s  |r|qS r&   )r   )rb   rN   r   r&   r'   	<setcomp>S  s   " z)System.validate_system.<locals>.<setcomp>z
                    The r   z< exist multiple times within the
                    system.
)r   shaper   rs   rx   r   rl   rn   r   r   r   r[   r   rq   r   r   r   r{   rw   r   r   r   r   ry   r   rT   r   join)r!   r   check_duplicatesmsgsn_hcn_vcn_q_depn_u_depq_setu_setn_qn_u	missing_qr   n_kdesmissing_kdes	missing_u	not_qdotsduplicates_to_checkr   r   r   r&   r   r'   validate_system  s   /




zSystem.validate_system)NN)rq   )Fr   ):r   
__module____qualname____doc__rB   classmethodrH   propertyrA   r@   rN   rP   rQ   rT   setterr)   r[   r^   rg   rl   rn   ro   rs   rv   rx   ry   r{   r   r   r   r   staticmethodrX   rY   rr   r~   r   r   r   r   r   r   rD   r   r   r   r]   r   r   r   r   r   r   r   r   r   r   r   r&   r&   r&   r'   r   #   s    
G(
	























+









+
Z



c                	   @   s   e Zd ZdZddddi ddddf	ddZedd Zedd Zed	d
 Zedd Z	edd Z
edd Zedd Zedd Zdd Zedd Zedd Zdd Zdd Zedd  Zed!d" ZdS )#r   aB"  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                    s  |du r6t  | _|du rd| _n fdd|D }t || _|	du r'd| _n! fdd|	D }t || _nt  | _t || _| j| j| _dur_| _|| _|| _d| _d| _	d| _
n)|durvd| _d| _d| _|| _|| _	d| _
nd| _d| _d| _d| _d| _	|| _
|durdurfdd|D }|| _|| _t|
ts|
durt|
}
t|ts|durt|}|
| _|| _dS )z#Initializes a SymbolicSystem objectNc                       g | ]} | qS r&   r&   rb   icoord_statesr&   r'   rd   2  re   z+SymbolicSystem.__init__.<locals>.<listcomp>c                    r  r&   r&   r  r	  r&   r'   rd   8  re   c                    s   g | ]}|t   qS r&   )r   r  )coordinate_derivativesr&   r'   rd   X  s    )r   _states_coordinates_speedsrk   _kin_explicit_rhs_dyn_implicit_rhs_dyn_implicit_mat_comb_implicit_rhs_comb_implicit_mat_comb_explicit_rhs_alg_conoutput_eqnsr-   rS   r<   r>   )r!   r
  right_hand_siderw   r   r  alg_conr  
coord_idxs
speed_idxsrT   r^   coordsspeeds_interr&   )r
  r  r'   rB   %  sV   




zSymbolicSystem.__init__c                 C      | j du r	td| j S )z8Returns the column matrix of the generalized coordinatesNz#The coordinates were not specified.)r  AttributeErrorrJ   r&   r&   r'   rq   e     
zSymbolicSystem.coordinatesc                 C   r  )z/Returns the column matrix of generalized speedsNzThe speeds were not specified.)r  r  rJ   r&   r&   r'   rw   m  r  zSymbolicSystem.speedsc                 C   rI   )z0Returns the column matrix of the state variables)r  rJ   r&   r&   r'   statesu  rK   zSymbolicSystem.statesc                 C   rI   )zReturns a list with the indices of the rows containing algebraic
        constraints in the combined form of the equations of motion)r  rJ   r&   r&   r'   r  z  r   zSymbolicSystem.alg_conc                 C   r  )zReturns the matrix, M, corresponding to the dynamic equations in
        implicit form, M x' = F, where the kinematical equations are not
        includedNzJdyn_implicit_mat is not specified for equations of motion form [1] or [2].)r  r  rJ   r&   r&   r'   dyn_implicit_mat     
zSymbolicSystem.dyn_implicit_matc                 C   r  )zReturns the column matrix, F, corresponding to the dynamic equations
        in implicit form, M x' = F, where the kinematical equations are not
        includedNzJdyn_implicit_rhs is not specified for equations of motion form [1] or [2].)r  r  rJ   r&   r&   r'   dyn_implicit_rhs  r"  zSymbolicSystem.dyn_implicit_rhsc                 C   sv   | j du r8| jdur4t| j}t| j}t||}t||}t||}|| j}||| _ | j S t	d| j S )zReturns the matrix, M, corresponding to the equations of motion in
        implicit form (form [2]), M x' = F, where the kinematical equations are
        includedNzDcomb_implicit_mat is not specified for equations of motion form [1].)
r  r  r   r  r  r   r   row_joinrk   r  )r!   num_kin_eqnsnum_dyn_eqnszeros1zeros2inter1inter2r&   r&   r'   comb_implicit_mat  s   





z SymbolicSystem.comb_implicit_matc                 C   s@   | j du r| jdur| j}| j}||| _ | j S td| j S )zReturns the column matrix, F, corresponding to the equations of
        motion in implicit form (form [2]), M x' = F, where the kinematical
        equations are includedNzGcomb_implicit_mat is not specified for equations of motion in form [1].)r  r  r  rk   r  )r!   	kin_inter	dyn_interr&   r&   r'   comb_implicit_rhs  s   

z SymbolicSystem.comb_implicit_rhsc                 C   sX   | j dur	tdt| dd}|dur | j| j}||}n| j| j}|| _ dS )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  r  getattrr  LUsolver  rk   r  r  )r!   r)  r*  outr&   r&   r'   compute_explicit_form  s   

z$SymbolicSystem.compute_explicit_formc                 C   r  )zReturns the right hand side of the equations of motion in explicit
        form, x' = F, where the kinematical equations are includedNzPPlease run .combute_explicit_form before attempting to access comb_explicit_rhs.)r  r  rJ   r&   r&   r'   comb_explicit_rhs     
z SymbolicSystem.comb_explicit_rhsc                 C   r  )zYReturns the right hand side of the kinematical equations in explicit
        form, q' = GNzJkin_explicit_rhs is not specified for equations of motion form [1] or [2].)r  r  rJ   r&   r&   r'   r/    r5  zSymbolicSystem.kin_explicit_rhsc                 C   sh   | j du r| jdd | jdd  }n| j dd }t }|D ]	}|t|}q || j}t|S )z_Returns a column matrix containing all of the symbols in the system
        that depend on timeN)r  r+  r.  r   unionr   r  rS   )r!   eom_expressionsfunctions_of_timer   r&   r&   r'   dynamic_symbols  s   
zSymbolicSystem.dynamic_symbolsc                 C   sf   | j du r| jdd | jdd  }n| j dd }t }|D ]}||j}q |tj t	|S )zfReturns a column matrix containing all of the symbols in the system
        that do not depend on timeN)
r  r+  r.  r   r6  free_symbolsremover   r   rS   )r!   r7  	constantsr   r&   r&   r'   constant_symbols  s   
zSymbolicSystem.constant_symbolsc                 C   r  )z Returns the bodies in the systemNz)bodies were not specified for the system.)r<   r  rJ   r&   r&   r'   rT     r  zSymbolicSystem.bodiesc                 C   r  )zReturns the loads in the systemNz(loads were not specified for the system.)r>   r  rJ   r&   r&   r'   r^     r  zSymbolicSystem.loads)r   r   r   r  rB   r  rq   rw   r   r  r!  r#  r+  r.  r3  r4  r/  r9  r=  rT   r^   r&   r&   r&   r'   r   \  sF     I
@










	
	
N)-	functoolsr   sympy.core.basicr   sympy.matrices.immutabler   sympy.matrices.denser   r   r   sympy.core.containersr
    sympy.physics.mechanics.actuatorr   !sympy.physics.mechanics.body_baser   !sympy.physics.mechanics.functionsr   r   r   sympy.physics.mechanics.jointr   sympy.physics.mechanics.kaner    sympy.physics.mechanics.lagranger   sympy.physics.mechanics.loadsr   r   sympy.physics.mechanics.methodr    sympy.physics.mechanics.particler   sympy.physics.vectorr   r   r   sympy.utilities.iterablesr   sympy.utilities.miscr   __all__r)   r   r   r&   r&   r&   r'   <module>   s:            A