
    wg+                       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mZ d dlmZmZ d dlmZmZmZmZmZmZ d d	lmZmZmZmZmZm Z m!Z!m"Z"m#Z# d d
l$m%Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z. d dl/m0Z0m1Z1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@ d dlAmBZBmCZCmDZD d dlEmFZF d dlGmHZHmIZI d ZJ G d deK      ZL G d de?      ZMd ZNd ZOdCdZPdDd ZQdDd!ZRd" ZSd# ZTd$ ZU	 	 dEd%ZVd& ZWd' ZXd( ZYd) ZZd* Z[d+ Z\dDd,Z]d- Z^d. Z_d/ Z`dFd0Zad1 Zbd2 Zcd3 Zdd4 Zed5 Zfd6 Zgd7 Zhd8 fd9Zid: Zjd; Zkd< Zld= Zmd> Zn	 	 dGd?ZodHd@ZpdIdAZqdJdBZry)K    )AddMulS)Tuple)factor_terms)I)EqEquality)default_sort_keyordered)DummySymbol)
expand_mulexpand
DerivativeAppliedUndefFunctionSubs)	expimcossinre	Piecewisepiecewise_foldsqrtlog	factorial)zerosMatrixNonSquareMatrixError
MatrixBaseeye)Polytogether)collectradsimpsignsimp)	powdenestpowsimp)ratsimp)simplify)	FiniteSet	ode_order)NonlinearErrorsolveset)connected_componentsiterablestrongly_connected_components)
filldedent)Integral	integratec                 V    |D ci c]  t        fd| D               c}S c c}w )Nc              3   6   K   | ]  }t        |        y wNr/   ).0eqfuncs     ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/solvers/ode/systems.py	<genexpr>z"_get_func_order.<locals>.<genexpr>   s     8biD)8   )max)eqsfuncsr>   s     `r?   _get_func_orderrE      s'    EJKTD#8C888KKKs   &c                       e Zd ZdZy)ODEOrderErrorz@Raised by linear_ode_to_matrix if the system has the wrong orderN__name__
__module____qualname____doc__     r?   rG   rG       s    JrN   rG   c                       e Zd ZdZy)ODENonlinearErrorz9Raised by linear_ode_to_matrix if the system is nonlinearNrH   rM   rN   r?   rP   rP   %   s    CrN   rP   c                   	 | j                   }| j                  }t        |      }t        |j	                  t
                    }t        |g|ddi}|D cg c]  }t        |       }}|s|j                  }t        d      t        d      g	g }t        |j                         |j                               D ]  \  }}t        |      }t        |t              rt        	fd|j                   D         }nt#        |      j%                  	      }t'        d t        ||      D         }|j)                  ||z          t+        |t-        |       S c c}w )Nr   FC1C2c              3   \   K   | ]#  \  }}t        |      j                        |f % y wr;   )r,   r'   )r<   coefcondsymss      r?   r@   z_simpsol.<locals>.<genexpr>8   s)     a
d!6!6t!<d Cas   ),c              3   ,   K   | ]  \  }}||z    y wr;   rM   )r<   gis      r?   r@   z_simpsol.<locals>.<genexpr>;   s     :Aa1f:   )lhsrhsr+   listatomsr   r%   r   gensr   zipcoeffsmonomsr   
isinstancer   argsr,   r'   r   appendr	   r   )
soleqr\   solr`   prY   termscoeffmonomrW   s
            @r?   _simpsolrm   *   s"   
))C
))C
#,C		#DS&4&&A%)*LO*D*vv4L&,'DEAHHJ
3 $uu%eY'aV[V`V`abEEN**40E:T5)9:;UU]#$ c3; +s   Ec                     t        t        |             j                  |      \  }}t        |      }|j	                  t
        d       }||z   S )Nc                 *    t        t        |             S r;   )r   r   )as    r?   <lambda>z_solsimp.<locals>.<lambda>D   s    \!_)= rN   )r+   r   as_independentr,   replacer   )etno_thas_ts       r?   _solsimprx   @   sC    *Q-(77:KD%4=DMM#=>E%<rN   c                 F  	
 	fd}d	
fd		d d 
|rF t               j                  d | D         }|D ci c]  }|t        |      j                          }}ni }| D cg c]+  }t	        |j
                   ||j                  |||            - } }| S c c}w c c}w )z&Simplify solutions from dsolve_system.c                 n    |r| j                  |      } t        |       }  | ||      } t        |       } | S )z#Simplify the rhs of an ODE solution)subsr   r)   )r]   repwrt1wrt2simp_coeff_deps       r?   simprhszsimpsol.<locals>.simprhsp   s9    ((3-C3S$-sm
rN   c                    fdfdd fd}t        j                   ||             }i }|D ]x  } |j                  ddi\  }} |      }|t        j                  ur/t        |      }	 |	j                   s||	z  }t        j                  }||vr|||<   l||xx   |z  cc<   z fd|j                         D        }
fd|
D        }
t        d	 |
D         S )
zGSplit rhs into terms, split terms into dep and coeff and collect on depc                 >    | j                   xr  | j                   S r;   )is_Addhas)rt   r}   s    r?   rq   z1simpsol.<locals>.simp_coeff_dep.<locals>.<lambda>{   s    !((";uquud| rN   c                 ^    | j                   xr t        t        | j                              S r;   )is_Mulanymapre   )rt   add_dep_termss    r?   rq   z1simpsol.<locals>.simp_coeff_dep.<locals>.<lambda>|   s     qxxKCM1660J,K rN   c                     t        | d      S )NF)deep)r   )rt   s    r?   rq   z1simpsol.<locals>.simp_coeff_dep.<locals>.<lambda>}   s    
15 9 rN   c                 (    | j                        S r;   )rs   )rt   expand_func
expandables    r?   rq   z1simpsol.<locals>.simp_coeff_dep.<locals>.<lambda>~   s    199Z#E rN   as_AddFc              3   :   K   | ]  \  }} |      |f  y wr;   rM   )r<   dc	simpcoeffr~   s      r?   r@   z2simpsol.<locals>.simp_coeff_dep.<locals>.<genexpr>   s!     DAi4(!,D   c              3   :   K   | ]  \  }} |      |f  y wr;   rM   )r<   r   r   r   r~   s      r?   r@   z2simpsol.<locals>.simp_coeff_dep.<locals>.<genexpr>   s!     L$!Q.D115Lr   c              3   ,   K   | ]  \  }}||z    y wr;   rM   )r<   r   r   s      r?   r@   z2simpsol.<locals>.simp_coeff_dep.<locals>.<genexpr>   s     1tq!QU1r[   )r   	make_argsrr   r   Oner   r   items)exprr}   r~   expand_mul_modrj   dctermrk   depdep2	termpairsr   r   r   r   r   simpdeps    ``        @@@r?   r   zsimpsol.<locals>.simp_coeff_depy   s    ;K
9EnT23 	!D,,,dA5AJE3 #t$C !%%#C(txxTME%%C"}335 !	!& ED	L)LI1y122rN   c           
          fd}t        |       } | j                  t              D ci c]!  }|t         ||j                  d               # }}| j	                  |      } | S c c}w )z<Normalise factors involving t with powsimp and recombine expc                 x    t        |       } | j                         \  }}t        |      }t        |      }||z  S r;   )r   as_numer_denomr   r'   )rp   numdenr}   s      r?   canonicalisez.simpsol.<locals>.simpdep.<locals>.canonicalise   s?     QA'')HCS/C#t$C9rN   r   )r+   r_   r   re   r{   )r   r}   r   rt   r|   s    `   r?   r   zsimpsol.<locals>.simpdep   s]    
	 t}8<

3H1q#l166!9-..HHyy~ Is   &A$c           	      @   t        |       } | j                         rt        t        |             } |7t	        |      t	        t        | j                  t        |      z
              z   }nt	        t        | j                              }t        | |      } t        |       } | S )z2Bring to a common fraction and cancel with ratsimp)	r&   is_polynomialr,   r(   r^   r   free_symbolssetr'   )rk   r~   rW   s      r?   r   zsimpsol.<locals>.simpcoeff   s     
 GEN+E:WU-?-?#d)-K%L MMD 2 234Dt$rN   c              3   F   K   | ]  }|j                  t                y wr;   )r_   r7   )r<   ss     r?   r@   zsimpsol.<locals>.<genexpr>   s     !A!''("3!As   !r;   )r   unionr   doitr	   r\   r]   )rh   r}   r~   r   r   	integralsrZ   r|   r   r   r   r   s            @@@r?   simpsolr   I   s    N3@&* CEKK!AS!AB	2;<Qq,q/&&((<<?B
C!2aeeWQUUCt45
CC
CJ = Ds   !B%0BNc           
         i }t        | |       }|du xs |j                   }dj                  t        dj                  t        |      t        |            d      dz         }d}|j	                  ||d       |rGt        | |      \  }}|st        t        d            ||d<   |j	                  t        | ||	             |S )
a
  
    Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()`

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

    This function takes in the coefficient matrix and/or the non-homogeneous term
    and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`.

    If the system is constant coefficient homogeneous, then "type1" is returned

    If the system is constant coefficient non-homogeneous, then "type2" is returned

    If the system is non-constant coefficient homogeneous, then "type3" is returned

    If the system is non-constant coefficient non-homogeneous, then "type4" is returned

    If the system has a non-constant coefficient matrix which can be factorized into constant
    coefficient matrix, then "type5" or "type6" is returned for when the system is homogeneous or
    non-homogeneous respectively.

    Note that, if the system of ODEs is of "type3" or "type4", then along with the type,
    the commutative antiderivative of the coefficient matrix is also returned.

    If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then
    NotImplementedError is raised.

    Parameters
    ==========

    A : Matrix
        Coefficient matrix of the system of ODEs
    b : Matrix or None
        Non-homogeneous term of the system. The default value is None.
        If this argument is None, then the system is assumed to be homogeneous.

    Examples
    ========

    >>> from sympy import symbols, Matrix
    >>> from sympy.solvers.ode.systems import linodesolve_type
    >>> t = symbols("t")
    >>> A = Matrix([[1, 1], [2, 3]])
    >>> b = Matrix([t, 1])

    >>> linodesolve_type(A, t)
    {'antiderivative': None, 'type_of_equation': 'type1'}

    >>> linodesolve_type(A, t, b=b)
    {'antiderivative': None, 'type_of_equation': 'type2'}

    >>> A_t = Matrix([[1, t], [-t, 1]])

    >>> linodesolve_type(A_t, t)
    {'antiderivative': Matrix([
    [      t, t**2/2],
    [-t**2/2,      t]]), 'type_of_equation': 'type3'}

    >>> linodesolve_type(A_t, t, b=b)
    {'antiderivative': Matrix([
    [      t, t**2/2],
    [-t**2/2,      t]]), 'type_of_equation': 'type4'}

    >>> A_non_commutative = Matrix([[1, t], [t, -1]])
    >>> linodesolve_type(A_non_commutative, t)
    Traceback (most recent call last):
    ...
    NotImplementedError:
    The system does not have a commutative antiderivative, it cannot be
    solved by linodesolve.

    Returns
    =======

    Dict

    Raises
    ======

    NotImplementedError
        When the coefficient matrix does not have a commutative antiderivative

    See Also
    ========

    linodesolve: Function for which linodesolve_type gets the information

    Ntype{}z{}{}      )type_of_equationantiderivativez
                The system does not have a commutative antiderivative, it cannot be solved
                by linodesolve.
            r   b)	_matrix_is_constantis_zero_matrixformatintupdate_is_commutative_anti_derivativeNotImplementedErrorr6   _first_order_type5_6_subs)	Aru   r   matchis_non_constantis_non_homogeneoustypeBis_commutings	            r?   linodesolve_typer      s    t E-a33O4i;1+;+;<??3v}}S-A3GYCZ[]^_bccdDA	LLda@A9!Q?<%j 2 '  
 #$.q!q9:LrN   c                    i }t        | |      }|d u xs |j                  }|t        dj                  |            }t	        |d   |      }t        t        ||      |      }t        |t              r||j                  t              sgt        |      dk(  rY|d   } |s&||d   z  }|j                  |t        |      d         }dj                  d| z         }	|j                  | |||	|d       |S )N{}_r   r   r      )
func_coefftaut_r   r]   )_factor_matrixr   r   r   r8   r2   r	   rd   r.   r   r   lenr{   r^   r   )
r   ru   r   r   r   is_homogeneousr   F_tinverser   s
             r?   r   r   ;  s    E!!Q'L$Y2!"2"2NELLO$Q+2b#;* gy)'++i2HG!QA!Q'FF1d7mA./??1N(:#;<DLL# "QH I LrN   c                    ddl m} t        fd| D              rd}t        |j	                              g }t        dd      D ]q  }D cg c]  }|j                  ||       }	}	  || |	      \  }
}|
j                  t              }
|j                  |k(  r|
n|
        |r|D cg c]  }|  } }p|}s |fS c c}w # t        $ r t        d      w xY wc c}w )aZ  
    Convert a linear system of ODEs to matrix form

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

    Express a system of linear ordinary differential equations as a single
    matrix differential equation [1]. For example the system $x' = x + y + 1$
    and $y' = x - y$ can be represented as

    .. math:: A_1 X' = A_0 X + b

    where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are
    $2 \times 1$ matrices with $X = [x, y]^T$.

    Higher-order systems are represented with additional matrices e.g. a
    second-order system would look like

    .. math:: A_2 X'' =  A_1 X' + A_0 X  + b

    Examples
    ========

    >>> from sympy import Function, Symbol, Matrix, Eq
    >>> from sympy.solvers.ode.systems import linear_ode_to_matrix
    >>> t = Symbol('t')
    >>> x = Function('x')
    >>> y = Function('y')

    We can create a system of linear ODEs like

    >>> eqs = [
    ...     Eq(x(t).diff(t), x(t) + y(t) + 1),
    ...     Eq(y(t).diff(t), x(t) - y(t)),
    ... ]
    >>> funcs = [x(t), y(t)]
    >>> order = 1 # 1st order system

    Now ``linear_ode_to_matrix`` can represent this as a matrix
    differential equation.

    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order)
    >>> A1
    Matrix([
    [1, 0],
    [0, 1]])
    >>> A0
    Matrix([
    [1, 1],
    [1,  -1]])
    >>> b
    Matrix([
    [1],
    [0]])

    The original equations can be recovered from these matrices:

    >>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs])
    >>> X = Matrix(funcs)
    >>> A1 * X.diff(t) - A0 * X - b == eqs_mat
    True

    If the system of equations has a maximum order greater than the
    order of the system specified, a ODEOrderError exception is raised.

    >>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))]
    >>> linear_ode_to_matrix(eqs, funcs, t, 1)
    Traceback (most recent call last):
    ...
    ODEOrderError: Cannot represent system in 1-order form

    If the system of equations is nonlinear, then ODENonlinearError is
    raised.

    >>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))]
    >>> linear_ode_to_matrix(eqs, funcs, t, 1)
    Traceback (most recent call last):
    ...
    ODENonlinearError: The system of ODEs is nonlinear.

    Parameters
    ==========

    eqs : list of SymPy expressions or equalities
        The equations as expressions (assumed equal to zero).
    funcs : list of applied functions
        The dependent variables of the system of ODEs.
    t : symbol
        The independent variable.
    order : int
        The order of the system of ODEs.

    Returns
    =======

    The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the
    the matrix representing the rhs of the matrix equation.

    Raises
    ======

    ODEOrderError
        When the system of ODEs have an order greater than what was specified
    ODENonlinearError
        When the system of ODEs is nonlinear

    See Also
    ========

    linear_eq_to_matrix: for systems of linear algebraic equations.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation

    r   )linear_eq_to_matrixc              3   J   K   | ]  }D ]  }t        ||      kD     y wr;   r/   )r<   r=   r>   rD   orders      r?   r@   z'linear_ode_to_matrix.<locals>.<genexpr>  s*     
G2
G9R&
G&
Gs    #z(Cannot represent system in {}-order formz The system of ODEs is nonlinear.)sympy.solvers.solvesetr   r   rG   r   rangediffr1   rP   	applyfuncr   rf   )rC   rD   ru   r   r   msgAsor>   rW   Air   r=   r]   s    ` `          r?   linear_ode_to_matrixr   V  s    l ;

G
GG8CJJu-..	B5"b! ,12D		!Q22	H'T2EB \\*%
		U
",!"#2B3#C#C%( s7N% 3  	H#$FGG	H $s   C,C,
CCc                 L    t        | |      \  }}||z  |j                         z  S )a  
    Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``.

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

    This functions returns the $\exp(A*t)$ by doing a simple
    matrix multiplication:

    .. math:: \exp(A*t) = P * expJ * P^{-1}

    where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal
    form of $A$ and $P$ is matrix such that:

    .. math:: A = P * J * P^{-1}

    The matrix exponential $\exp(A*t)$ appears in the solution of linear
    differential equations. For example if $x$ is a vector and $A$ is a matrix
    then the initial value problem

    .. math:: \frac{dx(t)}{dt} = A \times x(t),   x(0) = x0

    has the unique solution

    .. math:: x(t) = \exp(A t) x0

    Examples
    ========

    >>> from sympy import Symbol, Matrix, pprint
    >>> from sympy.solvers.ode.systems import matrix_exp
    >>> t = Symbol('t')

    We will consider a 2x2 matrix for comupting the exponential

    >>> A = Matrix([[2, -5], [2, -4]])
    >>> pprint(A)
    [2  -5]
    [     ]
    [2  -4]

    Now, exp(A*t) is given as follows:

    >>> pprint(matrix_exp(A, t))
    [   -t           -t                    -t              ]
    [3*e  *sin(t) + e  *cos(t)         -5*e  *sin(t)       ]
    [                                                      ]
    [         -t                     -t           -t       ]
    [      2*e  *sin(t)         - 3*e  *sin(t) + e  *cos(t)]

    Parameters
    ==========

    A : Matrix
        The matrix $A$ in the expression $\exp(A*t)$
    t : Symbol
        The independent variable

    See Also
    ========

    matrix_exp_jordan_form: For exponential of Jordan normal form

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form
    .. [2] https://en.wikipedia.org/wiki/Matrix_exponential

    )matrix_exp_jordan_forminv)r   ru   PexpJs       r?   
matrix_expr     s*    N %Q*GAtt8aeegrN   c           	         | j                   \  }}||k7  rt        d|d|d      | j                        rt        d      d } ||       }t        |j	                         t
              }| j                  t               }g }g t               }	|D ]  \  }
}|D ]  }t        |      }|r-|
|
j                         k7  r|
j                         |v r|
|	v r>|	j                  |
j                                t        t        |
      z        }t        |
      z  }t        t        |      t!        |      gt!        |       t        |      gg      t        ||fd      t        d|z  d|z  fd	      }|j#                  ||z         t%        |      D ]<  }j#                  t        ||                j#                  t        ||                > ?j'                  |       fd
}t        |||      }|j#                  t        |
z        |z           t        j(                  | }t        ||fd      }||fS )a  
    Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.

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

    Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:

    .. math::
        \exp(A*t) = P * expJ * P^{-1}

    Examples
    ========

    >>> from sympy import Matrix, Symbol
    >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
    >>> t = Symbol('t')

    We will consider a 2x2 defective matrix. This shows that our method
    works even for defective matrices.

    >>> A = Matrix([[1, 1], [0, 1]])

    It can be observed that this function gives us the Jordan normal form
    and the required invertible matrix P.

    >>> P, expJ = matrix_exp_jordan_form(A, t)

    Here, it is shown that P and expJ returned by this function is correct
    as they satisfy the formula: P * expJ * P_inverse = exp(A*t).

    >>> P * expJ * P.inv() == matrix_exp(A, t)
    True

    Parameters
    ==========

    A : Matrix
        The matrix $A$ in the expression $\exp(A*t)$
    t : Symbol
        The independent variable

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Defective_matrix
    .. [2] https://en.wikipedia.org/wiki/Jordan_matrix
    .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form

    z$Needed square matrix but got shape (z, )zMatrix A should not depend on tc                    | j                         \  }}t        |j                  d         D cg c]  }|dd|f    }}d}i }|D ]>  }|d   }|j                  d   }	||vrg ||<   ||   j                  ||||	z           ||	z  }@ |S c c}w )a   Chains from Jordan normal form analogous to M.eigenvects().
        Returns a dict with eignevalues as keys like:
            {e1: [[v111,v112,...], [v121, v122,...]], e2:...}
        where vijk is the kth vector in the jth chain for eigenvalue i.
        r   Nr   r   r   )jordan_cellsr   shaperf   )
r   r   blocksrZ   basisnchainsr   eigvalsizes
             r?   jordan_chainsz-matrix_exp_jordan_form.<locals>.jordan_chainsp  s     NN$	6!&qwwqz!23A1Q333 	AtWF771:DV#!#v6N!!%!D&/2IA	  4s   B	keyc                 Z    || k\  r|| z
  z  z  t        || z
        z  S t        dd      S Nr   )r   r    )rZ   jimblockru   s     r?   rq   z(matrix_exp_jordan_form.<locals>.<lambda>  s9    ?@Av!ac(*Yqs^; "1a[ rN   r   c                 4    | dz  |dz  f   | dz  |dz  f   S r   rM   )rZ   r   
expJblock2s     r?   rq   z(matrix_exp_jordan_form.<locals>.<lambda>  s-    AqDAI9NqQRsSTUVSVw9W rN   c                 @    || k\  r|| z
  z  t        || z
        z  S dS Nr   r   )rZ   r   ru   s     r?   rq   z(matrix_exp_jordan_form.<locals>.<lambda>  s&    Q!V!ac(9QqS>"9  rN   c                     |   |    S r;   rM   )rZ   r   vectorss     r?   rq   z(matrix_exp_jordan_form.<locals>.<lambda>  s    A rN   )r   
ValueErrorr   sortedr   r   r   r   r   	conjugateaddr   r   r   r!   r   r   rf   r   extenddiag)r   ru   NMr   eigenchainseigenchains_iterisrealr   seen_conjugatert   r   chainr   exprtimrt	expJblockrZ   funr   r   r   r   r  s    `                   @@@r?   r   r   6  s   h 77DAqAv!QOPP	
q:;;&  "K k//17GHq\FFGUN% 6	6 	6EE
A!q{{},+1M&""1;;=1BqEAI!uqy 3t9c$i"8$'I:s4y"9"; <#Aq +) *
 #1Q3!-WX	ei/0q 1ANN2eAh<0NN2eAh<01 u%J"1a-	c!a%j945/	664 ;;Dq!./Ad7NrN   c           	      
   t        | t              st        t        d            | j                  st        t        d            |Qt        |t              st        t        d            | j                  |j                  k7  rt        t        d            |qt        |t              st        t        d            |j                  st        t        d            | j                  |j                  k7  rt        t        d            t        fd	t        d
d      D              sdk(  st        t        d            | j                  }t        t        |      D cg c]  }t                c}      }	| t        fddD              rt        |d
      }|du}
}dk(  rt        | |      }|d   |d   }dv rPd}
|dk7  rI|Gt        | |      }|s#t        t        dj                                    |d   }|d   |d   } |d   }fd}dv rit        |       \  }}t!        |      }dv r	|||	z  z  }n|j#                         }||z  ||j%                         z  |z  j'                  |      |	z   z  }na|t)        |       \  }}dk(  r|j+                         |	z  }n7|j+                         | j+                         |z  j'                  |      |	z   z  }|
r|j#                  |      }|j-                  t*              }dk7  r|D cg c]  }t/        |       }}|D cg c]  }t1        |t3        |      d       }}|r|D cg c]  }|j5                          }}|S c c}w c c}w c c}w c c}w ) ai   
    System of n equations linear first-order differential equations

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

    This solver solves the system of ODEs of the following form:

    .. math::
        X'(t) = A(t) X(t) +  b(t)

    Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
    $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$

    Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
    differently.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
    the system is "type1". The solution is:

    .. math::
        X(t) = \exp(A t) C

    Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
    the system is "type2". The solution is:

    .. math::
        X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)

    When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
    $b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is:

    .. math::
        X(t) = \exp(B(t)) C

    When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
    non-homogeneous, the system is "type4". The solution is:

    .. math::
        X(t) =  e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)

    When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant
    coefficient matrix:

    .. math::
        A(t) = f(t) * A

    Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix,
    then we can do the following substitutions:

    .. math::
        tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau))

    Here, the substitution for the non-homogeneous term is done only when its non-zero.
    Using these substitutions, our original system becomes:

    .. math::
        Y'(tau) = A * Y(tau) + b(tau)/f(tau)

    The above system can be easily solved using the solution for "type1" or "type2" depending
    on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the
    solution for $tau$ as $t$ to get back $X(t)$

    .. math::
        X(t) = Y(tau)

    Systems of "type5" and "type6" have a commutative antiderivative but we use this solution
    because its faster to compute.

    The final solution is the general solution for all the four equations since a constant coefficient
    matrix is always commutative with its antidervative.

    An additional feature of this function is, if someone wants to substitute for value of the independent
    variable, they can pass the substitution `tau` and the solution will have the independent variable
    substituted with the passed expression(`tau`).

    Parameters
    ==========

    A : Matrix
        Coefficient matrix of the system of linear first order ODEs.
    t : Symbol
        Independent variable in the system of ODEs.
    b : Matrix or None
        Non-homogeneous term in the system of ODEs. If None is passed,
        a homogeneous system of ODEs is assumed.
    B : Matrix or None
        Antiderivative of the coefficient matrix. If the antiderivative
        is not passed and the solution requires the term, then the solver
        would compute it internally.
    type : String
        Type of the system of ODEs passed. Depending on the type, the
        solution is evaluated. The type values allowed and the corresponding
        system it solves are: "type1" for constant coefficient homogeneous
        "type2" for constant coefficient non-homogeneous, "type3" for non-constant
        coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous,
        "type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous
        systems respectively where the coefficient matrix can be factorized to a constant
        coefficient matrix.
        The default value is "auto" which will let the solver decide the correct type of
        the system passed.
    doit : Boolean
        Evaluate the solution if True, default value is False
    tau: Expression
        Used to substitute for the value of `t` after we get the solution of the system.

    Examples
    ========

    To solve the system of ODEs using this function directly, several things must be
    done in the right order. Wrong inputs to the function will lead to incorrect results.

    >>> from sympy import symbols, Function, Eq
    >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
    >>> from sympy.solvers.ode.subscheck import checkodesol
    >>> f, g = symbols("f, g", cls=Function)
    >>> x, a = symbols("x, a")
    >>> funcs = [f(x), g(x)]
    >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]

    Here, it is important to note that before we derive the coefficient matrix, it is
    important to get the system of ODEs into the desired form. For that we will use
    :obj:`sympy.solvers.ode.systems.canonical_odes()`.

    >>> eqs = canonical_odes(eqs, funcs, x)
    >>> eqs
    [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]

    Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
    non-homogeneous term if it is there.

    >>> eqs = eqs[0]
    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = A0

    We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
    :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
    to finally pass it to the solver.

    >>> system_info = linodesolve_type(A, x, b=b)
    >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation'])

    Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checkodesol(eqs, sol)
    (True, [0, 0])

    We can also use the doit method to evaluate the solutions passed by the function.

    >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)

    Now, we will look at a system of ODEs which is non-constant.

    >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]

    The system defined above is already in the desired form, so we do not have to convert it.

    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = A0

    A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
    Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
    with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
    If it does have a commutative antiderivative, then the function just returns the information about the system.

    >>> system_info = linodesolve_type(A, x, b=b)

    Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
    passed, then the solver will compute the required arguments internally.

    >>> sol_vector = linodesolve(A, x, b=b)

    Once again, we can verify the solution obtained.

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checkodesol(eqs, sol)
    (True, [0, 0])

    Returns
    =======

    List

    Raises
    ======

    ValueError
        This error is raised when the coefficient matrix, non-homogeneous term
        or the antiderivative, if passed, are not a matrix or
        do not have correct dimensions
    NonSquareMatrixError
        When the coefficient matrix or its antiderivative, if passed is not a
        square matrix
    NotImplementedError
        If the coefficient matrix does not have a commutative antiderivative

    See Also
    ========

    linear_ode_to_matrix: Coefficient matrix computation function
    canonical_odes: System of ODEs representation change
    linodesolve_type: Getting information about systems of ODEs to pass in this solver

    zT            The coefficients of the system of ODEs should be of type Matrix
        z<            The coefficient matrix must be a square
        Nze                The non-homogeneous terms of the system of ODEs should be of type Matrix
            z                The system of ODEs should have the same number of non-homogeneous terms and the number of
                equations
            zn                The antiderivative of coefficients of the system of ODEs should be of type Matrix
            zZ                The antiderivative of the coefficient matrix must be a square
            zv                        The coefficient matrix and its antiderivative should have same dimensions
                    c              3   F   K   | ]  }d j                  |      k(    yw)r   N)r   )r<   rZ   r   s     r?   r@   zlinodesolve.<locals>.<genexpr>  s     ?atxq))?   !r      autozI                    The input type should be a valid one
                c              3   (   K   | ]	  }|k(    y wr;   rM   )r<   typr   s     r?   r@   zlinodesolve.<locals>.<genexpr>  s     LL   )type2type4type6r   r   r   )type5r  TzI
                        The system passed isn't {}.
                    r   r   r   r   c                 $    | rt        |       S dS r   )r7   )xru   s    r?   rq   zlinodesolve.<locals>.<lambda>  s    A(1a. 1 rN   )type1r  r  r  )r!  r  type3r!  )exact)rd   r#   r  r6   	is_squarer"   rowsr   r   r!   r   r    r   r   r   r   r-   r{   r   r   r   r   r_   r   r'   r   r   )r   ru   r   r   r   r   r   r   _Cvectis_transformedpassed_typesystem_info	intx_wrttr   J
sol_vectorJinvr`   r   s    `  `               r?   linodesolver/    s   d a$ %   	 ;;": / $  	 	}!Z(Z )    66QVVZ )   
 	}!Z(Z )    {{&z 3 (   66QVVZ )    ?5A;??PV %   	 	
A U1X.EG./EySL0KLL!QK_NKv~&q!q1-.()!!& {71B"$Z 1t&& ' ' "%(%$$4I33%a+1QK%%a%iJ66!aR=DQ4!%%'>A#5"@"@"Ke"STJ921a8DAq7?5JqbXXZ!^$>$>y$IE$QRJ__Q,
C Dw-78jm8
8AKLA'!WT]$7LJL(231affh3
3y /j 9L 4s   "M1M60M;N c                 ,    t        fd| D              S )z2Checks if the matrix M is independent of t or not.c              3   P   K   | ]  }|j                  d       d   dk(    yw)T)r   r   r   N)rr   )r<   rU   ru   s     r?   r@   z&_matrix_is_constant.<locals>.<genexpr>  s+     Itt""1T"215:Is   #&)all)r	  ru   s    `r?   r   r     s    IqIIIrN   c                 P   ddl m} t        | |      } || g|D cg c]  }|j                  |||          c}ddi}g }|D ]U  }|D cg c]7  }t	        |j                  |||         ||j                  |||                  9 }	}|j                  |	       W |S c c}w c c}w )a  
    Function that solves for highest order derivatives in a system

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

    This function inputs a system of ODEs and based on the system,
    the dependent variables and their highest order, returns the system
    in the following form:

    .. math::
        X'(t) = A(t) X(t) + b(t)

    Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is
    the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the
    vector of dependent variables in their respective highest order. We use the term
    canonical form to imply the system of ODEs which is of the above form.

    If the system passed has a non-linear term with multiple solutions, then a list of
    systems is returned in its canonical form.

    Parameters
    ==========

    eqs : List
        List of the ODEs
    funcs : List
        List of dependent variables
    t : Symbol
        Independent variable

    Examples
    ========

    >>> from sympy import symbols, Function, Eq, Derivative
    >>> from sympy.solvers.ode.systems import canonical_odes
    >>> f, g = symbols("f g", cls=Function)
    >>> x, y = symbols("x y")
    >>> funcs = [f(x), g(x)]
    >>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))]

    >>> canonical_eqs = canonical_odes(eqs, funcs, x)
    >>> canonical_eqs
    [[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]]

    >>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)]

    >>> canonical_system = canonical_odes(system, funcs, x)
    >>> canonical_system
    [[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]]

    Returns
    =======

    List

    r   )solvedictT)sympy.solvers.solversr4  rE   r   r	   rf   )
rC   rD   ru   r4  r   r>   	canon_eqssystemsr=   systems
             r?   canonical_odesr:    s    t ,C'EcU5I4TYYq%+6IUPTUIG [`aSW"TYYq%+.499Qd3L0MNaav N J bs   B
<B#c                     t        | |      }|| z  | |z  z
  j                  t              j                  t              j                  }|dn|}||fS )a  
    Helper function for determining if the Matrix passed is commutative with its antiderivative

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

    This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect
    to the independent variable $t$.

    .. math::
        B(t) = \int A(t) dt

    The function outputs two values, first one being the antiderivative $B(t)$, second one being a
    boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix
    passed isn't commutative with $B(t)$.

    Parameters
    ==========

    A : Matrix
        The matrix which has to be checked
    t : Symbol
        Independent variable

    Examples
    ========

    >>> from sympy import symbols, Matrix
    >>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative
    >>> t = symbols("t")
    >>> A = Matrix([[1, t], [-t, 1]])

    >>> B, is_commuting = _is_commutative_anti_derivative(A, t)
    >>> is_commuting
    True

    Returns
    =======

    Matrix, Boolean

    F)r8   r   r   r   r   )r   ru   r   r   s       r?   r   r   9  sS    V 	!QAaC!A#I((0::<HWWL(05lLl?rN   c                     d }| D ]+  }|j                  |      d   }|j                  |      s)|} n |,| |z  j                  t              }t	        ||      }|r||fnd }|S )Nr   )rr   r   r   r,   r   )r   ru   r   element	temp_term
A_factored
can_factors          r?   r   r   l  sz    D **1-a0	==D	 f''0
(Q7
%/j!TKrN   c                    t        | |      }d}|d|d   z  }|j                         }|rt        |j                         |      }|j	                         }|d   d   dv rt        |d      }|\  }}}	}
}t        t        |      d      }t        t        |      d      }t        t        |	d|z  |z  z
        d      }|d|z  |z  k(  xr |
d|z  |z  k(  }||dz  z  ||z  z   |z   }||fS d}||fS )	NFr   r   )r      rB  T)forcer   )r   r   r%   r   rc   _get_poly_coeffsr*   r   )r   ru   r   is_type2polyrc   csrp   r   r   r   rt   a1c1b1s                  r?   _is_second_order_type2rK  |  s   !QDHay%%'DKKM1%!9Q<6!!$*BMAq!Q47$/B47$/B4AbDG,D9BQrT"W81"R<Had7RT>B&D
 T> HT>rN   c                     t        |dz         D cg c]  }d }}t        | j                         | j                               D ]  \  }}||d|d   z
  <    |S c c}w )Nr   r   r   )r   ra   rb   rc   )rF  r   r&  rG  r   ms         r?   rD  rD    s^    57^	$!	$B	$DKKM4;;=1 12ad7I 
%s   	Ac           	      ~   ddi}| j                   d   }t        | |      rt        ||      r|S | ||z  z   j                  t              j                  r|j                  d| d       |S | j                  r||j                  rt        ||      \  }}|rt        t        ||      d      \  }}}	||dz  j                         z  j                  t              |dz  dz  ||	z  z
  t        ||      z  z   }
t        d|z  |      }t        d	j                  |            }|j                  d
|
t        |      |d|d       |S )a  
    Works only for second order system in its canonical form.

    Type 0: Constant coefficient matrix, can be simply solved by
            introducing dummy variables.
    Type 1: When the substitution: $U = t*X' - X$ works for reducing
            the second order system to first order system.
    Type 2: When the system is of the form: $poly * X'' = A*X$ where
            $poly$ is square of a quadratic polynomial with respect to
            *t* and $A$ is a constant coefficient matrix.

    r   type0r   r!  )r   A1r   rB  r   r   r  T)r   A0g(t)r   r(  r   )r   r   r   r   r   r   rK  rD  r%   r   r,   r$   r8   r   r   r   )rP  rQ  ru   r   r   r   rE  r   rp   r   r   r   r   s                r?   _match_second_order_typerS    s:     )E
A2q!&9"a&@
RT	Z(77'<= L 
			Q-=-=/A6$&tD!}a8GAq!T1W$$&&11':ad1fqslCPQSTI=UUAAdFA&CQ(BLLgQ"&t*SD "$ % LrN   c           	         t        |D cg c]  }||j                  |      z  |z
   c}      }t        | |||z        }t        ||      D cg c]  \  }}t	        ||       }	}}t        |	||      d   }	|	S c c}w c c}}w )a  
    For a linear, second order system of ODEs, a particular substitution.

    A system of the below form can be reduced to a linear first order system of
    ODEs:
    .. math::
        X'' = A(t) * (t*X' - X) + b(t)

    By substituting:
    .. math::  U = t*X' - X

    To get the system:
    .. math::  U' = t*(A(t)*U + b(t))

    Where $U$ is the vector of dependent variables, $X$ is the vector of dependent
    variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to
    $t$. It may or may not reduce the system into linear first order system of ODEs.

    Then a check is made to determine if the system passed can be reduced or not, if
    this substitution works, then the system is reduced and its solved for the new
    substitution. After we get the solution for $U$:

    .. math::  U = a(t)

    We substitute and return the reduced system:

    .. math::
        a(t) = t*X' - X

    Parameters
    ==========

    A: Matrix
        Coefficient matrix($A(t)*t$) of the second order system of this form.
    b: Matrix
        Non-homogeneous term($b(t)$) of the system of ODEs.
    funcs: List
        List of dependent variables
    t: Symbol
        Independent variable of the system of ODEs.

    Returns
    =======

    List

    r   )r!   r   r/  ra   r	   r:  )
r   r   rD   ru   r>   Urh   r   ureduced_eqss
             r?   _second_order_subs_type1rX    s    b 	%8$$))A,%89A
aAaC
 C(+C412a84K4 eQ7:K 9 5s   A9A>c                 h   |D cg c]  }|j                   j                   }}|D cg c]+  } t        t        dj	                  |                  |      - }}| t        |      z  }t        ||      D cg c]!  \  }}t        |j                  |d      |      # }	}}|	|fS c c}w c c}w c c}}w )a  
    Returns a second order system based on the coefficient matrix passed.

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

    This function returns a system of second order ODE of the following form:

    .. math::
        X'' = A * X

    Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the
    coefficient matrix passed.

    Along with returning the second order system, this function also returns the new
    dependent variables with the new independent variable `t_` passed.

    Parameters
    ==========

    A: Matrix
        Coefficient matrix of the system
    funcs: List
        List of old dependent variables
    t_: Symbol
        New independent variable

    Returns
    =======

    List, List

    r   r   )	r>   rI   r   r   r   r!   ra   r	   r   )
r   rD   r   r>   
func_namesname	new_funcsrhssr]   new_eqss
             r?   _second_order_subs_type2r_    s    D 277$))$$7J7EOPT4%T 234R8PIPvi  D:=i:NOYT3r$))B"C(OGOI 8POs   B$0B)7&B.c                 >    t        fdt        |       D              S )Nc              3   n   K   | ],  \  }}t        ||z  z  j                  t                     . y wr;   )r   r   r,   )r<   rZ   r   ru   s      r?   r@   z#_is_euler_system.<locals>.<genexpr>)  s0     ]tq!"AadF#5#5g#>B]s   25)r2  	enumerate)r   ru   s    `r?   _is_euler_systemrc  (  s    ]yY[}]]]rN   c                    t        |      t        |       k7  rt        d|z        |D ](  }t        |j                        dk7  st        d|z         t        | |      t	        fd|D              }|dkD  }|dk(  xr t        fd|D              }	 |st        | |      n| g}t        |      dk(  rt        |d   ||      \  }	}
nd|d	}|S 	 d}|
j                  rdnd}t        |       | |||dd}|s|
|d<   t        fd|	D              }|sU|	d   }||d<   t        |      }||d<   	 t        ||
      }|j                  |       |j                  d      }|s||d<   |S d|d<   |r+|	dd
 \  }}t        ||      }|j                  |       d|d<   |d   dk(  r|st!        |	      }|r0t#        dj%                              }|j                  dd|d       ndd }t'        |	d         }t        d |	dd D              r=|; ||d         s0|d   j)                         \  }}|j                  d||d   |dd       |d   dk7  r|r|j                  dd
       ||d<   |S # t        $ r Y y
w xY w# t        $ r Y y
w xY w) a  
    Returns a dictionary with details of the eqs if the system passed is linear
    and can be classified by this function else returns None

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

    This function takes the eqs, converts it into a form Ax = b where x is a vector of terms
    containing dependent variables and their derivatives till their maximum order. If it is
    possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise
    they are non-linear.

    To check if the equations are constant coefficient, we need to check if all the terms in
    A obtained above are constant or not.

    To check if the equations are homogeneous or not, we need to check if b is a zero matrix
    or not.

    Parameters
    ==========

    eqs: List
        List of ODEs
    funcs: List
        List of dependent variables
    t: Symbol
        Independent variable of the equations in eqs
    is_canon: Boolean
        If True, then this function will not try to get the
        system in canonical form. Default value is False

    Returns
    =======

    match = {
        'no_of_equation': len(eqs),
        'eq': eqs,
        'func': funcs,
        'order': order,
        'is_linear': is_linear,
        'is_constant': is_constant,
        'is_homogeneous': is_homogeneous,
    }

    Dict or list of Dicts or None
        Dict with values for keys:
            1. no_of_equation: Number of equations
            2. eq: The set of equations
            3. func: List of dependent variables
            4. order: A dictionary that gives the order of the
                      dependent variable in eqs
            5. is_linear: Boolean value indicating if the set of
                          equations are linear or not.
            6. is_constant: Boolean value indicating if the set of
                          equations have constant coefficients or not.
            7. is_homogeneous: Boolean value indicating if the set of
                          equations are homogeneous or not.
            8. commutative_antiderivative: Antiderivative of the coefficient
                          matrix if the coefficient matrix is non-constant
                          and commutative with its antiderivative. This key
                          may or may not exist.
            9. is_general: Boolean value indicating if the system of ODEs is
                           solvable using one of the general case solvers or not.
            10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This
                     key may or may not exist.
            11. is_higher_order: True if the system passed has an order greater than 1.
                                 This key may or may not exist.
            12. is_second_order: True if the system passed is a second order ODE. This
                                 key may or may not exist.
        This Dict is the answer returned if the eqs are linear and constant
        coefficient. Otherwise, None is returned.

    zDNumber of functions given is not equal to the number of equations %sr   zOdsolve() and classify_sysode() work with functions of one variable only, not %sc              3   (   K   | ]	  }|     y wr;   rM   r<   r>   r   s     r?   r@   z*_classify_linear_system.<locals>.<genexpr>  s     5tuT{5r  r   c              3   .   K   | ]  }|   d k(    yw)r   NrM   rf  s     r?   r@   z*_classify_linear_system.<locals>.<genexpr>  s     /STdq0@/Ss   r   T)is_implicitr7  NF)no_of_equationr=   r>   r   	is_linearr   
is_generalr]   c              3   6   K   | ]  }t        |        y wr;   )r   )r<   A_ru   s     r?   r@   z*_classify_linear_system.<locals>.<genexpr>  s     >R)"a0>rA   r   is_constantr   r   commutative_antiderivativerO  r   is_second_orderr   r!  )r(  r   r   c                 T    | t        j                  | j                  d   | d         k(  S )Nr   r   )r!   jordan_blockr   )r	  s    r?   rq   z)_classify_linear_system.<locals>.<lambda>  s$    a6+>+>qwwqz1T7+S&S rN   r   c              3   4   K   | ]  }|j                     y wr;   )r   )r<   r   s     r?   r@   z*_classify_linear_system.<locals>.<genexpr>  s     :Aq'':s   r  )r   r,  f(t)r   r(  is_higher_order)r   r  re   rE   rB   r2  r:  r   rP   r   r   r   r   r   poprS  rc  r   r   r   jordan_form)rC   rD   ru   is_canonr>   system_orderru  rp  r7  r   r   r   rj  r   rn  r   r*  r   rP  rQ  match_second_orderis_eulerr   	is_jordanrj   r   r,  r   s     `                        @r?   _classify_linear_systemr}  ,  s)   \ 5zSX_bgghh  =tyy>Q 57;< = == C'E5u55L"Q&O"a'SC/SU/S,SO9AN3q1u	y>Q(1uaNEB  $&E
 L  I --T5N
 c((E e>2>>K
 qEl *!Q/*m	*1a15K 	[!#342@E./$+ !VFB!9"b!!DLL+,'+E#$
 #$/'A.HELLO,'$&( ) T	&r"vq1:Ab::u?PYbchijckYl 8//1DAqLLgA*/(d"T U '(G3		+T2#2 c  L # 		s$   ;I+ 1I: +	I76I7:	JJc                 r    g }| D ]/  }|j                  t        |t              r|nt        |d             1 |S r   )rf   rd   r
   r	   )rC   processed_eqsr=   s      r?   _preprocess_eqsr    s?    M L:b(#;RBKL rN   c                     i }i }t        |      }| D ]S  }|j                  j                  t              \  }|j                  j                  t              |hz
  |z  }|||<   |||<   U ||fS r;   )r   r\   r_   r   r]   )rC   rD   eqsorigeqsmapfuncsetr=   f1f2ss           r?   	_eqs2dictr    st    GF%jG ffll<(vv||L)RD0G;r
	
 7?rN   c                     t        |       }| j                         D cg c]  \  }}|D ]  }||f  }}}}||f}|S c c}}}w r;   )r^   r   )r   nodesr  r  f2edgesGs          r?   _dict2graphr    sN    GE%&WWY=='"c=2b"X=X=E=	AH >s   ?c                     | \  }}	 t        |||d      \  \  }}}t        ||      r|j                  ryy# t        t        f$ r Y yw xY w)Nr   FT)r   rP   rG   r   r   )sccru   rC   rD   rP  rQ  r   s          r?   	_is_type1r    s[    JC*3q!<R! 2q!a&6&6 }- s   5 AAc                    t        t        |             D cg c]  \  }}t        ||      s| }}}t               }t        |      D ]J  \  }||dz   d  D ]:  }t	        fd| |   D              s|    | |   z   | |<   |j                         < L t        |       D cg c]  \  }}||vs| } }}| S c c}}w c c}}w )Nr   c              3   F   K   | ]  }|j                             y wr;   )r   )r<   eq2rD   rZ   s     r?   r@   z,_combine_type1_subsystems.<locals>.<genexpr>  s     =37758$=r  )rb  ra   r  r   r   r  )		subsystemrD   ru   rZ   sysindicesremoveipr   s	    ` `     r?   _combine_type1_subsystemsr    s    (Y)>?UVQ9SRSCTqUGUUF7# AA 	A=	!==(|il:	!

1	
 $-Y#7KC1F?KIK V Ls   B=B='C4Cc           
      H   t        | |      \  }}g }t        t        |            D ]i  }|D ci c]  }|||   
 }}t        t        |            }	|	D 
cg c]  }
|
D cg c]  }||   	 c} }}
}t	        ||	|      }|j                  |       k |S c c}w c c}w c c}}
w r;   )r  r3   r  r5   r  rf   )rC   rD   ru   r  r  
subsystemsccfeqsmap_csccsr  r  s               r?   _component_divisionr  &  s    
  U+OFGJ";v#67 %*,-QAvayL--,[-BC:>?3#.Qgaj.?	?-iqA	)$%  ..?s   B	BB*BBc                 .   | d   }| d   }| j                  dd       }| j                  dd       }d| v r| d   n|}| d   }| j                  dd       }| d   }t        ||||||	      }t        ||      D 	
cg c]  \  }	}
t        |	|
       }}	}
|S c c}
}	w )
Nru   r>   r]   r   r   r   ro  r   )r   r   r   r   )getr/  ra   r	   )r   ru   rD   r]   r   r   r   r   r-  r  r   rh   s               r?   _linear_ode_solverr  9  s    c
A&ME
))E4
 C
))E4
 Cu}d!AlA 			.5A#$DQSA"&C1J !$E: 6
712a8
7C
7J 8s   6Bc                     | S r;   rM   )r   s    r?   rq   rq   O  s     rN   c           
          | D ci c]  }|j                   |j                   }}|D cg c]  }t        || ||                c}S c c}w c c}w r;   )r\   r]   r	   )rC   rD   r   rt   eq_dictr  s         r?   _select_equationsr  O  sI    %()quuaee|)G),12qBq'#a&/"22 *2s
   AAc                    | d   }| d   }| d   | d   }| j                  dd      }| j                  dd      }| j                  d	d      }|xr |d
k(  }|xr |dk(  xr d| v }|rWt        ||| j                  dd       | j                  dd       | j                  dd       || j                  dd             \  }	}
nWt        ||||| j                  dd       | j                  dd       | j                  dd       | j                  dd       	      \  }	}
|r| j                  d      |s)t        |	|
D cg c]  }|j	                         c}      }	d }	 |st        |	|
      }|	 t        |	|
      }||S |xr |dk(  }|rdndt        ||fd      }| j                  d	d      r|rL| d   }| d   }|D cg c]5  }t        |j                  |j                  j                  |      |z        7 }}|S |r4| d   | d   }|D cg c]  }|j                  |t                     }}|S |rS| d   }|t        |D cg c]  }|j                   c}      z  }t        ||      D cg c]  \  }}t        ||       }}}|S c c}w # t        $ r d }Y 5w xY w# t        $ r d }Y 7w xY wc c}w c c}w c c}w c c}}w )Nr=   r>   ru   r   r   rO  rp  Fr(  r!  r  r   rP  rQ  r]   r   )rP  rQ  r   r   r   r,  rt  )rD   r   r,  f_tr   r   __r&  c           	           t        t        dj                  | j                  j                                          S )Nz{}{}0)r   r   r   r>   rI   )r   ru   underscoress    r?   rq   z*_higher_order_ode_solver.<locals>.<lambda>  s.    *g(5Yd9e3f*ghi*j rN   r   rR  r   )r  _second_order_to_first_order_higher_order_to_first_orderr  r   _strong_component_solverr   _component_solverr	   r\   r]   r{   r   r!   ra   )r   rC   rD   sysorderr   rp  r(  r{  is_higher_order_type2r^  r\  r  rh   is_second_order_type2g_tr   r   r   r-  ru   r  s                      @@r?   _higher_order_ode_solverr  T  s   
+C&MEc
AW~H99'1Dii 159OYY/7N1$'/H*OtwO3%<9#ua=BYYtT=RW\W`W`aegkWl<AIIeT<RY]=BYYtT=RT
 :#xRW?CuyyQTVZG[>CiiPT>U<AIIc4<PTYT]T]^ceiTjl
 IIdA #G-KAaffQi-KL
C$*7IqAC
 {	#GY:C {
+?($cK
C jlC yy!5) -C,C@CD12aeeQUUZZ3/#56DCD J c
A+C0341166#s1v&4C4 J #c
AVC$8qQUU$899J(+E:(>?12a8?C?JW .L   # 	C	" E 5 %9?sB   5J
J )J =:J1"J6J;
-K JJJ.-J.c                    ddl m}m} t        | ||d      }d }|r||d<   |j	                  dd      rt        |      }n|j	                  dd      rt        |      }|tt        |       d	k(  rf || d   |d   
      }t        | d         j                  }t        t        | d   |d               D cg c]  }t                }	} ||||	      }|g}|S c c}w )Nr   )dsolveconstant_renumberT)rx  ru   ru  Frj  r   )r>   )	variablesnewconstants)sympy.solvers.ode.oder  r  r}  r  r  r  r   r   r   r   r0   r   )
rC   rD   ru   r  r  r   rh   r  r&  new_constantss
             r?   r  r    s    ?#CDAE
C
 c
99&.*51CYY{E*$U+C ;3s8q=QeAh/Cc!f22I.3Ic!feAh4O.PQUWQMQ#C9=YC%C J Rs   1Cc                 Z    | D cg c]  }|j                   j                  d    c}S c c}w r   )r\   re   )rC   r=   s     r?   _get_funcs_from_canonr    s"    %()rBFFKKN)))s    (c                 r   g }| D ]  }||z  }	 t        |      }t        |||      }|r|S g }| D ]z  }|}t        |      }|D cg c]6  }|j                  |D ci c]  }|j                  |j                   c}      8 }}}t        |||      }	|	t        t        d            ||	z  }| |S c c}w c c}}w )NzZ
                The system of ODEs passed cannot be solved by dsolve_system.
            )r  r  r{   r\   r]   r   r6   )
wccru   rC   r  rD   rh   r=   r   comp_eqsscc_sols
             r?   _weak_component_solverr    s    
 C s
!#&E
"3q
1C


C %c* DGGRBGG37aQUUAEE\78GG*8UA>?%j 2 '   	w!$ J 8Gs   B3B.6	B3.B3c                 P    t        | ||      }g }|D ]  }|t        ||      z  } |S r;   )r  r  )rC   rD   ru   
componentsrh   r  s         r?   r  r    s?    $S%3J
C . 	%c1--. JrN   c                 z   |du }|du }	|dk(  r|s|dk(  r|	s	|dk(  r9|s|	r5t        | ||d      \  \  }
}}}|
j                  st        t        d            |dk(  r6t	        |||      }|d   }|j                  dd      }|j                  d	d      }t        j                  |d      }|dk(  r:|t        t        |             }t        ||||      } t        j                  |d
      }|dk(  rD|t        dj                  |            }|}t        |||      \  } }t        j                  |d      }t        | |||      S )a  
    Expects the system to be in second order and in canonical form

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

    Reduces a second order system into a first order one depending on the type of second
    order system.
    1. "type0": If this is passed, then the system will be reduced to first order by
                introducing dummy variables.
    2. "type1": If this is passed, then a particular substitution will be used to reduce the
                the system into first order.
    3. "type2": If this is passed, then the system will be transformed with new dependent
                variables and independent variables. This transformation is a part of solving
                the corresponding system of ODEs.

    `A1` and `A0` are the coefficient matrices from the system and it is assumed that the
    second order system has the form given below:

    .. math::
        A2 * X'' = A1 * X' + A0 * X + b

    Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous
    term.

    Default value for `b` is None but if `A1` and `A0` are passed and `b` is not passed, then the
    system will be assumed homogeneous.

    Nr!  r  r  r   zG
                The system must be in its canonical form.
            r   rP  rQ  r   r   rD   )r   is_Identityr  r6   rS  r  r5  fromkeysr    r   rX  r   r   r_  r  )rC   rD   ru   r   rP  rQ  r   r   is_a1is_a0A2r   	sys_orders                r?   r  r    sM   > $JE$JEEtw5FN.sE1a@Ra~~Z )    v~(R3'(YYtT"YYtT"eQ'Iw9c#hA&r1eQ7MM%+	w:Q(B-b%<
UMM%+	'YGGrN   c                    | |t        | |      st        t        d            |"| |j                  st        t        d            t	        |D cg c]?  } t        t        dj                  |j                  j                                    |      A c}      }|j                  ||      || z  |z  z
  }	|"|j                  s|	|j                         |z  z  }	t        |	||      d   }	|	|fS c c}w )Nzi
            Correctly input for args 'A' and 'f_t' for Linear, Higher Order,
            Type 2
        zN
            Provide the keyword 'P' for matrix P in A = P * J * P-1.
        z{}__0r   )r   r  r6   r   r!   r   r   r   r>   rI   r   r   r:  )
r,  r  rD   ru   	max_orderr   r   r  r\  r^  s
             r?   "_higher_order_type2_to_sub_systemsr  ;  s     	yCK':1a'@ %   	
 	yQ]1+;+; %   	 UZ[PQHw~~affoo'F!GHK[\InnQ	*S1Wy-@@G}Q--1557Q;Wi3A6GI \s   AC0c                    ! |j                         }|dk(  rt        dj                  |            !|D cg c]?  } t        t	        dj                  |j
                  j                                    !      A }}t        fd|D              }t        t        ||            }	t        !      |	|<   t        t	                      fdt        d|dz         D ]  }
  t        !            j                  !|
      !|
z  z  } |      }t        |
dz         D cg c]  }||v r||   nd }}t         !fdt        |      D              ||
z  z  }|	j!                  t        ||      D ci c].  \  }}|j                  ||
      |j#                    !      |      0 c}}        | D cg c]  }|j#                  |	       }}t        ||      D ci c]  \  }}||    }}}t%        ||!      d   }t'        ||!|      S |d	k(  rn|j)                  d
d       }|j)                  dd       }|j)                  dd       }|j)                  dd       }t        fd|D              }t+        |||||||      S g }|D ]#  }|j
                  j                  } t        t	        dj                  |                  |      }|j-                  |       ||i}	g }t        d|         D ]  } t        t	        dj                  ||                  |      }||	|j                  ||      <   |j-                  |       |	|j                  ||dz
           }t/        |j                  |      |      }|j-                  |        | D cg c]  }|j#                  |	       c}|z   } & | |fS c c}w c c}w c c}}w c c}w c c}}w c c}w )Nr!  r   c              3   (   K   | ]	  }|     y wr;   rM   r<   r>   r  s     r?   r@   z/_higher_order_to_first_order.<locals>.<genexpr>\       :D	$:r  c                    t        | t              r/| j                  d   d   }| j                  d   }t        ||      diS t        | t              rB| j                  d   }t         | j                  d         j                               d   }||iS t        | t              rdi }| j                  D ]Q  }t        |t              r|j                   |             +t         |      j                               d   }d||<   S |S y )Nr   r   )	rd   r   re   r0   r   r^   keysr   r   )r   free_symbolr   rk   r   rb   arg _get_coeffs_from_subs_expressions          r?   r  zF_higher_order_to_first_order.<locals>._get_coeffs_from_subs_expressionb  s    $%"iil1oyy|!$4a88$$		!=diilKPPRSTUVu~%$$99 *C!#s+&Fs&KL !%%Ec%J%O%O%Q RST U()u*  %rN   r   r   c              3   Z   K   | ]"  \  }}       j                  |      |z   $ y wr;   )r   )r<   rZ   r   free_functionr   s      r?   r@   z/_higher_order_to_first_order.<locals>.<genexpr>~  s0      +TQ}R055b!<q@ +s   (+r  r  r,  r  r   r   c              3   (   K   | ]	  }|     y wr;   rM   r  s     r?   r@   z/_higher_order_to_first_order.<locals>.<genexpr>  r  r  )r   r   z{}_0z{}_{})r  r   r   r   r   r>   rI   rB   r5  ra   r   r   r   r   sumrb  r   r{   r:  r  r  r  rf   r	   )"rC   r  ru   rD   r   kwargsr  r\  r  	subs_dictr   r   
coeff_dictr   rb   expr_to_subsnfr=   r^  new_sys_orderr,  r  r   r   	prev_func	func_namer>   rZ   new_funcprev_fnew_eqr  r  r   s"    `                             @@@r?   r  r  T  s   }  wELLO$QVWACXeELL$ABCBGW	W:E::	UI./	2w	! )	0 q)a-( 	CA R)..r15b!e;D9$?JSXYZ]^Y^S_`%5J+>j'AE`F` +!&)+ +-.T2L+.ui+@B"'!R  ffQlL,=,=mB>OQS,TT B C	C 144"2779%447:5)7LMeaYq\)MM )R8;+G]BiXX
 wJJsD!jj%JJsD!JJsD!:E::	1!S%IQRVWXX I ;	NN++	8xfmmI678;%	q)I./ 	#ADxgnnY&B CDQGH.6IinnQ*+X&y~~a156FA1FNN6"	# -00brwwy!07:!;$ 	>i XD aB 5MR 1s$   AN1!N633N;4OOOc                 T   ddl m}m}m} t	        |       st        t        d            t        |       } |$t        |t              st        t        d            | ||       }t        d |D              rt        t        d            t        |       t        |      k7  rt        t        d            |$t        |t              st        t        d	            |Ct        t        | d   j                  t                    d   j                  t                    d   }g }	t        | ||      }
|
D ]0  }	 t!        |||      }|t%        |||      }|	j'                  |       2 |	rg }t)        |  j*                  }|	D ]  }t-        ||      } |||
      }|r>t)        | j*                  |z
  } |||||      }|D cg c]  }|j/                  |       }}|r%t)        | j*                  |z
  }t1        ||g||      }|j'                  |        |}	|	S # t"        $ r d}Y w xY wc c}w )aS  
    Solves any(supported) system of Ordinary Differential Equations

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

    This function takes a system of ODEs as an input, determines if the
    it is solvable by this function, and returns the solution if found any.

    This function can handle:
    1. Linear, First Order, Constant coefficient homogeneous system of ODEs
    2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs
    3. Linear, First Order, non-constant coefficient homogeneous system of ODEs
    4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs
    5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms
    6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above.

    The types of systems described above are not limited by the number of equations, i.e. this
    function can solve the above types irrespective of the number of equations in the system passed.
    But, the bigger the system, the more time it will take to solve the system.

    This function returns a list of solutions. Each solution is a list of equations where LHS is
    the dependent variable and RHS is an expression in terms of the independent variable.

    Among the non constant coefficient types, not all the systems are solvable by this function. Only
    those which have either a coefficient matrix with a commutative antiderivative or those systems which
    may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative.

    Parameters
    ==========

    eqs : List
        system of ODEs to be solved
    funcs : List or None
        List of dependent variables that make up the system of ODEs
    t : Symbol or None
        Independent variable in the system of ODEs
    ics : Dict or None
        Set of initial boundary/conditions for the system of ODEs
    doit : Boolean
        Evaluate the solutions if True. Default value is True. Can be
        set to false if the integral evaluation takes too much time and/or
        is not required.
    simplify: Boolean
        Simplify the solutions for the systems. Default value is True.
        Can be set to false if simplification takes too much time and/or
        is not required.

    Examples
    ========

    >>> from sympy import symbols, Eq, Function
    >>> from sympy.solvers.ode.systems import dsolve_system
    >>> f, g = symbols("f g", cls=Function)
    >>> x = symbols("x")

    >>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))]
    >>> dsolve_system(eqs)
    [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]

    You can also pass the initial conditions for the system of ODEs:

    >>> dsolve_system(eqs, ics={f(0): 1, g(0): 0})
    [[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]]

    Optionally, you can pass the dependent variables and the independent
    variable for which the system is to be solved:

    >>> funcs = [f(x), g(x)]
    >>> dsolve_system(eqs, funcs=funcs, t=x)
    [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]

    Lets look at an implicit system of ODEs:

    >>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))]
    >>> dsolve_system(eqs)
    [[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]]

    Returns
    =======

    List of List of Equations

    Raises
    ======

    NotImplementedError
        When the system of ODEs is not solvable by this function.
    ValueError
        When the parameters passed are not in the required form.

    r   )	solve_ics_extract_funcsr  zQ
            List of equations should be passed. The input is not valid.
        NzG
            Input to the funcs should be a list of functions.
        c              3   L   K   | ]  }t        |j                        d k7    yw)r   N)r   re   )r<   r>   s     r?   r@   z dsolve_system.<locals>.<genexpr>   s     
143tyy>Q
1s   "$zn
            dsolve_system can solve a system of ODEs with only one independent
            variable.
        zN
            Number of equations and number of functions do not match
        zE
            The independent variable must be of type Symbol
        )r  )r   )r  r  r  r  r4   r  r6   r  rd   r^   r   r   r   r_   r   r:  r  r   r  rf   r   r   r  r{   r   )rC   rD   ru   icsr   r-   r  r  r  solsr7  canon_eqrh   
final_solsr  	constantssolved_constantsr   s                     r?   dsolve_systemr    s\   z SRC= %   	 #
CE4!8 %   	 }s#

15
11 %   	
 3x3u: %   	 	}Z62 %   	 	yc!fll:./288@A!DDsE1-I 		*8UA>C ;#HeQ7CC	 
3K,,	 	#C#C/C#C9=C!3K44y@	#,S%C#H 9<=Aqvv./==!3K44y@	cA3	=c"	#  K= # 	C	( >s   6H<H%H"!H")Tr;   )NNr  FN)F)r  NNNN)NN)NrO  )NNNFT)s
sympy.corer   r   r   sympy.core.containersr   sympy.core.exprtoolsr   sympy.core.numbersr   sympy.core.relationalr	   r
   sympy.core.sortingr   r   sympy.core.symbolr   r   sympy.core.functionr   r   r   r   r   r   sympy.functionsr   r   r   r   r   r   r   r   r   (sympy.functions.combinatorial.factorialsr   sympy.matricesr    r!   r"   r#   r$   sympy.polysr%   r&   sympy.simplifyr'   r(   r)   sympy.simplify.powsimpr*   r+   sympy.simplify.ratsimpr,   sympy.simplify.simplifyr-   sympy.sets.setsr.   sympy.solvers.deutilsr0   r   r1   r2   sympy.utilities.iterablesr3   r4   r5   sympy.utilities.miscr6   sympy.integrals.integralsr7   r8   rE   r  rG   rP   rm   rx   r   r   r   r   r   r   r/  r   r:  r   r   rK  rD  rS  rX  r_  rc  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rM   rN   r?   <module>r	     sz   " " ' -   . 8 +? ?8 8 8 > O O & 5 5 5 * , % + ;F F + 9L	J 	
	 	
 ,Dm`6RjHVsn 9>|~	J
EP0f :!H7t'T^CJ		&, '2 3
FX@*
"L
 AE59@HF2[|erN   