
    EdN                        d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
mZ d dlmZ d dlmZ d d	lmZ d
dlmZ d
dlmZmZ d
dlmZ d
dlmZmZ d
dlmZmZ d Z G d de          Z d Z! G d de e          Z"e"xZ#Z$e%fdZ&e%fdZ'd Z(d Z)d Z* ed          d             Z+d0dZ,d  Z-dd!d"d#Z.d1d$Z/d2d&Z0d' Z1d( Z2d) Z3	 	 d3d,Z4d4d.Z5d/ Z6dS )5    N)Basic)S)Symbolsympify)cossin)doctest_depends_on)sympy_deprecation_warning)is_sequence   )
ShapeError)	_cholesky_LDLdecomposition)
MatrixBase)MutableRepMatrix	RepMatrix)_lower_triangular_solve_upper_triangular_solvec                     | j         S )zReturns True if x is zero.)is_zero)xs    4lib/python3.11/site-packages/sympy/matrices/dense.py_iszeror      s
    9    c                       e Zd ZdZdZdZdZed             Zd Z	d Z
d Zdd
ZddZd Zd Zej        e_        ej        e_        ej        e_        ej        e_        dS )DenseMatrixzJMatrix implementation based on DomainMatrix as the internal representationFgQ$@   c                 N    t          ddd           |                                 S )Nzy
            The private _mat attribute of Matrix is deprecated. Use the
            .flat() method instead.
            z1.9z$deprecated-private-matrix-attributes)deprecated_since_versionactive_deprecations_target)r   flatselfs    r   _matzDenseMatrix._mat&   s6    ! &+'M	
 	
 	
 	
 yy{{r   c                     |                      |                    dd          |                    dt                    |                    dd                    S )NmethodGE
iszerofunctry_block_diagF)r'   r)   r*   )invgetr   )r$   kwargss     r   _eval_inversezDenseMatrix._eval_inverse3   sS    xxvzz(D99#)::lG#D#D'-zz2BE'J'J  L L 	Lr   c                 f    ddl m} |                    | j                                                  S )z4Returns an Immutable version of this Matrix
        r   )ImmutableDenseMatrix)	immutabler0   _fromrep_repcopy)r$   clss     r   as_immutablezDenseMatrix.as_immutable8   s4     	;:::::||DINN,,---r   c                      t          |           S )aB  Returns a mutable version of this matrix

        Examples
        ========

        >>> from sympy import ImmutableMatrix
        >>> X = ImmutableMatrix([[1, 2], [3, 4]])
        >>> Y = X.as_mutable()
        >>> Y[1, 1] = 5 # Can set values in Y
        >>> Y
        Matrix([
        [1, 2],
        [3, 5]])
        )Matrixr#   s    r   
as_mutablezDenseMatrix.as_mutable>   s     d||r   Tc                 $    t          | |          S N)	hermitian)r   r$   r<   s     r   choleskyzDenseMatrix.choleskyO   s    3333r   c                 $    t          | |          S r;   )r   r=   s     r   LDLdecompositionzDenseMatrix.LDLdecompositionR   s     ;;;;r   c                 "    t          | |          S N)r   r$   rhss     r   lower_triangular_solvez"DenseMatrix.lower_triangular_solveU       &tS111r   c                 "    t          | |          S rB   )r   rC   s     r   upper_triangular_solvez"DenseMatrix.upper_triangular_solveX   rF   r   NT)__name__
__module____qualname____doc__is_MatrixExpr_op_priority_class_prioritypropertyr%   r.   r6   r9   r>   r@   rE   rH   r   r   r   r    r   r   r   r      s        TT MLO
 
 X
L L L
. . .  "4 4 4 4< < < <2 2 22 2 2 &/%6H%6%>%<%D"%<%D"""r   r   c                 2   t          | dd          r|                                 S t          | t                    r| S t	          | d          rJ|                                 }t          |j                  dk    rt          |          S t          |           S | S )z0Return a matrix as a Matrix, otherwise return x.	is_MatrixF	__array__r   )
getattrr9   
isinstancer   hasattrrU   lenshaper   r8   )r   as     r   _force_mutabler\   a   s    q+u%% ||~~	Au		 	K	 	  KKMMqw<<1 	1::ayyHr   c                       e Zd Zd ZdS )MutableDenseMatrixc                     ddl m} |                                                                 D ]\  \  }}} ||fi || ||f<   dS )zApplies simplify to the elements of a matrix in place.

        This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))

        See Also
        ========

        sympy.simplify.simplify.simplify
        r   )simplifyN)sympy.simplify.simplifyr`   todokitems)r$   r-   	_simplifyijelements         r   r`   zMutableDenseMatrix.simplifyq   sm     	BAAAAA#zz||1133 	6 	6OFQG"755f55DAJJ	6 	6r   N)rJ   rK   rL   r`   rR   r   r   r^   r^   o   s#        6 6 6 6 6r   r^   c                 x    ddl m}  |t          |           |          }t          |           D ]
\  }}|||<   |S )zmConverts Python list of SymPy expressions to a NumPy array.

    See Also
    ========

    matrix2numpy
    r   empty)numpyrj   rY   	enumerate)ldtyperj   r[   re   ss         r   
list2numpyrp      sV     c!ffeA!  1!Hr   c                     ddl m}  || j        |          }t          | j                  D ](}t          | j                  D ]}| ||f         |||f<   )|S )zYConverts SymPy's matrix to a NumPy array.

    See Also
    ========

    list2numpy
    r   ri   )rk   rj   rZ   rangerowscols)mrn   rj   r[   re   rf   s         r   matrix2numpyrv      sx     aguA16]]  qv 	 	A1gAadGG	Hr   c                 t    t          |           }t          |           }||df| |dfdf}t          |          S )a  Returns a rotation matrix for a rotation of theta (in radians) about
    the 3-axis.

    Examples
    ========

    >>> from sympy import pi, rot_axis3

    A rotation of pi/3 (60 degrees):

    >>> theta = pi/3
    >>> rot_axis3(theta)
    Matrix([
    [       1/2, sqrt(3)/2, 0],
    [-sqrt(3)/2,       1/2, 0],
    [         0,         0, 1]])

    If we rotate by pi/2 (90 degrees):

    >>> rot_axis3(pi/2)
    Matrix([
    [ 0, 1, 0],
    [-1, 0, 0],
    [ 0, 0, 1]])

    See Also
    ========

    rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
        about the 1-axis
    rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
        about the 2-axis
    r   )r   r   r   r   r	   r8   thetactstlils       r   	rot_axis3r~      sG    D 
UB	UBA;CQ<C #;;r   c                 t    t          |           }t          |           }|d| fd|d|ff}t          |          S )a  Returns a rotation matrix for a rotation of theta (in radians) about
    the 2-axis.

    Examples
    ========

    >>> from sympy import pi, rot_axis2

    A rotation of pi/3 (60 degrees):

    >>> theta = pi/3
    >>> rot_axis2(theta)
    Matrix([
    [      1/2, 0, -sqrt(3)/2],
    [        0, 1,          0],
    [sqrt(3)/2, 0,        1/2]])

    If we rotate by pi/2 (90 degrees):

    >>> rot_axis2(pi/2)
    Matrix([
    [0, 0, -1],
    [0, 1,  0],
    [1, 0,  0]])

    See Also
    ========

    rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
        about the 1-axis
    rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
        about the 3-axis
    r   )r   r   r   rx   ry   s       r   	rot_axis2r      sG    D 
UB	UBB3<2;C #;;r   c                 t    t          |           }t          |           }dd||fd| |ff}t          |          S )a  Returns a rotation matrix for a rotation of theta (in radians) about
    the 1-axis.

    Examples
    ========

    >>> from sympy import pi, rot_axis1

    A rotation of pi/3 (60 degrees):

    >>> theta = pi/3
    >>> rot_axis1(theta)
    Matrix([
    [1,          0,         0],
    [0,        1/2, sqrt(3)/2],
    [0, -sqrt(3)/2,       1/2]])

    If we rotate by pi/2 (90 degrees):

    >>> rot_axis1(pi/2)
    Matrix([
    [1,  0, 0],
    [0,  0, 1],
    [0, -1, 0]])

    See Also
    ========

    rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
        about the 2-axis
    rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
        about the 3-axis
    )r   r   r   r   rx   ry   s       r   	rot_axis1r      sG    D 
UB	UBr2;sB<C #;;r   )rk   )modulesc                     ddl m}m}  ||t                    } ||          D ]=}t	          | dd                    t          t          |                    fi |||<   >|S )aI  Create a numpy ndarray of symbols (as an object array).

    The created symbols are named ``prefix_i1_i2_``...  You should thus provide a
    non-empty prefix if you want your symbols to be unique for different output
    arrays, as SymPy symbols with identical names are the same object.

    Parameters
    ----------

    prefix : string
      A prefix prepended to the name of every symbol.

    shape : int or tuple
      Shape of the created array.  If an int, the array is one-dimensional; for
      more than one dimension the shape must be a tuple.

    \*\*kwargs : dict
      keyword arguments passed on to Symbol

    Examples
    ========
    These doctests require numpy.

    >>> from sympy import symarray
    >>> symarray('', 3)
    [_0 _1 _2]

    If you want multiple symarrays to contain distinct symbols, you *must*
    provide unique prefixes:

    >>> a = symarray('', 3)
    >>> b = symarray('', 3)
    >>> a[0] == b[0]
    True
    >>> a = symarray('a', 3)
    >>> b = symarray('b', 3)
    >>> a[0] == b[0]
    False

    Creating symarrays with a prefix:

    >>> symarray('a', 3)
    [a_0 a_1 a_2]

    For more than one dimension, the shape must be given as a tuple:

    >>> symarray('a', (2, 3))
    [[a_0_0 a_0_1 a_0_2]
     [a_1_0 a_1_1 a_1_2]]
    >>> symarray('a', (2, 3, 2))
    [[[a_0_0_0 a_0_0_1]
      [a_0_1_0 a_0_1_1]
      [a_0_2_0 a_0_2_1]]
    <BLANKLINE>
     [[a_1_0_0 a_1_0_1]
      [a_1_1_0 a_1_1_1]
      [a_1_2_0 a_1_2_1]]]

    For setting assumptions of the underlying Symbols:

    >>> [s.is_real for s in symarray('a', 2, real=True)]
    [True, True]
    r   )rj   ndindex)rn   _)rk   rj   r   objectr   joinmapstr)prefixrZ   r-   rj   r   arrindexs          r   symarrayr   %  s    B %$$$$$$$
%V
$
$
$C & &vvvsxxC/H/H/HI & &$& &E

Jr   Tc                      t          t          t                                |s fd}n fd}t                     }t	          |||                                          S )aY  Given linear difference operator L of order 'k' and homogeneous
       equation Ly = 0 we want to compute kernel of L, which is a set
       of 'k' sequences: a(n), b(n), ... z(n).

       Solutions of L are linearly independent iff their Casoratian,
       denoted as C(a, b, ..., z), do not vanish for n = 0.

       Casoratian is defined by k x k determinant::

                  +  a(n)     b(n)     . . . z(n)     +
                  |  a(n+1)   b(n+1)   . . . z(n+1)   |
                  |    .         .     .        .     |
                  |    .         .       .      .     |
                  |    .         .         .    .     |
                  +  a(n+k-1) b(n+k-1) . . . z(n+k-1) +

       It proves very useful in rsolve_hyper() where it is applied
       to a generating set of a recurrence to factor out linearly
       dependent solutions and return a basis:

       >>> from sympy import Symbol, casoratian, factorial
       >>> n = Symbol('n', integer=True)

       Exponential and factorial are linearly independent:

       >>> casoratian([2**n, factorial(n)], n) != 0
       True

    c                 B    |                              | z             S rB   subsre   rf   nseqss     r   <lambda>zcasoratian.<locals>.<lambda>  s    aaQ// r   c                 <    |                              |           S rB   r   r   s     r   r   zcasoratian.<locals>.<lambda>  s    aa++ r   )listr   r   rY   r8   det)r   r   zerofks   ``   r   
casoratianr   r  sp    > GT""##D ,/////+++++D		A!Q??   r   c                  $    t          j        | i |S )z`Create square identity matrix n x n

    See Also
    ========

    diag
    zeros
    ones
    )r8   eyeargsr-   s     r   r   r     s     :t&v&&&r   Fstrictunpackc                 *    t          j        || |d|S )a]  Returns a matrix with the provided values placed on the
    diagonal. If non-square matrices are included, they will
    produce a block-diagonal matrix.

    Examples
    ========

    This version of diag is a thin wrapper to Matrix.diag that differs
    in that it treats all lists like matrices -- even when a single list
    is given. If this is not desired, either put a `*` before the list or
    set `unpack=True`.

    >>> from sympy import diag

    >>> diag([1, 2, 3], unpack=True)  # = diag(1,2,3) or diag(*[1,2,3])
    Matrix([
    [1, 0, 0],
    [0, 2, 0],
    [0, 0, 3]])

    >>> diag([1, 2, 3])  # a column vector
    Matrix([
    [1],
    [2],
    [3]])

    See Also
    ========
    .common.MatrixCommon.eye
    .common.MatrixCommon.diagonal - to extract a diagonal
    .common.MatrixCommon.diag
    .expressions.blockmatrix.BlockMatrix
    r   )r8   diag)r   r   valuesr-   s       r   r   r     s!    D ;vfGGGGGr   c                 &    t          j        | |ddS )a  Apply the Gram-Schmidt process to a set of vectors.

    Parameters
    ==========

    vlist : List of Matrix
        Vectors to be orthogonalized for.

    orthonormal : Bool, optional
        If true, return an orthonormal basis.

    Returns
    =======

    vlist : List of Matrix
        Orthogonalized vectors

    Notes
    =====

    This routine is mostly duplicate from ``Matrix.orthogonalize``,
    except for some difference that this always raises error when
    linearly dependent vectors are found, and the keyword ``normalize``
    has been named as ``orthonormal`` in this function.

    See Also
    ========

    .matrices.MatrixSubspaces.orthogonalize

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
    T)	normalize	rankcheck)r^   orthogonalize)vlistorthonormals     r   GramSchmidtr     s&    H +	+   r   rR   c                    t          |t                    rDd|j        vrt          d          |j        dk    r|j        }|                                d         }t          |          r!t          |          }|st          d          nt          d          t          | d          st          d| z            t          |          }||z   }t          |          }t          |          D ]\\  }}t          |d          st          d| z            t          |          D ]%}	|                    ||	                   |||	|z   f<   &]t          |          D ]T}	t          |	|          D ]A}
|                     ||	                                       ||
                   ||	|z   |
|z   f<   BUt          |          D ]'}	t          |	dz   |          D ]}
||	|
f         ||
|	f<   (|S )a  Compute Hessian matrix for a function f wrt parameters in varlist
    which may be given as a sequence or a row/column vector. A list of
    constraints may optionally be given.

    Examples
    ========

    >>> from sympy import Function, hessian, pprint
    >>> from sympy.abc import x, y
    >>> f = Function('f')(x, y)
    >>> g1 = Function('g')(x, y)
    >>> g2 = x**2 + 3*y
    >>> pprint(hessian(f, (x, y), [g1, g2]))
    [                   d               d            ]
    [     0        0    --(g(x, y))     --(g(x, y))  ]
    [                   dx              dy           ]
    [                                                ]
    [     0        0        2*x              3       ]
    [                                                ]
    [                     2               2          ]
    [d                   d               d           ]
    [--(g(x, y))  2*x   ---(f(x, y))   -----(f(x, y))]
    [dx                   2            dy dx         ]
    [                   dx                           ]
    [                                                ]
    [                     2               2          ]
    [d                   d               d           ]
    [--(g(x, y))   3   -----(f(x, y))   ---(f(x, y)) ]
    [dy                dy dx              2          ]
    [                                   dy           ]

    References
    ==========

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

    See Also
    ========

    sympy.matrices.matrices.MatrixCalculus.jacobian
    wronskian
    r   z)`varlist` must be a column or row vector.r   z `len(varlist)` must not be zero.z*Improper variable list in hessian functiondiffz'Function `f` (%s) is not differentiable)rW   r   rZ   r   rt   Ttolistr   rY   
ValueErrorrV   zerosrl   rr   r   )r   varlistconstraintsr   ru   Noutr   gre   rf   s              r   hessianr     s4   X ':&& &GM! 	JHIII<1 	 iG..""1%7 GLL 	A?@@@	A EFFF1f HBQFGGGKA	AA
((C+&& / /1q&!! 	LFJKKKq 	/ 	/AFF71:..C1q5MM	/1XX D Dq! 	D 	DA !wqz 2 2 7 7
 C CCAq1u	D1XX " "q1ua 	" 	"AAqD	C1II	"Jr   c                 :    t                               ||           S )z
    Create a Jordan block:

    Examples
    ========

    >>> from sympy import jordan_cell
    >>> from sympy.abc import x
    >>> jordan_cell(x, 4)
    Matrix([
    [x, 1, 0, 0],
    [0, x, 1, 0],
    [0, 0, x, 1],
    [0, 0, 0, x]])
    )size
eigenvalue)r8   jordan_block)eigenvalr   s     r   jordan_cellr   F  s    " A(;;;r   c                 ,    |                      |          S )a  Return the Hadamard product (elementwise product) of A and B

    >>> from sympy import Matrix, matrix_multiply_elementwise
    >>> A = Matrix([[0, 1, 2], [3, 4, 5]])
    >>> B = Matrix([[1, 10, 100], [100, 10, 1]])
    >>> matrix_multiply_elementwise(A, B)
    Matrix([
    [  0, 10, 200],
    [300, 40,   5]])

    See Also
    ========

    sympy.matrices.common.MatrixCommon.__mul__
    )multiply_elementwise)ABs     r   matrix_multiply_elementwiser   Z  s      !!!$$$r   c                  \    d|v r|                     d          |d<   t          j        | i |S )zReturns a matrix of ones with ``rows`` rows and ``cols`` columns;
    if ``cols`` is omitted a square matrix will be returned.

    See Also
    ========

    zeros
    eye
    diag
    crt   )popr8   onesr   s     r   r   r   m  s8     f} )Cv;''''r   c   d   c                    |pt          j        |          }|| }|r| |k    rt          d| |fz            t          | |z            }|dk    r6|                    |t          t          |          |z  dz                      }t          | |          }	|s4|D ]0}
t          |
|          \  }}|	                    ||          |	||f<   1n@|D ]=}
t          |
|          \  }}||k    r"|	                    ||          x|	||f<   |	||f<   >|	S )a  Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted
    the matrix will be square. If ``symmetric`` is True the matrix must be
    square. If ``percent`` is less than 100 then only approximately the given
    percentage of elements will be non-zero.

    The pseudo-random number generator used to generate matrix is chosen in the
    following way.

    * If ``prng`` is supplied, it will be used as random number generator.
      It should be an instance of ``random.Random``, or at least have
      ``randint`` and ``shuffle`` methods with same signatures.
    * if ``prng`` is not supplied but ``seed`` is supplied, then new
      ``random.Random`` with given ``seed`` will be created;
    * otherwise, a new ``random.Random`` with default seed will be used.

    Examples
    ========

    >>> from sympy import randMatrix
    >>> randMatrix(3) # doctest:+SKIP
    [25, 45, 27]
    [44, 54,  9]
    [23, 96, 46]
    >>> randMatrix(3, 2) # doctest:+SKIP
    [87, 29]
    [23, 37]
    [90, 26]
    >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP
    [0, 2, 0]
    [2, 0, 1]
    [0, 0, 1]
    >>> randMatrix(3, symmetric=True) # doctest:+SKIP
    [85, 26, 29]
    [26, 71, 43]
    [29, 43, 57]
    >>> A = randMatrix(3, seed=1)
    >>> B = randMatrix(3, seed=2)
    >>> A == B
    False
    >>> A == randMatrix(3, seed=1)
    True
    >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP
    [77, 70,  0],
    [70,  0,  0],
    [ 0,  0, 88]
    Nz4For symmetric matrices, r must equal c, but %i != %ir   )
randomRandomr   rr   sampleintrY   r   divmodrandint)rr   minmaxseed	symmetricpercentprngijru   ijkre   rf   s                r   
randMatrixr     sN   b &6=&&D  ZQ!V ZOSTVWRXXYYY	q1uB#~ :[[SRC!78899aA ; 	- 	-C#q>>DAqll3,,AadGG	-  	; 	;C#q>>DAqAv ;$(LLc$:$::!Q$!AqD'Hr   bareissc                      d  D              t                     }|dk    rt          j        S t          || fd          }|                    |          S )ax  
    Compute Wronskian for [] of functions

    ::

                         | f1       f2        ...   fn      |
                         | f1'      f2'       ...   fn'     |
                         |  .        .        .      .      |
        W(f1, ..., fn) = |  .        .         .     .      |
                         |  .        .          .    .      |
                         |  (n)      (n)            (n)     |
                         | D   (f1) D   (f2)  ...  D   (fn) |

    see: https://en.wikipedia.org/wiki/Wronskian

    See Also
    ========

    sympy.matrices.matrices.MatrixCalculus.jacobian
    hessian
    c                 ,    g | ]}t          |          S rR   r   ).0r   s     r   
<listcomp>zwronskian.<locals>.<listcomp>  s    //////r   r   c                 <    |                               |          S rB   )r   )re   rf   	functionsvars     r   r   zwronskian.<locals>.<lambda>  s    )A,"3"3C";"; r   )rY   r   Oner8   r   )r   r   r'   r   Ws   ``   r   	wronskianr     se    . 0/Y///IIAAv uq!;;;;;<<A55==r   c                  \    d|v r|                     d          |d<   t          j        | i |S )zReturns a matrix of zeros with ``rows`` rows and ``cols`` columns;
    if ``cols`` is omitted a square matrix will be returned.

    See Also
    ========

    ones
    eye
    diag
    r   rt   )r   r8   r   r   s     r   r   r     s8     f} )Cv<((((r   rI   )F)rR   )Nr   r   NFr   N)r   )7r   sympy.core.basicr   sympy.core.singletonr   sympy.core.symbolr   sympy.core.sympifyr   (sympy.functions.elementary.trigonometricr   r	   sympy.utilities.decoratorr
   sympy.utilities.exceptionsr   sympy.utilities.iterablesr   commonr   decompositionsr   r   matricesr   	repmatrixr   r   solversr   r   r   r   r\   r^   MutableMatrixr8   r   rp   rv   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rR   r   r   <module>r      s&    " " " " " " " " " " " " $ $ $ $ $ $ & & & & & & = = = = = = = = 8 8 8 8 8 8 @ @ @ @ @ @ 1 1 1 1 1 1       8 8 8 8 8 8 8 8             2 2 2 2 2 2 2 2 E E E E E E E E  
FE FE FE FE FE) FE FE FER  6 6 6 6 6&6 6 6 6" , +      !     ' ' 'T' ' 'T' ' 'T J'''E E ('EX(! (! (! (!V' ' ' e "H "H "H "H "HJ& & & &RJ J J JZ< < <(% % %&( ( ($ ?D!%I I I IX   >) ) ) ) )r   