
    EdH                     R    d dl mZmZmZ d dlmZ d dlmZ dgZ G d d          Z	dS )    )eyeMatrixzeros)dynamicsymbols)find_dynamicsymbolsSymbolicSystemc            	       F   e Zd ZdZddddi ddddf	dZed             Zed             Zed             Zed             Z	ed             Z
ed	             Zed
             Zed             Zd Zed             Zed             Zd Zd Zed             Ze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                 |   |mt                    | _        |d| _        n"fd|D             }t          |          | _        |	d| _        nofd|	D             }t          |          | _        nLt                    | _        t          |          | _        | j                            | j                  | _        +| _        || _        || _        d| _        d| _	        d| _
        nW|+d| _        d| _        d| _        || _        || _	        d| _
        n*d| _        d| _        d| _        d| _        d| _	        || _
        |fd|D             }|| _        || _        t          |
t                    s|
t          |
          }
t          |t                    s|t          |          }|
| _        || _        dS )z#Initializes a SymbolicSystem objectNc                      g | ]
}|         S  r   .0icoord_statess     >lib/python3.11/site-packages/sympy/physics/mechanics/system.py
<listcomp>z+SymbolicSystem.__init__.<locals>.<listcomp>   s    >>>a,q/>>>    c                      g | ]
}|         S r   r   r   s     r   r   z+SymbolicSystem.__init__.<locals>.<listcomp>   s    DDDAQDDDr   c                 4    g | ]}|t                    z   S r   )len)r   r   coordinate_derivativess     r   r   z+SymbolicSystem.__init__.<locals>.<listcomp>  s'    HHH1q35666HHHr   )r   _states_coordinates_speedscol_join_kin_explicit_rhs_dyn_implicit_rhs_dyn_implicit_mat_comb_implicit_rhs_comb_implicit_mat_comb_explicit_rhs_alg_conoutput_eqns
isinstancetuple_bodies_loads)selfr   right_hand_sidespeedsmass_matrixr   alg_conr#   
coord_idxs
speed_idxsbodiesloadscoordsspeeds_inters    `   `        r   __init__zSymbolicSystem.__init__   s
     	D!,//DL 3$(!!>>>>:>>>$*6NN! 4#DDDDDDD%l33 &| 4 4D!&>>DL,55dlCCDL " 	6%;D"%4D"%0D"&*D#&*D#&*D## 	6%)D"%)D"%)D"&5D#&1D#&*D##%)D"%)D"%)D"&*D#&*D#&5D#  	I#9 	IHHHHHHHG& &%(( 	#V 	#6]]F%'' 	!E 	!%LLEr   c                 <    | j         t          d          | j         S )z8Returns the column matrix of the generalized coordinatesNz#The coordinates were not specified.)r   AttributeErrorr(   s    r   coordinateszSymbolicSystem.coordinates  s'      	% !FGGG$$r   c                 <    | j         t          d          | j         S )z/Returns the column matrix of generalized speedsNzThe speeds were not specified.)r   r5   r6   s    r   r*   zSymbolicSystem.speeds  s%     < 	  !ABBB<r   c                     | j         S )z0Returns the column matrix of the state variables)r   r6   s    r   stateszSymbolicSystem.states!  s     |r   c                     | j         S )zReturns a list with the indices of the rows containing algebraic
        constraints in the combined form of the equations of motion)r"   r6   s    r   r,   zSymbolicSystem.alg_con&  s     }r   c                 <    | j         t          d          | j         S )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   r5   r6   s    r   dyn_implicit_matzSymbolicSystem.dyn_implicit_mat,  5    
 ! 	*  "H I I I ))r   c                 <    | j         t          d          | j         S )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   r5   r6   s    r   dyn_implicit_rhszSymbolicSystem.dyn_implicit_rhs7  r>   r   c                    | j         | j        t          | 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_joinr   r5   )r(   num_kin_eqnsnum_dyn_eqnszeros1zeros2inter1inter2s          r   comb_implicit_matz SymbolicSystem.comb_implicit_matB  s    
 " 	+% F"4#9::"4#9::|\::|\::\**33F;;)?@@*0//&*A*A'..$ &E F F F **r   c                     | j         E| j        /| 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   r   r5   )r(   	kin_inter	dyn_inters      r   comb_implicit_rhsz SymbolicSystem.comb_implicit_rhsW  sp    
 " 
	+% I 2	 2	*3*<*<Y*G*G'..$ &H I I I **r   c                    | j         t          d          t          | dd          }|5| 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!   r5   getattrr   LUsolver   r   r    r   )r(   rG   rH   outs       r   compute_explicit_formz$SymbolicSystem.compute_explicit_formh  s     " 	I !GHHH1488 	K+33D4JKKF//&))CC)11$2IJJC"%r   c                 <    | j         t          d          | j         S )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!   r5   r6   s    r   comb_explicit_rhsz SymbolicSystem.comb_explicit_rhsx  s5     " 	+  "K L L L **r   c                 <    | j         t          d          | j         S )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   r5   r6   s    r   rO   zSymbolicSystem.kin_explicit_rhs  s5     ! 	*  "H I I I ))r   c                 *   | j          | j        dd         | j        dd         z   }n| j         dd         }t                      }|D ]$}|                    t          |                    }%|                    | j                  }t          |          S )z_Returns a column matrix containing all of the symbols in the system
        that depend on timeN)r!   rI   rM   setunionr   r   r%   )r(   eom_expressionsfunctions_of_timeexprs       r   dynamic_symbolszSymbolicSystem.dynamic_symbols  s     " 	;#5aaa8#5aaa8 9OO  $6qqq9OEE# 	+ 	+D 1 7 7#D))!+ !+-33DLAA&'''r   c                 $   | j          | j        dd         | j        dd         z   }n| j         dd         }t                      }|D ]}|                    |j                  }|                    t          j                   t          |          S )zfReturns a column matrix containing all of the symbols in the system
        that do not depend on timeN)
r!   rI   rM   rX   rY   free_symbolsremover   _tr%   )r(   rZ   	constantsr\   s       r   constant_symbolszSymbolicSystem.constant_symbols  s     " 	;#5aaa8#5aaa8 9OO  $6qqq9OEE	# 	; 	;D!(9::II*+++Yr   c                 <    | j         t          d          | j         S )z Returns the bodies in the systemNz)bodies were not specified for the system.)r&   r5   r6   s    r   r/   zSymbolicSystem.bodies  s%     < 	  !LMMM<r   c                 <    | j         t          d          | j         S )zReturns the loads in the systemNz(loads were not specified for the system.)r'   r5   r6   s    r   r0   zSymbolicSystem.loads  s%     ; 	 !KLLL;r   )__name__
__module____qualname____doc__r3   propertyr7   r*   r:   r,   r=   r@   rI   rM   rS   rU   rO   r]   rc   r/   r0   r   r   r   r   r      s       F FP >B!$DT$> > > >@ % % X%     X    X   X
 * * X* * * X* + + X+( + + X+ & & &  + + X+ * * X*( ( ($     "     X    X  r   N)
sympy.core.backendr   r   r   sympy.physics.mechanicsr   !sympy.physics.mechanics.functionsr   __all__r   r   r   r   <module>ro      s    1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 A A A A A A
u u u u u u u u u ur   