o
    ohN                     @   s   d dl mZmZmZmZmZ d dlmZ d dlm	Z	m
Z
 d dlmZ d dlmZmZmZmZ d dlmZ d dlmZ dgZG d	d deZd
S )    )diffzerosMatrixeyesympify)default_sort_key)dynamicsymbolsReferenceFrame)_Methods)find_dynamicsymbolsmsubs_f_list_parser_validate_coordinates)
Linearizer)iterableLagrangesMethodc                   @   s   e Zd ZdZ		d%ddZdd Zdd Zed	d
 Zedd Z	edd Z
edd Z		d&ddZ		d&ddZd'ddZd(ddZedd Zedd Zedd  Zed!d" Zed#d$ ZdS ))r   a  Lagrange's method object.

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

    This object generates the equations of motion in a two step procedure. The
    first step involves the initialization of LagrangesMethod by supplying the
    Lagrangian and the generalized coordinates, at the bare minimum. If there
    are any constraint equations, they can be supplied as keyword arguments.
    The Lagrange multipliers are automatically generated and are equal in
    number to the constraint equations. Similarly any non-conservative forces
    can be supplied in an iterable (as described below and also shown in the
    example) along with a ReferenceFrame. This is also discussed further in the
    __init__ method.

    Attributes
    ==========

    q, u : Matrix
        Matrices of the generalized coordinates and speeds
    loads : iterable
        Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
        describing the forces on the system.
    bodies : iterable
        Iterable containing the rigid bodies and particles of the system.
    mass_matrix : Matrix
        The system's mass matrix
    forcing : Matrix
        The system's forcing vector
    mass_matrix_full : Matrix
        The "mass matrix" for the qdot's, qdoubledot's, and the
        lagrange multipliers (lam)
    forcing_full : Matrix
        The forcing vector for the qdot's, qdoubledot's and
        lagrange multipliers (lam)

    Examples
    ========

    This is a simple example for a one degree of freedom translational
    spring-mass-damper.

    In this example, we first need to do the kinematics.
    This involves creating generalized coordinates and their derivatives.
    Then we create a point and set its velocity in a frame.

        >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian
        >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point
        >>> from sympy.physics.mechanics import dynamicsymbols
        >>> from sympy import symbols
        >>> q = dynamicsymbols('q')
        >>> qd = dynamicsymbols('q', 1)
        >>> m, k, b = symbols('m k b')
        >>> N = ReferenceFrame('N')
        >>> P = Point('P')
        >>> P.set_vel(N, qd * N.x)

    We need to then prepare the information as required by LagrangesMethod to
    generate equations of motion.
    First we create the Particle, which has a point attached to it.
    Following this the lagrangian is created from the kinetic and potential
    energies.
    Then, an iterable of nonconservative forces/torques must be constructed,
    where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple,
    with the Vectors representing the nonconservative forces or torques.

        >>> Pa = Particle('Pa', P, m)
        >>> Pa.potential_energy = k * q**2 / 2.0
        >>> L = Lagrangian(N, Pa)
        >>> fl = [(P, -b * qd * N.x)]

    Finally we can generate the equations of motion.
    First we create the LagrangesMethod object. To do this one must supply
    the Lagrangian, and the generalized coordinates. The constraint equations,
    the forcelist, and the inertial frame may also be provided, if relevant.
    Next we generate Lagrange's equations of motion, such that:
    Lagrange's equations of motion = 0.
    We have the equations of motion at this point.

        >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N)
        >>> print(l.form_lagranges_equations())
        Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]])

    We can also solve for the states using the 'rhs' method.

        >>> print(l.rhs())
        Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]])

    Please refer to the docstrings on each method for more details.
    Nc           	      C   s&  t t|g| _d| _t  | _t  | _t  | _t  | _t  | _|r#|ng }t	|s-t
d|| _|r;t|ts;t
d|| _|| _t  | _t  | _t  | _t  | _t  | _t	|s]t
dt || _| jtj| _| jtj| _t| j dd }||}||}t |tj|g| _|| _dS )a  Supply the following for the initialization of LagrangesMethod.

        Lagrangian : Sympifyable

        qs : array_like
            The generalized coordinates

        hol_coneqs : array_like, optional
            The holonomic constraint equations

        nonhol_coneqs : array_like, optional
            The nonholonomic constraint equations

        forcelist : iterable, optional
            Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector)
            tuples which represent the force at a point or torque on a frame.
            This feature is primarily to account for the nonconservative forces
            and/or moments.

        bodies : iterable, optional
            Takes an iterable containing the rigid bodies and particles of the
            system.

        frame : ReferenceFrame, optional
            Supply the inertial frame. This is used to determine the
            generalized forces due to non-conservative forces.
        Nz,Force pairs must be supplied in an iterable.z$frame must be a valid ReferenceFramez+Generalized coordinates must be an iterablec                 S      | rt | S t  S Nr   x r   t/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/sympy/physics/mechanics/lagrange.py<lambda>       z*LagrangesMethod.__init__.<locals>.<lambda>)r   r   _Leom_m_cd_m_d_f_cd_f_d
lam_coeffsr   	TypeError
_forcelist
isinstancer	   _bodiesinertiallam_vec_term1_term2_term3_term4_qqr   r   _t_qdots_qdoubledotsr   coneqs_hol_coneqs)	self
Lagrangianqs	forcelistbodiesframe
hol_coneqsnonhol_coneqs	mat_buildr   r   r   __init__i   sB   


zLagrangesMethod.__init__c           
         sx  | j }t| jd}t| j}| j|| _| j	t
jj| _| j| jj| _| jrc| j}t|}tt
dt|d  | _|| | _| jj| j | _|	t
j}|| j| _|| | _nt|d| _| jr| j t|d| _t|D ]\}tt| j  }t fdd|D | j|< qynt|d| _| j| j | j }	|	| j| _|	| | _ |	| j | _!| j!S )zMethod to form Lagrange's equations of motion.

        Returns a vector of equations of motion using Lagrange's equations of
        the second kind.
        r   zlam1:   c                 3   s&    | ]\}}|  |V  qd S r   )r   dot).0vfNqdr   r   	<genexpr>   s   $ z;LagrangesMethod.form_lagranges_equations.<locals>.<genexpr>)"r/   dictfromkeysr0   lenr-   r   jacobianr(   r   r   r.   Tr)   r1   r   strr'   r!   r*   r   subsr   r   r6   r&   r+   	enumeratezipr   sumr   r    r   )
r3   qdsqdd_zeronr1   m
diffconeqsiflistwithout_lamr   rB   r   form_lagranges_equations   s:   
 z(LagrangesMethod.form_lagranges_equationsc                 C   s   |   S r   )rX   r3   r   r   r   
_form_eoms   s   zLagrangesMethod._form_eomsc                 C   s.   | j du r	td| jr| j| jjS | jS )a7  Returns the mass matrix, which is augmented by the Lagrange
        multipliers, if necessary.

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

        If the system is described by 'n' generalized coordinates and there are
        no constraint equations then an n X n matrix is returned.

        If there are 'n' generalized coordinates and 'm' constraint equations
        have been supplied during initialization then an n X (n+m) matrix is
        returned. The (n + m - 1)th and (n + m)th columns contain the
        coefficients of the Lagrange multipliers.
        N-Need to compute the equations of motion first)r   
ValueErrorr1   r   row_joinr!   rJ   rY   r   r   r   mass_matrix   s
   
zLagrangesMethod.mass_matrixc                 C   s   | j du r	tdt| j}t| j}t|t||| }t||| j}| jrBt||| j	t||}|
|
|S |
|S )z6Augments the coefficients of qdots to the mass_matrix.Nr[   )r   r\   rH   r-   r1   r   r]   r   r^   r   col_join)r3   rR   rS   row1row2row3r   r   r   mass_matrix_full  s   



z LagrangesMethod.mass_matrix_fullc                 C   s   | j du r	td| jS )z=Returns the forcing vector from 'lagranges_equations' method.Nr[   )r   r\   r    rY   r   r   r   forcing  s   
zLagrangesMethod.forcingc                 C   s<   | j du r	td| jr| j| j| jS | j| jS )z+Augments qdots to the forcing vector above.Nr[   )r   r\   r1   r/   r_   rd   r   rY   r   r   r   forcing_full  s
   
zLagrangesMethod.forcing_fullLUc                 C   sx  t j}| j}| j}||}	| j}
dd }||}||}||}||}| j}| j}||}|}| }| j}| j	| j
  }| j }t|t|ksSt|t|kr_tdt|t|tt||gt|krotdtt||gt|krtdtt|||	|
g}tt||}|jtd |D ]}t|t j|v rtdqt||||||||||||||||
|dS )	ak  Returns an instance of the Linearizer class, initiated from the data
        in the LagrangesMethod class. This may be more desirable than using the
        linearize class method, as the Linearizer object will allow more
        efficient recalculation (i.e. about varying operating points).

        Parameters
        ==========

        q_ind, qd_ind : array_like, optional
            The independent generalized coordinates and speeds.
        q_dep, qd_dep : array_like, optional
            The dependent generalized coordinates and speeds.
        linear_solver : str, callable
            Method used to solve the several symbolic linear systems of the
            form ``A*x=b`` in the linearization process. If a string is
            supplied, it should be a valid method that can be used with the
            :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
            supplied, it should have the format ``x = f(A, b)``, where it
            solves the equations and returns the solution. The default is
            ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
            ``LUsolve()`` is fast to compute but will often result in
            divide-by-zero and thus ``nan`` results.

        Returns
        =======
        Linearizer
            An instantiated
            :class:`sympy.physics.mechanics.linearize.Linearizer`.

        c                 S   r   r   r   r   r   r   r   r   M  r   z/LagrangesMethod.to_linearizer.<locals>.<lambda>z?Must supply {:} dependent coordinates, and {:} dependent speedszHMust partition q into q_ind and q_dep, with no extra or missing symbols.zKMust partition qd into qd_ind and qd_dep, with no extra or missing symbols.)keyzpCannot have derivatives of specified                                  quantities when linearizing forcing terms.linear_solver)r   r.   r-   r/   r   r'   r2   r1   r(   r)   r+   r*   rH   r\   formatsetr   listr   sortr   r   )r3   q_indqd_indq_depqd_depri   tr-   uudlamsr;   q_iq_du_iu_df_cf_vf_af_0f_1f_2f_3f_4insymsrrU   r   r   r   to_linearizer$  sH   "

 zLagrangesMethod.to_linearizerc           	      K   s0   | j |||||d}|jdi |}||jf S )aw  Linearize the equations of motion about a symbolic operating point.

        Parameters
        ==========
        linear_solver : str, callable
            Method used to solve the several symbolic linear systems of the
            form ``A*x=b`` in the linearization process. If a string is
            supplied, it should be a valid method that can be used with the
            :meth:`sympy.matrices.matrixbase.MatrixBase.solve`. If a callable is
            supplied, it should have the format ``x = f(A, b)``, where it
            solves the equations and returns the solution. The default is
            ``'LU'`` which corresponds to SymPy's ``A.LUsolve(b)``.
            ``LUsolve()`` is fast to compute but will often result in
            divide-by-zero and thus ``nan`` results.
        **kwargs
            Extra keyword arguments are passed to
            :meth:`sympy.physics.mechanics.linearize.Linearizer.linearize`.

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

        If kwarg A_and_B is False (default), returns M, A, B, r for the
        linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r.

        If kwarg A_and_B is True, returns A, B, r for the linearized form
        dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is
        computationally intensive if there are many symbolic parameters. For
        this reason, it may be more desirable to use the default A_and_B=False,
        returning M, A, and B. Values may then be substituted in to these
        matrices, and the state space form found as
        A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat.

        In both cases, r is found as all dynamicsymbols in the equations of
        motion that are not part of q, u, q', or u'. They are sorted in
        canonical form.

        The operating points may be also entered using the ``op_point`` kwarg.
        This takes a dictionary of {symbol: value}, or a an iterable of such
        dictionaries. The values may be numeric or symbolic. The more values
        you can specify beforehand, the faster this computation will run.

        For more documentation, please see the ``Linearizer`` class.rh   Nr   )r   	linearizer   )	r3   rn   ro   rp   rq   ri   kwargs
linearizerresultr   r   r   r   w  s
   -zLagrangesMethod.linearizerF   c           	      C   s   t | j}|dkrtdt|tr|}nt|r&i }|D ]}|| qn|du r-i }ntd| j	| j
t|| }| j	| j}t||}t||}|| | d }|dkrgtt| j|S |dkrot|S td|)aq  Solves for the values of the lagrange multipliers symbolically at
        the specified operating point.

        Parameters
        ==========

        op_point : dict or iterable of dicts, optional
            Point at which to solve at. The operating point is specified as
            a dictionary or iterable of dictionaries of {symbol: value}. The
            value may be numeric or symbolic itself.

        sol_type : str, optional
            Solution return type. Valid options are:
            - 'dict': A dict of {symbol : value} (default)
            - 'Matrix': An ordered column matrix of the solution
        r   z0System has no lagrange multipliers to solve for.NzDop_point must be either a dictionary or an iterable of dictionaries.rF   r   zUnknown sol_type {:}.)rH   r'   r\   r$   rF   r   updater"   r^   r_   r!   r]   r   rd   r   r   LUsolverN   r   rj   )	r3   op_pointsol_typekop_point_dictopr^   force_matrixsol_listr   r   r   solve_multipliers  s2   



z!LagrangesMethod.solve_multipliersc                 K   s<   |du r| j | j| _| jS | j j|dd| j | _| jS )a/  Returns equations that can be solved numerically.

        Parameters
        ==========

        inv_method : str
            The specific sympy inverse matrix calculation method to use. For a
            list of valid methods, see
            :meth:`~sympy.matrices.matrixbase.MatrixBase.inv`
        NT)try_block_diag)rc   r   re   _rhsinv)r3   
inv_methodr   r   r   r   rhs  s   zLagrangesMethod.rhsc                 C      | j S r   )r,   rY   r   r   r   r-        zLagrangesMethod.qc                 C   r   r   )r/   rY   r   r   r   rs     r   zLagrangesMethod.uc                 C   r   r   )r%   rY   r   r   r   r7     r   zLagrangesMethod.bodiesc                 C   r   r   r#   rY   r   r   r   r6     r   zLagrangesMethod.forcelistc                 C   r   r   r   rY   r   r   r   loads  r   zLagrangesMethod.loads)NNNNN)NNNNrf   )NrF   r   )__name__
__module____qualname____doc__r<   rX   rZ   propertyr^   rc   rd   re   r   r   r   r   r-   rs   r7   r6   r   r   r   r   r   r      sB    [
E8





S

2
2



N)sympyr   r   r   r   r   sympy.core.sortingr   sympy.physics.vectorr   r	   sympy.physics.mechanics.methodr
   !sympy.physics.mechanics.functionsr   r   r   r   !sympy.physics.mechanics.linearizer   sympy.utilities.iterablesr   __all__r   r   r   r   r   <module>   s    