a
    RG5dX                     @   s   d dl mZ d dlmZmZmZ d dlmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZ dd	 Zd
d Zdd Zdd Zdd Zdd Zdd ZefddZdd Zd&ddZd'ddZd(d!d"Zd)d$d%ZdS )*    )
expand_mul)Dummyuniquely_named_symbolsymbols)numbered_symbols   )
ShapeErrorNonSquareMatrixErrorNonInvertibleMatrixError)_fuzzy_positive_definite)_get_intermediate_simp_iszeroc                    s@      stdj jkr$td jj fddS )a  Solves ``Ax = B`` efficiently, where A is a diagonal Matrix,
    with non-zero diagonal entries.

    Examples
    ========

    >>> from sympy import Matrix, eye
    >>> A = eye(2)*2
    >>> B = Matrix([[1, 2], [3, 4]])
    >>> A.diagonal_solve(B) == B/2
    True

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv_solve
    zMatrix should be diagonalzSize mis-matchc                    s   | |f  | | f  S N )ijMrhsr   R/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/matrices/solvers.py<lambda>*       z!_diagonal_solve.<locals>.<lambda>)is_diagonal	TypeErrorrows_newcolsr   r   r   r   _diagonal_solve
   s    r   c              	      s   ddl m}  jstd|j jkr.td js<tdt }|	 j|j
t|j
D ]pt jD ]` f dkrtd||f t fdd	tD   f  f< qjq\ S )
Solves ``Ax = B``, where A is a lower triangular matrix.

    See Also
    ========

    upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv_solve
    r   MutableDenseMatrixMatrix must be square.Matrices size mismatch. Matrix must be lower triangular.r   Matrix must be non-singular.c                 3   s&   | ]} |f |f  V  qd S r   r   .0kr   Xr   r   r   r   	<genexpr>N   s   z*_lower_triangular_solve.<locals>.<genexpr>)denser    	is_squarer	   r   r   is_lower
ValueErrorr   zerosr   ranger   sumr   r   r   r    dpsr   r(   r   _lower_triangular_solve-   s&    
r4   c           	   
   C   s   | j std|j| jkr"td| js0tdt }dd t| jD }|  D ]$\}}}||krR|| 	||f qR|
 }t|jD ]j}t|jD ]Z}|| D ](\}}|||f  ||||f  8  < q||||f | ||f  |||f< qq| |S )r   r!   r"   r#   c                 S   s   g | ]}g qS r   r   r&   r   r   r   r   
<listcomp>k   r   z2_lower_triangular_solve_sparse.<locals>.<listcomp>)r,   r	   r   r   r-   r.   r   r0   row_listappend
as_mutabler   r   	r   r   r3   r   r   r   vr)   ur   r   r   _lower_triangular_solve_sparseS   s$    "(r=   c              	      s   ddl m}  jstd|j jkr.td js<tdt }|	 j|j
t|j
D ]|tt jD ]h f dkrtd||f t fdd	td  jD   f  f< qnq\ S )
Solves ``Ax = B``, where A is an upper triangular matrix.

    See Also
    ========

    lower_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv_solve
    r   r   r!   Matrix size mismatch.Matrix is not upper triangular.r   r$   c                 3   s&   | ]} |f |f  V  qd S r   r   r%   r(   r   r   r*      s   z*_upper_triangular_solve.<locals>.<genexpr>)r+   r    r,   r	   r   r   is_upperr   r   r/   r   r0   reversedr.   r1   r   r2   r   r(   r   _upper_triangular_solve}   s&    
rC   c           	   
   C   s  | j std|j| jkr"td| js0tdt }dd t| jD }|  D ]$\}}}||k rR|| 	||f qR|
 }t|jD ]r}tt|jD ]^}t|| D ](\}}|||f  ||||f  8  < q||||f | ||f  |||f< qq| |S )r>   r!   r?   r@   c                 S   s   g | ]}g qS r   r   r5   r   r   r   r6      r   z2_upper_triangular_solve_sparse.<locals>.<listcomp>)r,   r	   r   r   rA   r   r   r0   r7   r8   r9   r   rB   r   r:   r   r   r   _upper_triangular_solve_sparse   s$    "(rD   c                 C   s   | j | jk rtdd}d}|  r*d}n
| js4d}|sDt| du rh| j}|| } ||}|   }| j|d}|	|}|r|j
|S |j
|S dS )a  Solves ``Ax = B`` using Cholesky decomposition,
    for a general square non-singular matrix.
    For a non-square matrix with rows > cols,
    the least squares solution is returned.

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    diagonal_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv_solve
    6Under-determined System. Try M.gauss_jordan_solve(rhs)TF	hermitianN)r   r   NotImplementedErroris_symmetricis_hermitianr   Hmultiplycholeskylower_triangular_solveupper_triangular_solveT)r   r   rG   reformrK   LYr   r   r   _cholesky_solve   s(    



rT   c           	      C   s   | j | jk rtdd}d}|  r*d}n
| js4d}|sDt| du rh| j}|| } ||}|   }| j|d\}}|	|}|
|}|r|j|S |j|S dS )a  Solves ``Ax = B`` using LDL decomposition,
    for a general square and non-singular matrix.

    For a non-square matrix with rows > cols,
    the least squares solution is returned.

    Examples
    ========

    >>> from sympy import Matrix, eye
    >>> A = eye(2)*2
    >>> B = Matrix([[1, 2], [3, 4]])
    >>> A.LDLsolve(B) == B/2
    True

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.LDLdecomposition
    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LUsolve
    QRsolve
    pinv_solve
    rE   TFrF   N)r   r   rH   rI   rJ   r   rK   rL   LDLdecompositionrN   diagonal_solverO   rP   )	r   r   rG   rQ   rK   rR   DrS   Zr   r   r   	_LDLsolve   s*    




rY   c           
   	      s  |j | j krtd| j }| j}||k r0tdz| jtdd\}}W n ty`   tdY n0 t  |	|
 }t|D ]<}tt||D ](}	|||	f |||	 fdd qq~||krt||D ],}t|jD ]}	||||	f stdqq|d	|d
d
f }t|d ddD ]b}t|d |D ]*}	|||	f |||	 fdd q4|||f || fdd q"||S )a  Solve the linear system ``Ax = rhs`` for ``x`` where ``A = M``.

    This is for symbolic matrices, for real or complex ones use
    mpmath.lu_solve or mpmath.qr_solve.

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    QRsolve
    pinv_solve
    LUdecomposition
    z4``M`` and ``rhs`` must have the same number of rows.z&Underdetermined systems not supported.T)
iszerofunc	rankcheck Matrix det == 0; not invertible.c                    s    | |  S r   r   xyr3   scaler   r   r   `  r   z_LUsolve.<locals>.<lambda>zThe system is inconsistent.r   Nr   c                    s    | |  S r   r   r]   r`   r   r   r   o  r   c                    s    |  S r   r   )r^   _r`   r   r   r   r  r   )r   r   r   rH   LUdecomposition_Simpler   r.   r
   r   permute_rowsr9   r0   minZ
zip_row_opZrow_op	__class__)
r   r   rZ   mnApermbr   r   r   r`   r   _LUsolve5  sB    
rm   c                 C   s   t tt}|  \}}|j| }g }|j}t|d ddD ]f}||ddf }	t|d |D ]$}
|	|||
f ||d |
   8 }	q\||	}	||	|||f   q:| j|ddd  S )a  Solve the linear system ``Ax = b``.

    ``M`` is the matrix ``A``, the method argument is the vector
    ``b``.  The method returns the solution vector ``x``.  If ``b`` is a
    matrix, the system is solved for each column of ``b`` and the
    return value is a matrix of the same shape as ``b``.

    This method is slower (approximately by a factor of 2) but
    more stable for floating-point arithmetic than the LUsolve method.
    However, LUsolve usually uses an exact arithmetic, so you do not need
    to use QRsolve.

    This is mainly for educational purposes and symbolic matrices, for real
    (or complex) matrices use mpmath.qr_solve.

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    LUsolve
    pinv_solve
    QRdecomposition
    r   rb   N)r   r   QRdecompositionrP   r   r0   r8   vstack)r   rl   r3   QRr_   r^   ri   r   tmpr'   r   r   r   _QRsolvew  s    

"rs   Fc                    s  ddl m}m} | j}| |  | }|j}|ddd| f j\} |jdd\}	|	ddd| f |	dd| df  }	}
t	t
 fddt}fdd	t|	jD }|| j}|
|dddf jstd
td|dd dd dj}t||fdd	t | | D  | |}|	d||f }|
d|ddf }||||  |}| |}t D ]&}||ddf ||| ddf< q|||| }}|r|||fS ||fS dS )a!  
    Solves ``Ax = B`` using Gauss Jordan elimination.

    There may be zero, one, or infinite solutions.  If one solution
    exists, it will be returned. If infinite solutions exist, it will
    be returned parametrically. If no solutions exist, It will throw
    ValueError.

    Parameters
    ==========

    B : Matrix
        The right hand side of the equation to be solved for.  Must have
        the same number of rows as matrix A.

    freevar : boolean, optional
        Flag, when set to `True` will return the indices of the free
        variables in the solutions (column Matrix), for a system that is
        undetermined (e.g. A has more columns than rows), for which
        infinite solutions are possible, in terms of arbitrary
        values of free variables. Default `False`.

    Returns
    =======

    x : Matrix
        The matrix that will satisfy ``Ax = B``.  Will have as many rows as
        matrix A has columns, and as many columns as matrix B.

    params : Matrix
        If the system is underdetermined (e.g. A has more columns than
        rows), infinite solutions are possible, in terms of arbitrary
        parameters. These arbitrary parameters are returned as params
        Matrix.

    free_var_index : List, optional
        If the system is underdetermined (e.g. A has more columns than
        rows), infinite solutions are possible, in terms of arbitrary
        values of free variables. Then the indices of the free variables
        in the solutions (column Matrix) are returned by free_var_index,
        if the flag `freevar` is set to `True`.

    Examples
    ========

    >>> from sympy import Matrix
    >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
    >>> B = Matrix([7, 12, 4])
    >>> sol, params = A.gauss_jordan_solve(B)
    >>> sol
    Matrix([
    [-2*tau0 - 3*tau1 + 2],
    [                 tau0],
    [           2*tau1 + 5],
    [                 tau1]])
    >>> params
    Matrix([
    [tau0],
    [tau1]])
    >>> taus_zeroes = { tau:0 for tau in params }
    >>> sol_unique = sol.xreplace(taus_zeroes)
    >>> sol_unique
        Matrix([
    [2],
    [0],
    [5],
    [0]])


    >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
    >>> B = Matrix([3, 6, 9])
    >>> sol, params = A.gauss_jordan_solve(B)
    >>> sol
    Matrix([
    [-1],
    [ 2],
    [ 0]])
    >>> params
    Matrix(0, 1, [])

    >>> A = Matrix([[2, -7], [-1, 4]])
    >>> B = Matrix([[-21, 3], [12, -2]])
    >>> sol, params = A.gauss_jordan_solve(B)
    >>> sol
    Matrix([
    [0, -2],
    [3, -1]])
    >>> params
    Matrix(0, 2, [])


    >>> from sympy import Matrix
    >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
    >>> B = Matrix([7, 12, 4])
    >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True)
    >>> sol
    Matrix([
    [-2*tau0 - 3*tau1 + 2],
    [                 tau0],
    [           2*tau1 + 5],
    [                 tau1]])
    >>> params
    Matrix([
    [tau0],
    [tau1]])
    >>> freevars
    [1, 3]


    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv

    References
    ==========

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

    r   )Matrixr/   NT)simplifyc                    s   |  k S r   r   )p)colr   r   r   7  r   z%_gauss_jordan_solve.<locals>.<lambda>c                    s   g | ]}| vr|qS r   r   )r&   c)pivotsr   r   r6   <  r   z'_gauss_jordan_solve.<locals>.<listcomp>zLinear system has no solutiontauc                 S   s   t | dS )N
1234567890)strrstrip)r   r   r   r   r   I  r   c                 S   s   d|  S )Nrc   r   )sr   r   r   r   J  r   )comparemodifyc                    s   g | ]}t  qS r   )nextr%   )genr   r   r6   L  r   )sympy.matricesrt   r/   rg   hstackcopyr   shaperreflistfilterlenr0   rP   is_zero_matrixr.   r   namer   reshapero   )r   Bfreevarrt   r/   clsaugZB_colsrowrj   r;   rankZfree_var_indexpermutationr   rz   VvtZfree_solsolr'   r   )rw   r   ry   r   _gauss_jordan_solve  s@     ."
$
r   Nc           	      C   sv   ddl m} | }|  }|du rR|j|j }}td||td}| |||j}|	|||j|	| 	| S )a	  Solve ``Ax = B`` using the Moore-Penrose pseudoinverse.

    There may be zero, one, or infinite solutions.  If one solution
    exists, it will be returned.  If infinite solutions exist, one will
    be returned based on the value of arbitrary_matrix.  If no solutions
    exist, the least-squares solution is returned.

    Parameters
    ==========

    B : Matrix
        The right hand side of the equation to be solved for.  Must have
        the same number of rows as matrix A.
    arbitrary_matrix : Matrix
        If the system is underdetermined (e.g. A has more columns than
        rows), infinite solutions are possible, in terms of an arbitrary
        matrix.  This parameter may be set to a specific matrix to use
        for that purpose; if so, it must be the same shape as x, with as
        many rows as matrix A has columns, and as many columns as matrix
        B.  If left as None, an appropriate matrix containing dummy
        symbols in the form of ``wn_m`` will be used, with n and m being
        row and column position of each symbol.

    Returns
    =======

    x : Matrix
        The matrix that will satisfy ``Ax = B``.  Will have as many rows as
        matrix A has columns, and as many columns as matrix B.

    Examples
    ========

    >>> from sympy import Matrix
    >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
    >>> B = Matrix([7, 8])
    >>> A.pinv_solve(B)
    Matrix([
    [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18],
    [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9],
    [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]])
    >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0]))
    Matrix([
    [-55/18],
    [   1/9],
    [ 59/18]])

    See Also
    ========

    sympy.matrices.dense.DenseMatrix.lower_triangular_solve
    sympy.matrices.dense.DenseMatrix.upper_triangular_solve
    gauss_jordan_solve
    cholesky_solve
    diagonal_solve
    LDLsolve
    LUsolve
    QRsolve
    pinv

    Notes
    =====

    This may return either exact solutions or least squares solutions.
    To determine which, check ``A * A.pinv() * B == B``.  It will be
    True if exact solutions exist, and False if only a least-squares
    solution exists.  Be aware that the left hand side of that equation
    may need to be simplified to correctly compare to the right hand
    side.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system

    r   )eyeNzw:{}_:{})r   )
r   r   pinvr   r   formatr   rg   rP   rL   )	r   r   arbitrary_matrixr   rj   ZA_pinvr   r   wr   r   r   _pinv_solveb  s    Nr   GJc                 C   s   |dv rFz|  |\}}|r$tdW n ty@   tdY n0 |S |dkrX| |S |dkrj| |S |dkr|| |S |dkr| |S |dkr| |S | j|d		|S d
S )a  Solves linear equation where the unique solution exists.

    Parameters
    ==========

    rhs : Matrix
        Vector representing the right hand side of the linear equation.

    method : string, optional
        If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be
        used, which is implemented in the routine ``gauss_jordan_solve``.

        If set to ``'LU'``, ``LUsolve`` routine will be used.

        If set to ``'QR'``, ``QRsolve`` routine will be used.

        If set to ``'PINV'``, ``pinv_solve`` routine will be used.

        It also supports the methods available for special linear systems

        For positive definite systems:

        If set to ``'CH'``, ``cholesky_solve`` routine will be used.

        If set to ``'LDL'``, ``LDLsolve`` routine will be used.

        To use a different method and to compute the solution via the
        inverse, use a method defined in the .inv() docstring.

    Returns
    =======

    solutions : Matrix
        Vector representing the solution.

    Raises
    ======

    ValueError
        If there is not a unique solution then a ``ValueError`` will be
        raised.

        If ``M`` is not square, a ``ValueError`` and a different routine
        for solving the system will be suggested.
    )r   GEzcMatrix det == 0; not invertible. Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.r\   ZLUCHQRLDLPINVmethodN)
gauss_jordan_solver
   r.   LUsolvecholesky_solveQRsolveLDLsolve
pinv_solveinvrL   )r   r   r   solnparamr   r   r   _solve  s&    /




r   r   c                 C   sh   |dkr|  |S |dkr$| |S |dkr6| |S |dkrH| |S | j}||  j|| |dS dS )a4  Return the least-square fit to the data.

    Parameters
    ==========

    rhs : Matrix
        Vector representing the right hand side of the linear equation.

    method : string or boolean, optional
        If set to ``'CH'``, ``cholesky_solve`` routine will be used.

        If set to ``'LDL'``, ``LDLsolve`` routine will be used.

        If set to ``'QR'``, ``QRsolve`` routine will be used.

        If set to ``'PINV'``, ``pinv_solve`` routine will be used.

        Otherwise, the conjugate of ``M`` will be used to create a system
        of equations that is passed to ``solve`` along with the hint
        defined by ``method``.

    Returns
    =======

    solutions : Matrix
        Vector representing the solution.

    Examples
    ========

    >>> from sympy import Matrix, ones
    >>> A = Matrix([1, 2, 3])
    >>> B = Matrix([2, 3, 4])
    >>> S = Matrix(A.row_join(B))
    >>> S
    Matrix([
    [1, 2],
    [2, 3],
    [3, 4]])

    If each line of S represent coefficients of Ax + By
    and x and y are [2, 3] then S*xy is:

    >>> r = S*Matrix([2, 3]); r
    Matrix([
    [ 8],
    [13],
    [18]])

    But let's add 1 to the middle value and then solve for the
    least-squares value of xy:

    >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
    Matrix([
    [ 5/3],
    [10/3]])

    The error is given by S*xy - r:

    >>> S*xy - r
    Matrix([
    [1/3],
    [1/3],
    [1/3]])
    >>> _.norm().n(2)
    0.58

    If a different xy is used, the norm will be higher:

    >>> xy += ones(2, 1)/10
    >>> (S*xy - r).norm().n(2)
    1.5

    r   r   r   r   r   N)r   r   r   r   rK   solve)r   r   r   tr   r   r   _solve_least_squares  s    L



r   )F)N)r   )r   )sympy.core.functionr   sympy.core.symbolr   r   r   sympy.utilities.iterablesr   commonr   r	   r
   eigenr   	utilitiesr   r   r   r4   r=   rC   rD   rT   rY   rm   rs   r   r   r   r   r   r   r   r   <module>   s&   #&*&*.:B5
 7
\
J