
    wg*u             	       V   d 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
 ddlmZ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 ddlm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl%m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8 dZ9 G d de:      Z; G d de;      Z< G d  d!e<      Z= G d" d#e<      Z> G d$ d%e<      Z? G d& d'e<      Z@ G d( d)e<      ZA G d* d+eAe@e?e>e=      ZB G d, d-      ZC G d. d/      ZD G d0 d1      ZEd2 ZFd6d4ZGd5 ZHy3)7at  
A module contining deprecated matrix mixin classes.

The classes in this module are deprecated and will be removed in a future
release. They are kept here for backwards compatibility in case downstream
code was subclassing them.

Importing anything else from this module is deprecated so anything here
should either not be used or should be imported from somewhere else.
    )defaultdict)Iterable)
isfunction)reducerefine)SympifyErrorAdd)Atom)call_highest_priority)	fuzzy_and	FuzzyBool)IntegerMod)S)Symbol)sympify)Absreim)sympy_deprecation_warning   )_dotprodsimp	_simplify)Poly)flattenis_sequence)as_int
filldedent)	NDimArray)_get_intermediate_simp_bool)MatrixError
ShapeErrorNonSquareMatrixErrorNonInvertibleMatrixErrorNonPositiveDefiniteMatrixError)MatrixShapingMatrixSpecialMatrixPropertiesMatrixOperationsMatrixArithmeticMatrixCommonMatrixDeterminantMatrixReductionsMatrixSubspacesMatrixEigenMatrixCalculusMatrixDeprecatedc                        e Zd Z fdZ xZS )_MatrixDeprecatedMetac                    t        d| j                   d| j                   dddd       dd	lm} dd
lm}m}m}m}m	}m
} t        t        t        t        t        t         t"        ||||||f}	| |	v rt%        ||      ryt&        
| Q  |      S )Nz:
            Checking whether an object is an instance of zc is
            deprecated.

            Use `isinstance(obj, Matrix)` instead of `isinstance(obj, z)`.
            1.13deprecated-matrix-mixins   deprecated_since_versionactive_deprecations_target
stacklevelr   
MatrixBase)r.   r/   r0   r1   r2   r3   T)r   __name__sympy.matrices.matrixbaser?   sympy.matrices.matricesr.   r/   r0   r1   r2   r3   MatrixRequiredr(   r)   r*   r+   r,   r-   
isinstancesuper__instancecheck__)clsinstancer?   r.   r/   r0   r1   r2   r3   
all_mixins	__class__s             Z/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/matrices/common.pyrF   z'_MatrixDeprecatedMeta.__instancecheck__Q   s    !::=,, HG HK||n U	 &,'A
	
 	9	
 	
 

  *Hj!A7,X66    )r@   
__module____qualname__rF   __classcell__rJ   s   @rK   r5   r5   ?   s    $+7 +7rL   r5   c                   `     e Zd ZdZdZdZdZ fdZed        Z	d Z
d Zd Zed        Z xZS )	rC   z1Deprecated mixin class for making matrix classes.Nc                     | j                   t        vrt        d| j                    dddd       t        |   di | y )Nzd
                Inheriting from the Matrix mixin classes is deprecated.

                The class z4 is subclassing a deprecated mixin.
                r7   r8   r9   r:    )r@   _DEPRECATED_MIXINSr   rE   __init_subclass__)rG   kwargsrJ   s     rK   rU   z MatrixRequired.__init_subclass__   sQ     <<11% <<. )
 *0+E	 	!+F+rL   c                     t        d      )z`_new` must, at minimum, be callable as
        `_new(rows, cols, mat) where mat is a flat list of the
        elements of the matrix.Subclasses must implement this.NotImplementedErrorrG   argsrV   s      rK   _newzMatrixRequired._new       
 ""CDDrL   c                     t        d      NrX   rY   selfothers     rK   __eq__zMatrixRequired.__eq__   s    !"CDDrL   c                     t        d      )a  Implementations of __getitem__ should accept ints, in which
        case the matrix is indexed as a flat list, tuples (i,j) in which
        case the (i,j) entry is returned, slices, or mixed tuples (a,b)
        where a and b are any combination of slices and integers.rX   rY   rb   keys     rK   __getitem__zMatrixRequired.__getitem__   r^   rL   c                     t        d      )z*The total number of entries in the matrix.rX   rY   rb   s    rK   __len__zMatrixRequired.__len__       !"CDDrL   c                     t        d      r`   rY   rj   s    rK   shapezMatrixRequired.shape   rl   rL   )r@   rM   rN   __doc__rowscolsr   rU   classmethodr]   rd   rh   rk   propertyrn   rO   rP   s   @rK   rC   rC      sX    ;DDI,6 E EEEE E ErL   rC   )	metaclassc                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zed        Zd Zd Zd Zd Zd#dZd Zed        Zd Z d Z!d Z"d Z#d$d Z$ed!        Z%y")%r(   z;Provides basic matrix shaping and extracting of submatricesc                 f      fd} j                   j                   j                  dz
  |      S )Nc                 0    |k  r| |f   S | |dz   f   S Nr   rS   )ijcolrb   s     rK   entryz*MatrixShaping._eval_col_del.<locals>.entry   s(    !"S41:<d1a!e8n<rL   r   r]   rp   rq   )rb   r{   r|   s   `` rK   _eval_col_delzMatrixShaping._eval_col_del   s'    	=yyDIIM599rL   c                 ~      fd} j                   j                   j                  j                  z   |      S )Nc                     |k  r| |f   S |cxk  rj                   z   k  rn n
| |z
  f   S | |j                   z
  f   S Nrq   )ry   rz   rc   posrb   s     rK   r|   z-MatrixShaping._eval_col_insert.<locals>.entry   sY    3wAqDz!,C%**,,QCZ((1uzz>)**rL   r}   )rb   r   rc   r|   s   ``` rK   _eval_col_insertzMatrixShaping._eval_col_insert   s.    	+ yyDII

$:EBBrL   c                       j                    fd}t               j                   j                   j                   z    j                  |      S )Nc                 0    | k  r| |f   S | z
  |f   S r   rS   )ry   rz   rc   rp   rb   s     rK   r|   z+MatrixShaping._eval_col_join.<locals>.entry   s+    4xAqDz!T1%%rL   )rp   classofr]   rq   )rb   rc   r|   rp   s   `` @rK   _eval_col_joinzMatrixShaping._eval_col_join   sE    yy	&
 tU#((UZZ)?).0 	0rL   c           	          t        |       }| j                  fd|D        }| j                  t        |      t              |D cg c]  }||   	 c}      S c c}w )Nc              3   <   K   | ]  }D ]  }|z  |z      y wr   rS   ).0ry   rz   rq   colsLists      rK   	<genexpr>z.MatrixShaping._eval_extract.<locals>.<genexpr>   s%     DA8Da1t8a<D<D   )listrq   r]   len)rb   rowsListr   matindicesry   rq   s     `   @rK   _eval_extractzMatrixShaping._eval_extract   sQ    4jyyDDyyXH*12Q#a&24 	42s   	Ac                 *    g fd |        S )Nc                 `   d}|| j                   d   k  r|dk(  r| d|d f   }| |d df   }n| d ||d f   }| |d d |f   }t        |      st        |      r|dz  }\j                  | d |d |f          | j                   | d |d |f   j                   k(  ry  | |d |d f          y y Nr   r   )rn   anyappend)Mry   to_the_rightto_the_bottomrecurse_sub_blocks
sub_blockss       rK   r   z?MatrixShaping._eval_get_diag_blocks.<locals>.recurse_sub_blocks   s    Aqwwqz/6#$QU8L$%ab!eHM#$RaRV9L$%ab"1"fIM|$M(:FA%%aBQBi0ww!BQBF)//1*1QRV95! "rL   rS   )rb   r   r   s    @@rK   _eval_get_diag_blocksz#MatrixShaping._eval_get_diag_blocks   s    
	( 	4 rL   c                 f      fd} j                   j                  dz
   j                  |      S )Nc                 0    | k  r| |f   S | dz   |f   S rx   rS   )ry   rz   rowrb   s     rK   r|   z*MatrixShaping._eval_row_del.<locals>.entry   s(    !"S41:<d1q5!8n<rL   r   r}   )rb   r   r|   s   `` rK   _eval_row_delzMatrixShaping._eval_row_del   s'    	=yyQ		599rL   c                     t        |       }|| j                  z  }t        |      ||| | j                  | j                  |j                  z   | j                  |      S r   )r   rq   r]   rp   )rb   r   rc   entries
insert_poss        rK   _eval_row_insertzMatrixShaping._eval_row_insert   sL    t*499_
)-e
:&yyUZZ/GDDrL   c                       j                    fd}t               j                   j                   j                   j                   z   |      S )Nc                 0    |k  r| |f   S | |z
  f   S r   rS   )ry   rz   rq   rc   rb   s     rK   r|   z+MatrixShaping._eval_row_join.<locals>.entry  s+    4xAqDz!AH%%rL   )rq   r   r]   rp   )rb   rc   r|   rq   s   `` @rK   _eval_row_joinzMatrixShaping._eval_row_join  sE    yy	&
 tU#((DII

4J).0 	0rL   c           	      r    t        | j                        D cg c]  }t        | |d d f          c}S c c}w r   )rangerp   r   rb   ry   s     rK   _eval_tolistzMatrixShaping._eval_tolist  s+    ).tyy)9:AT!A#Y:::s   4c                     i }| j                   \  }}t        |      D ]0  }t        |      D ]   }| ||f   }|| j                  k7  s||||f<   " 2 |S r   )rn   r   zero)rb   dokrp   rq   ry   rz   vals          rK   _eval_todokzMatrixShaping._eval_todok  sg    ZZ
dt 	$A4[ $1a4j$))# #C1I$	$
 
rL   c                 b      j                    fd} j                  t               d|      S )Nc                 ,    | z  }| |z  z
  }||f   S r   rS   )n_rz   ry   rp   rb   s       rK   r|   z&MatrixShaping._eval_vec.<locals>.entry   s'    T	AAHA1:rL   r   )rp   r]   r   )rb   r|   rp   s   ` @rK   	_eval_veczMatrixShaping._eval_vec  s*    yy	 yyTAu--rL   c                 >   | j                   }g }|r8t        |      D ])  }t        ||      D ]  }|j                  | ||f           + n:t        |      D ],  }t        |dz   |      D ]  }|j                  | ||f           . | j                  t	        |      d|      S rx   )rq   r   r   r]   r   )rb   diagonalcvrz   ry   s         rK   
_eval_vechzMatrixShaping._eval_vech(  s    II1X )q! )AHHT!Q$Z()) 1X )q1ua )AHHT!Q$Z()) yyQA&&rL   c                     |dk  r|| j                   z  }d|cxk  r| j                   k  sn t        dj                  |            | j                  |      S )zDelete the specified column.r   zColumn {} is out of range.)rq   
IndexErrorformatr~   )rb   r{   s     rK   col_delzMatrixShaping.col_del5  sP    7499CC#$))#9@@EFF!!#&&rL   c                 `   | s t        |       |      S t        |      }|dk  r| j                  |z   }|dk  rd}n|| j                  kD  r| j                  }| j                  |j                  k7  r/t	        dj                  | j                  |j                              | j                  ||      S )ay  Insert one or more columns at the given column position.

        Examples
        ========

        >>> from sympy import zeros, ones
        >>> M = zeros(3)
        >>> V = ones(3, 1)
        >>> M.col_insert(1, V)
        Matrix([
        [0, 1, 0, 0],
        [0, 1, 0, 0],
        [0, 1, 0, 0]])

        See Also
        ========

        col
        row_insert
        r   9The matrices have incompatible number of rows ({} and {}))typer   rq   rp   r$   r   r   rb   r   rc   s      rK   
col_insertzMatrixShaping.col_insert=  s    , 4:e$$Sk7))c/C7C499_))C99

"K		5::.0 0 $$S%00rL   c                 \   | j                   dk(  rE| j                  |j                  k7  r,| j                  d|j                  g       j                  |      S | j                  |j                  k7  r/t	        dj                  | j                  |j                              | j                  |      S )a  Concatenates two matrices along self's last and other's first row.

        Examples
        ========

        >>> from sympy import zeros, ones
        >>> M = zeros(3)
        >>> V = ones(1, 3)
        >>> M.col_join(V)
        Matrix([
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [1, 1, 1]])

        See Also
        ========

        col
        row_join
        r   <The matrices have incompatible number of columns ({} and {}))rp   rq   r]   col_joinr$   r   r   ra   s     rK   r   zMatrixShaping.col_joinf  s    . 99>dii5::599Q

B/88??99

"N		5::.0 0 ""5))rL   c                     | dd|f   S )a  Elementary column selector.

        Examples
        ========

        >>> from sympy import eye
        >>> eye(2).col(0)
        Matrix([
        [1],
        [0]])

        See Also
        ========

        row
        col_del
        col_join
        col_insert
        NrS   )rb   rz   s     rK   r{   zMatrixShaping.col  s    ( AqDzrL   c                    t        |      rt        |      st        d      |r2t        d |D              r t        |      D cg c]
  \  }}|s	| }}}|r2t        d |D              r t        |      D cg c]
  \  }}|s	| }}}|D cg c]  }t	        || j
                         }}|D cg c]  }t	        || j                         }}| j                  ||      S c c}}w c c}}w c c}w c c}w )a  Return a submatrix by specifying a list of rows and columns.
        Negative indices can be given. All indices must be in the range
        $-n \le i < n$ where $n$ is the number of rows or columns.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(4, 3, range(12))
        >>> m
        Matrix([
        [0,  1,  2],
        [3,  4,  5],
        [6,  7,  8],
        [9, 10, 11]])
        >>> m.extract([0, 1, 3], [0, 1])
        Matrix([
        [0,  1],
        [3,  4],
        [9, 10]])

        Rows or columns can be repeated:

        >>> m.extract([0, 0, 1], [-1])
        Matrix([
        [2],
        [2],
        [5]])

        Every other row can be taken by using range to provide the indices:

        >>> m.extract(range(0, m.rows, 2), [-1])
        Matrix([
        [2],
        [8]])

        RowsList or colsList can also be a list of booleans, in which case
        the rows or columns corresponding to the True values will be selected:

        >>> m.extract([0, 1, 2, 3], [True, False, True])
        Matrix([
        [0,  2],
        [3,  5],
        [6,  8],
        [9, 11]])
        z&rowsList and colsList must be iterablec              3   <   K   | ]  }t        |t                y wr   rD   boolr   ry   s     rK   r   z(MatrixShaping.extract.<locals>.<genexpr>       BAJq$/B   c              3   <   K   | ]  }t        |t                y wr   r   r   s     rK   r   z(MatrixShaping.extract.<locals>.<genexpr>  r   r   )r   	TypeErrorall	enumeratea2idxrp   rq   r   )rb   r   r   indexitemks         rK   extractzMatrixShaping.extract  s    ` 8$K,ADEEBBB1:81DM+%MHMBBB1:81DM+%MHM 2::AE!TYY'::19:AE!TYY'::!!(H55 NM ;:s$   
C"C"8
C(C(C.1C3c                 "    | j                         S )az  Obtains the square sub-matrices on the main diagonal of a square matrix.

        Useful for inverting symbolic matrices or solving systems of
        linear equations which may be decoupled by having a block diagonal
        structure.

        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy.abc import x, y, z
        >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
        >>> a1, a2, a3 = A.get_diag_blocks()
        >>> a1
        Matrix([
        [1,    3],
        [y, z**2]])
        >>> a2
        Matrix([[x]])
        >>> a3
        Matrix([[0]])

        )r   rj   s    rK   get_diag_blockszMatrixShaping.get_diag_blocks  s    0 ))++rL   c                     t        |      dk(  r| j                         S t        |d         }t        |j                  |      S )a(  Return a matrix formed by joining args horizontally (i.e.
        by repeated application of row_join).

        Examples
        ========

        >>> from sympy import Matrix, eye
        >>> Matrix.hstack(eye(2), 2*eye(2))
        Matrix([
        [1, 0, 2, 0],
        [0, 1, 0, 2]])
        r   )r   r]   r   r   row_joinrG   r\   klss      rK   hstackzMatrixShaping.hstack  s9     t9>88:47mcllD))rL   c                       j                    j                  z  |z  k7  rt        d|fz         j                  | fd      S )a  Reshape the matrix. Total number of elements must remain the same.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(2, 3, lambda i, j: 1)
        >>> m
        Matrix([
        [1, 1, 1],
        [1, 1, 1]])
        >>> m.reshape(1, 6)
        Matrix([[1, 1, 1, 1, 1, 1]])
        >>> m.reshape(3, 2)
        Matrix([
        [1, 1],
        [1, 1],
        [1, 1]])

        z Invalid reshape parameters %d %dc                     | z  |z      S r   rS   )ry   rz   rq   rb   s     rK   <lambda>z'MatrixShaping.reshape.<locals>.<lambda>  s    $q4x!|2D rL   )rp   rq   
ValueErrorr]   )rb   rp   rq   s   ` `rK   reshapezMatrixShaping.reshape  sG    * 99tyy D4K/?4,NOOyyt%DEErL   c                     |dk  r|| j                   z  }d|cxk  r| j                   k  sn t        dj                  |            | j                  |      S )zDelete the specified row.r   zRow {} is out of range.)rp   r   r   r   )rb   r   s     rK   row_delzMatrixShaping.row_del!  sP    7499CC#$))#6==cBCC!!#&&rL   c                 `   | s| j                  |      S t        |      }|dk  r| j                  |z   }|dk  rd}n|| j                  kD  r| j                  }| j                  |j                  k7  r/t	        dj                  | j                  |j                              | j                  ||      S )a}  Insert one or more rows at the given row position.

        Examples
        ========

        >>> from sympy import zeros, ones
        >>> M = zeros(3)
        >>> V = ones(1, 3)
        >>> M.row_insert(1, V)
        Matrix([
        [0, 0, 0],
        [1, 1, 1],
        [0, 0, 0],
        [0, 0, 0]])

        See Also
        ========

        row
        col_insert
        r   r   )r]   r   rp   rq   r$   r   r   r   s      rK   
row_insertzMatrixShaping.row_insert*  s    . 99U##Sk7))c/C7C499_))C99

"N		5::.0 0 $$S%00rL   c                 \   | j                   dk(  rE| j                  |j                  k7  r,| j                  |j                  dg       j                  |      S | j                  |j                  k7  r/t	        dj                  | j                  |j                              | j                  |      S )a|  Concatenates two matrices along self's last and rhs's first column

        Examples
        ========

        >>> from sympy import zeros, ones
        >>> M = zeros(3)
        >>> V = ones(3, 1)
        >>> M.row_join(V)
        Matrix([
        [0, 0, 0, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 1]])

        See Also
        ========

        row
        col_join
        r   r   )rq   rp   r]   r   r$   r   r   ra   s     rK   r   zMatrixShaping.row_joinT  s    , 99>dii5::599UZZB/88??99

"K		5::.0 0 ""5))rL   c                 j   g }t        |      }|dkD  rdn| }|rdn|}	 || j                  k(  s|| j                  k(  rn!|j                  | ||f          |dz  }|dz  }@|s8t	        t        d|dd| j                  z
  d| j                  dz
  d            | j                  dt        |      |      S )a  Returns the kth diagonal of self. The main diagonal
        corresponds to `k=0`; diagonals above and below correspond to
        `k > 0` and `k < 0`, respectively. The values of `self[i, j]`
        for which `j - i = k`, are returned in order of increasing
        `i + j`, starting with `i + j = |k|`.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(3, 3, lambda i, j: j - i); m
        Matrix([
        [ 0,  1, 2],
        [-1,  0, 1],
        [-2, -1, 0]])
        >>> _.diagonal()
        Matrix([[0, 0, 0]])
        >>> m.diagonal(1)
        Matrix([[1, 1]])
        >>> m.diagonal(-2)
        Matrix([[-2]])

        Even though the diagonal is returned as a Matrix, the element
        retrieval can be done with a single index:

        >>> Matrix.diag(1, 2, 3).diagonal()[1]  # instead of [0, 1]
        2

        See Also
        ========

        diag
        r   r   z
            The z diagonal is out of range [, ])r   rp   rq   r   r   r    r]   r   )rb   r   rvrr   s        rK   r   zMatrixShaping.diagonals  s    D 1IQAQBADII~diiIId1a4j!FAFA  Zq499}dii!m)- . / / yyCGR((rL   c                     | |ddf   S )zElementary row selector.

        Examples
        ========

        >>> from sympy import eye
        >>> eye(2).row(0)
        Matrix([[1, 0]])

        See Also
        ========

        col
        row_del
        row_join
        row_insert
        NrS   r   s     rK   r   zMatrixShaping.row  s    $ AqDzrL   c                 2    | j                   | j                  fS )a  The shape (dimensions) of the matrix as the 2-tuple (rows, cols).

        Examples
        ========

        >>> from sympy import zeros
        >>> M = zeros(2, 3)
        >>> M.shape
        (2, 3)
        >>> M.rows
        2
        >>> M.cols
        3
        rp   rq   rj   s    rK   rn   zMatrixShaping.shape  s      		499%%rL   c                 "    | j                         S )zReturn the matrix as dictionary of keys.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix.eye(3)
        >>> M.todok()
        {(0, 0): 1, (1, 1): 1, (2, 2): 1}
        )r   rj   s    rK   todokzMatrixShaping.todok  s     !!rL   c                     | j                   sg S | j                  s#t        | j                         D cg c]  }g  c}S | j                         S c c}w )a   Return the Matrix as a nested Python list.

        Examples
        ========

        >>> from sympy import Matrix, ones
        >>> m = Matrix(3, 3, range(9))
        >>> m
        Matrix([
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
        >>> m.tolist()
        [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
        >>> ones(3, 0).tolist()
        [[], [], []]

        When there are no rows then it will not be possible to tell how
        many columns were in the original matrix:

        >>> ones(0, 3).tolist()
        []

        )rp   rq   r   r   r   s     rK   tolistzMatrixShaping.tolist  sE    2 yyIyy %dii 011B11  "" 2s   	Ac                     i }| j                         }t        |      D ].  \  }}t        |      D ci c]  \  }}|s	|| }}}|s*|||<   0 |S c c}}w )a;  Returns matrix as dict of dicts containing non-zero elements of the Matrix

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix([[0, 1],[0, 3]])
        >>> A
        Matrix([
        [0, 1],
        [0, 3]])
        >>> A.todod()
        {0: {1: 1}, 1: {1: 3}}


        )r   r   )r   rowsdictMlolry   Mirz   Mijr   s           rK   tododzMatrixShaping.todod  sd    " xxzt_ 	"EAr(1"=fa1c6=C=!	"  >s
   
AAc                 "    | j                         S )a  Return the Matrix converted into a one column matrix by stacking columns

        Examples
        ========

        >>> from sympy import Matrix
        >>> m=Matrix([[1, 3], [2, 4]])
        >>> m
        Matrix([
        [1, 3],
        [2, 4]])
        >>> m.vec()
        Matrix([
        [1],
        [2],
        [3],
        [4]])

        See Also
        ========

        vech
        )r   rj   s    rK   veczMatrixShaping.vec  s    0 ~~rL   c                     | j                   st        |r| j                         st        d      | j	                  |      S )a{  Reshapes the matrix into a column vector by stacking the
        elements in the lower triangle.

        Parameters
        ==========

        diagonal : bool, optional
            If ``True``, it includes the diagonal elements.

        check_symmetry : bool, optional
            If ``True``, it checks whether the matrix is symmetric.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m=Matrix([[1, 2], [2, 3]])
        >>> m
        Matrix([
        [1, 2],
        [2, 3]])
        >>> m.vech()
        Matrix([
        [1],
        [2],
        [3]])
        >>> m.vech(diagonal=False)
        Matrix([[2]])

        Notes
        =====

        This should work for symmetric matrices and ``vech`` can
        represent symmetric matrices in vector form with less size than
        ``vec``.

        See Also
        ========

        vec
        zThe matrix is not symmetric.)	is_squarer%   is_symmetricr   r   )rb   r   check_symmetrys      rK   vechzMatrixShaping.vech*  s;    T ~~&&$"3"3"5;<<x((rL   c                     t        |      dk(  r| j                         S t        |d         }t        |j                  |      S )a:  Return a matrix formed by joining args vertically (i.e.
        by repeated application of col_join).

        Examples
        ========

        >>> from sympy import Matrix, eye
        >>> Matrix.vstack(eye(2), 2*eye(2))
        Matrix([
        [1, 0],
        [0, 1],
        [2, 0],
        [0, 2]])
        r   )r   r]   r   r   r   r   s      rK   vstackzMatrixShaping.vstack\  s9      t9>88:47mcllD))rL   Nr   )TT)&r@   rM   rN   ro   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r{   r   r   rr   r   r   r   r   r   r   r   rs   rn   r   r   r   r   r  r  rS   rL   rK   r(   r(      s    E:
	C	044:
E	0;	.'''1R*@,<6|,4 * *&F2'(1T*>0)d( & &""#>2 40)d * *rL   r(   c                      e Zd ZdZed        Zed        Zeddefd       Zed        Z	ed        Z
ed	        Zed
ddddd       Zedd       Zedddd       Zedd       Zedd       Zed        Zed        Zy)r)   z Construction of special matricesc                 4    fd}| j                  |||      S )zUdiag_dict is a defaultdict containing
        all the entries of the diagonal matrix.c                     | |f   S r   rS   )ry   rz   	diag_dicts     rK   r|   z'MatrixSpecial._eval_diag.<locals>.entryz  s    aV$$rL   r]   )rG   rp   rq   r  r|   s      ` rK   
_eval_diagzMatrixSpecial._eval_diagv  s    	%xxdE**rL   c                     | j                   g||z  z  }| j                  gt        ||      z  |d d |dz   <   | j                  |||d      S )Nr   Fcopy)r   oneminr]   )rG   rp   rq   valss       rK   	_eval_eyezMatrixSpecial._eval_eye~  sO    z49%''3tT?2XtAvXxxdDux55rL   uppersizec                 P     |dk(  r fd}n fd} j                  |||      S )Nlowerc                 R    | |k(  rS |dz   | k(  rj                   S j                  S rx   r  r   ry   rz   rG   
eigenvalues     rK   r|   z/MatrixSpecial._eval_jordan_block.<locals>.entry  -    6%%UaZ77NxxrL   c                 R    | |k(  rS | dz   |k(  rj                   S j                  S rx   r  r  s     rK   r|   z/MatrixSpecial._eval_jordan_block.<locals>.entry  r  rL   r  )rG   r  r  bandr|   s   ` `  rK   _eval_jordan_blockz MatrixSpecial._eval_jordan_block  s)    7?   xxdE**rL   c                 4      fd} j                  |||      S )Nc                     j                   S r   r  ry   rz   rG   s     rK   r|   z'MatrixSpecial._eval_ones.<locals>.entry  s    77NrL   r  )rG   rp   rq   r|   s   `   rK   
_eval_oneszMatrixSpecial._eval_ones  s    	xxdE**rL   c                 N    | j                  ||| j                  g||z  z  d      S )NFr  )r]   r   )rG   rp   rq   s      rK   _eval_zeroszMatrixSpecial._eval_zeros  s(    xxdSXXJT	$:xGGrL   c                 N     fd} j                  d|z  dz   d|z  dz   |      } j                  t        t        | |dz               d      |z   |j                  z   }t         j                  t        t        | |dz               d            |z   |j                  z   }||fS )Nc                 D    | dz   |k(  rj                   S j                  S rx   r  r$  s     rK   r|   z,MatrixSpecial._eval_wilkinson.<locals>.entry  s     !eqj3776chh6rL      r   T)unpack)r]   diagr   r   Tabs)rG   r   r|   Dwminuswpluss   `     rK   _eval_wilkinsonzMatrixSpecial._eval_wilkinson  s    	7 HHQqS1WacAgu-$uaRQ/0>BQSSHCHHT%AE"23DHABQFLu}rL   FTN)strictr+  rp   rq   c          
      x   ddl m} ddlm} ddlm}	 |j                  d|       }
|r0t        |      dk(  r"t        |d         rt        |d   |      s|d   }t        t              }dx}}|D ]  }t        |t              rj|r( ||      }|j                  \  }}|j                         }n~|	j                  |      \  }}}|j!                         D ]  \  \  }}}||||z   ||z   f<    g }n>t#        |d      r |j                  \  }}|j                         }n||||f<   |dz  }|dz  }t%        |      D ]%  \  }}t%        |      D ]  \  }}||||z   ||z   f<    ' ||z  }||z  } |||}}|||}}n||n|}||k  s||k  r&t'        t)        dj+                  ||||                  |
j-                  |||      S )	aX
  Returns a matrix with the specified diagonal.
        If matrices are passed, a block-diagonal matrix
        is created (i.e. the "direct sum" of the matrices).

        kwargs
        ======

        rows : rows of the resulting matrix; computed if
               not given.

        cols : columns of the resulting matrix; computed if
               not given.

        cls : class for the resulting matrix

        unpack : bool which, when True (default), unpacks a single
        sequence rather than interpreting it as a Matrix.

        strict : bool which, when False (default), allows Matrices to
        have variable-length rows.

        Examples
        ========

        >>> from sympy import Matrix
        >>> Matrix.diag(1, 2, 3)
        Matrix([
        [1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]])

        The current default is to unpack a single sequence. If this is
        not desired, set `unpack=False` and it will be interpreted as
        a matrix.

        >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
        True

        When more than one element is passed, each is interpreted as
        something to put on the diagonal. Lists are converted to
        matrices. Filling of the diagonal always continues from
        the bottom right hand corner of the previous item: this
        will create a block-diagonal matrix whether the matrices
        are square or not.

        >>> col = [1, 2, 3]
        >>> row = [[4, 5]]
        >>> Matrix.diag(col, row)
        Matrix([
        [1, 0, 0],
        [2, 0, 0],
        [3, 0, 0],
        [0, 4, 5]])

        When `unpack` is False, elements within a list need not all be
        of the same length. Setting `strict` to True would raise a
        ValueError for the following:

        >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
        Matrix([
        [1, 2, 3],
        [4, 5, 0],
        [6, 0, 0]])

        The type of the returned matrix can be set with the ``cls``
        keyword.

        >>> from sympy import ImmutableMatrix
        >>> from sympy.utilities.misc import func_name
        >>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
        'ImmutableDenseMatrix'

        A zero dimension matrix can be used to position the start of
        the filling at the start of an arbitrary row or column:

        >>> from sympy import ones
        >>> r2 = ones(0, 2)
        >>> Matrix.diag(r2, 1, 2)
        Matrix([
        [0, 0, 1, 0],
        [0, 0, 0, 2]])

        See Also
        ========
        eye
        diagonal
        .dense.diag
        .expressions.blockmatrix.BlockMatrix
        .sparsetools.banded
       r   r>   )Matrix)SparseMatrixrG   r   rn   zg
                The constructed matrix is {} x {} but a size of {} x {}
                was specified.)rA   r?   sympy.matrices.denser5  sympy.matricesr6  getr   r   rD   r   intr   rn   r   _handle_creation_inputsitemshasattrr   r   r    r   r  )r   r3  r+  rp   rq   r\   rV   r?   r5  r6  klassdiag_entriesrmaxcmaxmr   r   r   smatry   rz   mis                         rK   r,  zMatrixSpecial.diag  s   x 	9//

5#&c$i1nT!W)=tAw
37D #3't 	A!T"q	A77DAq
A!-!E!Ea!HJAq$%)ZZ\ ?	A=>a$hD%9:?AG$ww1HHJ-.dD\*		"1 ;2%bM ;DAq9:L!d(AH!56;; AIDAID5	6 <t$D<t$D<4TD$;$+Z )""(&tT4"@B C C dL99rL   c                     ||}|dk  s|dk  rt        dj                  ||            |j                  d|       }t        |      t        |      }}|j	                  ||      S )zReturns an identity matrix.

        Parameters
        ==========

        rows : rows of the matrix
        cols : cols of the matrix (if None, cols=rows)

        kwargs
        ======
        cls : class of the returned matrix
        r   @Cannot create a {} x {} matrix. Both dimensions must be positiverG   )r   r   r9  r   r  r   rp   rq   rV   r>  s        rK   eyezMatrixSpecial.eye:  sn     <D!8tax @@FtT@RT T

5#&D\6$<dtT**rL   )r  c                   |j                  d|       }|j                  dd      }||t        d      ||k7  r!d||fvrt        dj                  ||            ||}|t        d      t	        |      }|j                  |||      S )a  Returns a Jordan block

        Parameters
        ==========

        size : Integer, optional
            Specifies the shape of the Jordan block matrix.

        eigenvalue : Number or Symbol
            Specifies the value for the main diagonal of the matrix.

            .. note::
                The keyword ``eigenval`` is also specified as an alias
                of this keyword, but it is not recommended to use.

                We may deprecate the alias in later release.

        band : 'upper' or 'lower', optional
            Specifies the position of the off-diagonal to put `1` s on.

        cls : Matrix, optional
            Specifies the matrix class of the output form.

            If it is not specified, the class type where the method is
            being executed on will be returned.

        Returns
        =======

        Matrix
            A Jordan block matrix.

        Raises
        ======

        ValueError
            If insufficient arguments are given for matrix size
            specification, or no eigenvalue is given.

        Examples
        ========

        Creating a default Jordan block:

        >>> from sympy import Matrix
        >>> from sympy.abc import x
        >>> Matrix.jordan_block(4, x)
        Matrix([
        [x, 1, 0, 0],
        [0, x, 1, 0],
        [0, 0, x, 1],
        [0, 0, 0, x]])

        Creating an alternative Jordan block matrix where `1` is on
        lower off-diagonal:

        >>> Matrix.jordan_block(4, x, band='lower')
        Matrix([
        [x, 0, 0, 0],
        [1, x, 0, 0],
        [0, 1, x, 0],
        [0, 0, 1, x]])

        Creating a Jordan block with keyword arguments

        >>> Matrix.jordan_block(size=4, eigenvalue=x)
        Matrix([
        [x, 1, 0, 0],
        [0, x, 1, 0],
        [0, 0, x, 1],
        [0, 0, 0, x]])

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Jordan_matrix
        rG   eigenvalNzMust supply an eigenvaluez=Inconsistent values are given: 'eigenval'={}, 'eigenvalue'={}zMust supply a matrix size)popr9  r   r   r   r   )r   r  r  r  rV   r>  rJ  s          rK   jordan_blockzMatrixSpecial.jordan_blockR  s    ^ 

5#&::j$/("28998#Xz4J(J""(&:">@ @ #%
<899d|''j$??rL   c                 ~    ||}|j                  d|       }t        |      t        |      }}|j                  ||      S )zReturns a matrix of ones.

        Parameters
        ==========

        rows : rows of the matrix
        cols : cols of the matrix (if None, cols=rows)

        kwargs
        ======
        cls : class of the returned matrix
        rG   )r9  r   r%  rG  s        rK   oneszMatrixSpecial.ones  sB     <D

5#&D\6$<dd++rL   c                     ||}|dk  s|dk  rt        dj                  ||            |j                  d|       }t        |      t        |      }}|j	                  ||      S )zReturns a matrix of zeros.

        Parameters
        ==========

        rows : rows of the matrix
        cols : cols of the matrix (if None, cols=rows)

        kwargs
        ======
        cls : class of the returned matrix
        r   rF  rG   )r   r   r9  r   r'  rG  s        rK   zeroszMatrixSpecial.zeros  sp     <D!8tax @@FtT@RT T

5#&D\6$<d  t,,rL   c                      j                  |      }t        |t              st        dj	                  |            |j
                  st        dj	                  |            |j                  st        dj	                  |            |j                         dk\  st        dj	                  |            |j                          fd} j                  |      S )a  Returns a companion matrix of a polynomial.

        Examples
        ========

        >>> from sympy import Matrix, Poly, Symbol, symbols
        >>> x = Symbol('x')
        >>> c0, c1, c2, c3, c4 = symbols('c0:5')
        >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
        >>> Matrix.companion(p)
        Matrix([
        [0, 0, 0, 0, -c0],
        [1, 0, 0, 0, -c1],
        [0, 1, 0, 0, -c2],
        [0, 0, 1, 0, -c3],
        [0, 0, 0, 1, -c4]])
        z{} must be a Poly instance.z{} must be a monic polynomial.z#{} must be a univariate polynomial.r   z${} must have degree not less than 1.c                 f    |dz
  k(  r	d| z
      S | |dz   k(  rj                   S j                  S )Nr   r  )ry   rz   coeffsr   r  s     rK   r|   z&MatrixSpecial.companion.<locals>.entry  s;    D1H}rAv&a!eww88OrL   )
_sympifyrD   r   r   r   is_monicis_univariatedegree
all_coeffsr]   )r   polyr|   rT  r  s   `  @@rK   	companionzMatrixSpecial.companion  s    & ||D!$%:AA$GHH}}=DDTJKK!!5<<TBD D {{}qy6==dCE E "	 xxdE**rL   c                 ^    |j                  d|       }t        |      }|j                  |      S )a  Returns two square Wilkinson Matrix of size 2*n + 1
        $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n)

        Examples
        ========

        >>> from sympy import Matrix
        >>> wminus, wplus = Matrix.wilkinson(3)
        >>> wminus
        Matrix([
        [-3,  1,  0, 0, 0, 0, 0],
        [ 1, -2,  1, 0, 0, 0, 0],
        [ 0,  1, -1, 1, 0, 0, 0],
        [ 0,  0,  1, 0, 1, 0, 0],
        [ 0,  0,  0, 1, 1, 1, 0],
        [ 0,  0,  0, 0, 1, 2, 1],
        [ 0,  0,  0, 0, 0, 1, 3]])
        >>> wplus
        Matrix([
        [3, 1, 0, 0, 0, 0, 0],
        [1, 2, 1, 0, 0, 0, 0],
        [0, 1, 1, 1, 0, 0, 0],
        [0, 0, 1, 0, 1, 0, 0],
        [0, 0, 0, 1, 1, 1, 0],
        [0, 0, 0, 0, 1, 2, 1],
        [0, 0, 0, 0, 0, 1, 3]])

        References
        ==========

        .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/
        .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.

        rG   )r9  r   r2  )r   r   rV   r>  s       rK   	wilkinsonzMatrixSpecial.wilkinson  s/    H 

5#&1I$$Q''rL   )r  r   )NN)r@   rM   rN   ro   rr   r  r  r:  r   r%  r'  r2  r,  rH  rL  rN  rP  r[  r]  rS   rL   rK   r)   r)   s  s+   *+ + 6 6
 +c + +" + +
 H H 	 	  %dD K: K:Z + +. _@g _@ _@B , ,( - -. '+ '+T %( %(rL   r)   c                   Z   e Zd ZdZd Zd Zd Zd Zd Zd Z	de
fd	Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zed        Zd Zd&dZd Zed        Zed        Zed        Zede
fd       Zed        Zed        Z ed        Z!d Z"d&d Z#ed!        Z$ed"        Z%ed#        Z&d$ Z'y%)'r*   z&Provides basic properties of a matrix.c                 d    t               }| D ]   }|j                   |j                  |        " |S r   )setupdateatoms)rb   typesresultry   s       rK   _eval_atomszMatrixProperties._eval_atoms7  s3     	+AMM'!''5/*	+rL   c                 >     t               j                  d | D         S )Nc              3   :   K   | ]  }|s|j                     y wr   )free_symbolsr   s     rK   r   z6MatrixProperties._eval_free_symbols.<locals>.<genexpr>>  s     ?QQ^^?s   )r`  unionrj   s    rK   _eval_free_symbolsz#MatrixProperties._eval_free_symbols=  s    su{{?T?@@rL   c                 ,    t        fd| D              S )Nc              3   <   K   | ]  } |j                      y wr   )has)r   apatternss     rK   r   z-MatrixProperties._eval_has.<locals>.<genexpr>A  s     25155(#2r   r   rb   ro  s    `rK   	_eval_haszMatrixProperties._eval_has@  s    2T222rL   c                 Z     t         fdt         j                        D              syy)Nc              3      K   | ]=  }t        j                        D ]#  } ||f   ||f   z         j                   % ? y wr   r   rq   is_zero)r   ry   rz   rb   simpfuncs      rK   r   z;MatrixProperties._eval_is_anti_symmetric.<locals>.<genexpr>D  sL     q`efjfofo`pq[\8DAJad34<<q<qs   AAFTr   r   rp   )rb   rw  s   ``rK   _eval_is_anti_symmetricz(MatrixProperties._eval_is_anti_symmetricC  s     qeDIIFVqqrL   c                     t        | j                        D ],  }t        | j                        D ]  }||k7  s	| ||f   s  y . y)NFT)r   rp   rq   )rb   ry   rz   s      rK   _eval_is_diagonalz"MatrixProperties._eval_is_diagonalH  sK    tyy! 	!A499% !6d1a4j !	! rL   c                 t      j                   j                   j                   fd      }|j                  S )Nc                 J     | |f   || f   j                         z
        S r   	conjugatery   rz   rb   rw  s     rK   r   z<MatrixProperties._eval_is_matrix_hermitian.<locals>.<lambda>S  s/    8DAJQUVWYZVZQ[QeQeQgDg;h rL   r]   rp   rq   is_zero_matrixrb   rw  r   s   `` rK   _eval_is_matrix_hermitianz*MatrixProperties._eval_is_matrix_hermitianR  s*    ii		499.hi!!!rL   returnc                 \     d t         fdt         j                        D              S )Nc                     | |k(  ryyr   rS   ry   rz   s     rK   diracz1MatrixProperties._eval_is_Identity.<locals>.diracW  s    AvrL   c              3   t   K   | ]/  }t        j                        D ]  }||f    ||      k(    1 y wr   )r   rq   )r   ry   rz   r  rb   s      rK   r   z5MatrixProperties._eval_is_Identity.<locals>.<genexpr>\  sH      +tyy)+ 1:q!, +, +s   58rx  )rb   r  s   `@rK   _eval_is_Identityz"MatrixProperties._eval_is_IdentityV  s-    	
  +tyy)+ + 	+rL   c                 R     t         fdt         j                        D              S )Nc              3   |   K   | ]3  }t        |d z   j                        D ]  }||f   j                    5 yw)r*  Nru  r   ry   rz   rb   s      rK   r   z=MatrixProperties._eval_is_lower_hessenberg.<locals>.<genexpr>a  I      5!!a%35 1:%% 5% 5   9<rx  rj   s   `rK   _eval_is_lower_hessenbergz*MatrixProperties._eval_is_lower_hessenberg`  &     5!$)),5 5 	5rL   c                 R     t         fdt         j                        D              S )Nc              3   |   K   | ]3  }t        |d z   j                        D ]  }||f   j                    5 ywr   Nru  r  s      rK   r   z2MatrixProperties._eval_is_lower.<locals>.<genexpr>f  r  r  rx  rj   s   `rK   _eval_is_lowerzMatrixProperties._eval_is_lowere  r  rL   c                 ,    | j                  t              S r   )rm  r   rj   s    rK   _eval_is_symbolicz"MatrixProperties._eval_is_symbolicj  s    xxrL   c                 t      j                   j                   j                   fd      }|j                  S )Nc                 .     | |f   || f   z
        S r   rS   r  s     rK   r   z5MatrixProperties._eval_is_symmetric.<locals>.<lambda>n  s&    8DAJQUVWYZVZQ[D[;\ rL   r  r  s   `` rK   _eval_is_symmetricz#MatrixProperties._eval_is_symmetricm  s*    ii		499.\]!!!rL   c                 P    t        d | D              ryt        d | D              ry y)Nc              3   :   K   | ]  }|j                   d k(    yw)FNrv  r   s     rK   r   z8MatrixProperties._eval_is_zero_matrix.<locals>.<genexpr>r  s     0aqyyE!0s   Fc              3   8   K   | ]  }|j                   d u   y wr   r  r   s     rK   r   z8MatrixProperties._eval_is_zero_matrix.<locals>.<genexpr>t  s     /QqyyD /s   Trp  rj   s    rK   _eval_is_zero_matrixz%MatrixProperties._eval_is_zero_matrixq  s'    0400/$//rL   c                 T     t         fdt        d j                        D              S )Nc              3      K   | ]<  }t        t        j                  |d z
              D ]  }||f   j                    > ywr  r   r  rq   rv  r  s      rK   r   z=MatrixProperties._eval_is_upper_hessenberg.<locals>.<genexpr>y  sN      <!#dii!a%"9:< 1:%% <% <s   AAr*  rx  rj   s   `rK   _eval_is_upper_hessenbergz*MatrixProperties._eval_is_upper_hessenbergx  s(     <!!TYY/< < 	<rL   c                 F    | D cg c]  }|j                   r| c}S c c}w r   r  r   s     rK   _eval_valueszMatrixProperties._eval_values}  s    1aqyy111s   c                 d      fdt         j                        D        }t        d |D              S )Nc              3   ,   K   | ]  }||f     y wr   rS   r   ry   rb   s     rK   r   z;MatrixProperties._has_positive_diagonals.<locals>.<genexpr>       A1DAJA   c              3   4   K   | ]  }|j                     y wr   )is_positiver   xs     rK   r   z;MatrixProperties._has_positive_diagonals.<locals>.<genexpr>  s     A1A   r   rp   r   rb   diagonal_entriess   ` rK   _has_positive_diagonalsz(MatrixProperties._has_positive_diagonals  s)    Adii0@AA0@AAArL   c                 d      fdt         j                        D        }t        d |D              S )Nc              3   ,   K   | ]  }||f     y wr   rS   r  s     rK   r   z>MatrixProperties._has_nonnegative_diagonals.<locals>.<genexpr>  r  r  c              3   4   K   | ]  }|j                     y wr   )is_nonnegativer  s     rK   r   z>MatrixProperties._has_nonnegative_diagonals.<locals>.<genexpr>  s     Da))Dr  r  r  s   ` rK   _has_nonnegative_diagonalsz+MatrixProperties._has_nonnegative_diagonals  s)    Adii0@AD3CDDDrL   c                 V    t        d |D              }|st        f} | j                  | S )av  Returns the atoms that form the current object.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> from sympy import Matrix
        >>> Matrix([[x]])
        Matrix([[x]])
        >>> _.atoms()
        {x}
        >>> Matrix([[x, y], [y, x]])
        Matrix([
        [x, y],
        [y, x]])
        >>> _.atoms()
        {x, y}
        c              3   V   K   | ]!  }t        |t              r|n
t        |       # y wr   )rD   r   )r   ts     rK   r   z)MatrixProperties.atoms.<locals>.<genexpr>  s"     K:a.aDG;Ks   '))tupler   re  )rb   rc  s     rK   rb  zMatrixProperties.atoms  s1    ( KUKKGEt''rL   c                 "    | j                         S )zReturns the free symbols within the matrix.

        Examples
        ========

        >>> from sympy.abc import x
        >>> from sympy import Matrix
        >>> Matrix([[x], [1]]).free_symbols
        {x}
        )rj  rj   s    rK   rh  zMatrixProperties.free_symbols  s     &&((rL   c                       | j                   | S )a  Test whether any subexpression matches any of the patterns.

        Examples
        ========

        >>> from sympy import Matrix, SparseMatrix, Float
        >>> from sympy.abc import x, y
        >>> A = Matrix(((1, x), (0.2, 3)))
        >>> B = SparseMatrix(((1, x), (0.2, 3)))
        >>> A.has(x)
        True
        >>> A.has(y)
        False
        >>> A.has(Float)
        True
        >>> B.has(x)
        True
        >>> B.has(y)
        False
        >>> B.has(Float)
        True
        )rr  rq  s     rK   rm  zMatrixProperties.has  s    . t~~x((rL   c                 n    |}t        |      s|rt        nd }| j                  sy| j                  |      S )a  Check if matrix M is an antisymmetric matrix,
        that is, M is a square matrix with all M[i, j] == -M[j, i].

        When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
        simplified before testing to see if it is zero. By default,
        the SymPy simplify function is used. To use a custom function
        set simplify to a function that accepts a single argument which
        returns a simplified expression. To skip simplification, set
        simplify to False but note that although this will be faster,
        it may induce false negatives.

        Examples
        ========

        >>> from sympy import Matrix, symbols
        >>> m = Matrix(2, 2, [0, 1, -1, 0])
        >>> m
        Matrix([
        [ 0, 1],
        [-1, 0]])
        >>> m.is_anti_symmetric()
        True
        >>> x, y = symbols('x y')
        >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
        >>> m
        Matrix([
        [ 0, 0, x],
        [-y, 0, 0]])
        >>> m.is_anti_symmetric()
        False

        >>> from sympy.abc import x, y
        >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
        ...                   -(x + 1)**2, 0, x*y,
        ...                   -y, -x*y, 0])

        Simplification of matrix elements is done by default so even
        though two elements which should be equal and opposite would not
        pass an equality test, the matrix is still reported as
        anti-symmetric:

        >>> m[0, 1] == -m[1, 0]
        False
        >>> m.is_anti_symmetric()
        True

        If ``simplify=False`` is used for the case when a Matrix is already
        simplified, this will speed things up. Here, we see that without
        simplification the matrix does not appear anti-symmetric:

        >>> print(m.is_anti_symmetric(simplify=False))
        None

        But if the matrix were already expanded, then it would appear
        anti-symmetric and simplification in the is_anti_symmetric routine
        is not needed:

        >>> m = m.expand()
        >>> m.is_anti_symmetric(simplify=False)
        True
        c                     | S r   rS   r  s    rK   r   z4MatrixProperties.is_anti_symmetric.<locals>.<lambda>	      A rL   F)r   r   r  ry  rb   simplifyrw  s      rK   is_anti_symmetricz"MatrixProperties.is_anti_symmetric  s6    ~ (#$,y+H~~++H55rL   c                 "    | j                         S )a.  Check if matrix is diagonal,
        that is matrix in which the entries outside the main diagonal are all zero.

        Examples
        ========

        >>> from sympy import Matrix, diag
        >>> m = Matrix(2, 2, [1, 0, 0, 2])
        >>> m
        Matrix([
        [1, 0],
        [0, 2]])
        >>> m.is_diagonal()
        True

        >>> m = Matrix(2, 2, [1, 1, 0, 2])
        >>> m
        Matrix([
        [1, 1],
        [0, 2]])
        >>> m.is_diagonal()
        False

        >>> m = diag(1, 2, 3)
        >>> m
        Matrix([
        [1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]])
        >>> m.is_diagonal()
        True

        See Also
        ========

        is_lower
        is_upper
        sympy.matrices.matrixbase.MatrixCommon.is_diagonalizable
        diagonalize
        )r{  rj   s    rK   is_diagonalzMatrixProperties.is_diagonal  s    R %%''rL   c                       j                   sy j                  \  } fdt        fdt        |      D              S )a  Tests if the matrix is row weakly diagonally dominant.

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

        A $n, n$ matrix $A$ is row weakly diagonally dominant if

        .. math::
            \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
            \left|A_{i, j}\right| \quad {\text{for all }}
            i \in \{ 0, ..., n-1 \}

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
        >>> A.is_weakly_diagonally_dominant
        True

        >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
        >>> A.is_weakly_diagonally_dominant
        False

        >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
        >>> A.is_weakly_diagonally_dominant
        True

        Notes
        =====

        If you want to test whether a matrix is column diagonally
        dominant, you can apply the test after transposing the matrix.
        Fc                     j                   }t              D ]  }| |k7  s	|t        | |f         z  } t        | | f         |z
  j                  S r   )r   r   r   r  ry   	summationrz   rq   rb   s      rK   test_rowz@MatrixProperties.is_weakly_diagonally_dominant.<locals>.test_rowc  s[    		I4[ 16T!Q$Z0I1 QT
Oi/???rL   c              3   .   K   | ]  } |        y wr   rS   r   ry   r  s     rK   r   zAMatrixProperties.is_weakly_diagonally_dominant.<locals>.<genexpr>j       :!:   r  rn   r   r   rb   rp   rq   r  s   ` @@rK   is_weakly_diagonally_dominantz.MatrixProperties.is_weakly_diagonally_dominant:  s:    H ~~ZZ
d	@ :eDk:::rL   c                       j                   sy j                  \  } fdt        fdt        |      D              S )a  Tests if the matrix is row strongly diagonally dominant.

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

        A $n, n$ matrix $A$ is row strongly diagonally dominant if

        .. math::
            \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
            \left|A_{i, j}\right| \quad {\text{for all }}
            i \in \{ 0, ..., n-1 \}

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
        >>> A.is_strongly_diagonally_dominant
        False

        >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
        >>> A.is_strongly_diagonally_dominant
        False

        >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
        >>> A.is_strongly_diagonally_dominant
        True

        Notes
        =====

        If you want to test whether a matrix is column diagonally
        dominant, you can apply the test after transposing the matrix.
        Fc                     j                   }t              D ]  }| |k7  s	|t        | |f         z  } t        | | f         |z
  j                  S r   )r   r   r   r  r  s      rK   r  zBMatrixProperties.is_strongly_diagonally_dominant.<locals>.test_row  s[    		I4[ 16T!Q$Z0I1 QT
Oi/<<<rL   c              3   .   K   | ]  } |        y wr   rS   r  s     rK   r   zCMatrixProperties.is_strongly_diagonally_dominant.<locals>.<genexpr>  r  r  r  r  s   ` @@rK   is_strongly_diagonally_dominantz0MatrixProperties.is_strongly_diagonally_dominantl  s9    H ~~ZZ
d	= :eDk:::rL   c                 F    | j                   sy| j                  t              S )ag  Checks if the matrix is Hermitian.

        In a Hermitian matrix element i,j is the complex conjugate of
        element j,i.

        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy import I
        >>> from sympy.abc import x
        >>> a = Matrix([[1, I], [-I, 1]])
        >>> a
        Matrix([
        [ 1, I],
        [-I, 1]])
        >>> a.is_hermitian
        True
        >>> a[0, 0] = 2*I
        >>> a.is_hermitian
        False
        >>> a[0, 0] = x
        >>> a.is_hermitian
        >>> a[0, 1] = a[1, 0]*I
        >>> a.is_hermitian
        False
        F)r  r  r   rj   s    rK   is_hermitianzMatrixProperties.is_hermitian  s    : ~~--i88rL   c                 <    | j                   sy| j                         S NF)r  r  rj   s    rK   is_IdentityzMatrixProperties.is_Identity  s    ~~%%''rL   c                 "    | j                         S )a-  Checks if the matrix is in the lower-Hessenberg form.

        The lower hessenberg matrix has zero entries
        above the first superdiagonal.

        Examples
        ========

        >>> from sympy import Matrix
        >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
        >>> a
        Matrix([
        [1, 2, 0, 0],
        [5, 2, 3, 0],
        [3, 4, 3, 7],
        [5, 6, 1, 1]])
        >>> a.is_lower_hessenberg
        True

        See Also
        ========

        is_upper_hessenberg
        is_lower
        )r  rj   s    rK   is_lower_hessenbergz$MatrixProperties.is_lower_hessenberg      6 --//rL   c                 "    | j                         S )al  Check if matrix is a lower triangular matrix. True can be returned
        even if the matrix is not square.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(2, 2, [1, 0, 0, 1])
        >>> m
        Matrix([
        [1, 0],
        [0, 1]])
        >>> m.is_lower
        True

        >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5])
        >>> m
        Matrix([
        [0, 0, 0],
        [2, 0, 0],
        [1, 4, 0],
        [6, 6, 5]])
        >>> m.is_lower
        True

        >>> from sympy.abc import x, y
        >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
        >>> m
        Matrix([
        [x**2 + y, x + y**2],
        [       0,    x + y]])
        >>> m.is_lower
        False

        See Also
        ========

        is_upper
        is_diagonal
        is_lower_hessenberg
        )r  rj   s    rK   is_lowerzMatrixProperties.is_lower  s    V ""$$rL   c                 4    | j                   | j                  k(  S )a/  Checks if a matrix is square.

        A matrix is square if the number of rows equals the number of columns.
        The empty matrix is square by definition, since the number of rows and
        the number of columns are both zero.

        Examples
        ========

        >>> from sympy import Matrix
        >>> a = Matrix([[1, 2, 3], [4, 5, 6]])
        >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> c = Matrix([])
        >>> a.is_square
        False
        >>> b.is_square
        True
        >>> c.is_square
        True
        r   rj   s    rK   r  zMatrixProperties.is_square  s    , yyDII%%rL   c                 "    | j                         S )zChecks if any elements contain Symbols.

        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy.abc import x, y
        >>> M = Matrix([[x, y], [1, 0]])
        >>> M.is_symbolic()
        True

        )r  rj   s    rK   is_symboliczMatrixProperties.is_symbolic(  s     %%''rL   c                 n    |}t        |      s|rt        nd }| j                  sy| j                  |      S )a  Check if matrix is symmetric matrix,
        that is square matrix and is equal to its transpose.

        By default, simplifications occur before testing symmetry.
        They can be skipped using 'simplify=False'; while speeding things a bit,
        this may however induce false negatives.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(2, 2, [0, 1, 1, 2])
        >>> m
        Matrix([
        [0, 1],
        [1, 2]])
        >>> m.is_symmetric()
        True

        >>> m = Matrix(2, 2, [0, 1, 2, 0])
        >>> m
        Matrix([
        [0, 1],
        [2, 0]])
        >>> m.is_symmetric()
        False

        >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
        >>> m
        Matrix([
        [0, 0, 0],
        [0, 0, 0]])
        >>> m.is_symmetric()
        False

        >>> from sympy.abc import x, y
        >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
        >>> m
        Matrix([
        [         1, x**2 + 2*x + 1, y],
        [(x + 1)**2,              2, 0],
        [         y,              0, 3]])
        >>> m.is_symmetric()
        True

        If the matrix is already simplified, you may speed-up is_symmetric()
        test by using 'simplify=False'.

        >>> bool(m.is_symmetric(simplify=False))
        False
        >>> m1 = m.expand()
        >>> m1.is_symmetric(simplify=False)
        True
        c                     | S r   rS   r  s    rK   r   z/MatrixProperties.is_symmetric.<locals>.<lambda>p  r  rL   F)r   r   r  r  r  s      rK   r  zMatrixProperties.is_symmetric7  s6    n (#$,y+H~~&&x00rL   c                 "    | j                         S )a(  Checks if the matrix is the upper-Hessenberg form.

        The upper hessenberg matrix has zero entries
        below the first subdiagonal.

        Examples
        ========

        >>> from sympy import Matrix
        >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
        >>> a
        Matrix([
        [1, 4, 2, 3],
        [3, 4, 1, 7],
        [0, 2, 3, 4],
        [0, 0, 1, 3]])
        >>> a.is_upper_hessenberg
        True

        See Also
        ========

        is_lower_hessenberg
        is_upper
        )r  rj   s    rK   is_upper_hessenbergz$MatrixProperties.is_upper_hessenbergw  r  rL   c                 T     t         fdt        d j                        D              S )a$  Check if matrix is an upper triangular matrix. True can be returned
        even if the matrix is not square.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(2, 2, [1, 0, 0, 1])
        >>> m
        Matrix([
        [1, 0],
        [0, 1]])
        >>> m.is_upper
        True

        >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0])
        >>> m
        Matrix([
        [5, 1, 9],
        [0, 4, 6],
        [0, 0, 5],
        [0, 0, 0]])
        >>> m.is_upper
        True

        >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
        >>> m
        Matrix([
        [4, 2, 5],
        [6, 1, 1]])
        >>> m.is_upper
        False

        See Also
        ========

        is_lower
        is_diagonal
        is_upper_hessenberg
        c              3      K   | ]9  }t        t        |j                              D ]  }||f   j                    ; y wr   r  r  s      rK   r   z,MatrixProperties.is_upper.<locals>.<genexpr>  sJ      6!#a"346 1:%% 6% 6s   ?Ar   rx  rj   s   `rK   is_upperzMatrixProperties.is_upper  s+    T  6!!TYY/6 6 	6rL   c                 "    | j                         S )a,  Checks if a matrix is a zero matrix.

        A matrix is zero if every element is zero.  A matrix need not be square
        to be considered zero.  The empty matrix is zero by the principle of
        vacuous truth.  For a matrix that may or may not be zero (e.g.
        contains a symbol), this will be None

        Examples
        ========

        >>> from sympy import Matrix, zeros
        >>> from sympy.abc import x
        >>> a = Matrix([[0, 0], [0, 0]])
        >>> b = zeros(3, 4)
        >>> c = Matrix([[0, 1], [0, 0]])
        >>> d = Matrix([])
        >>> e = Matrix([[x, 0], [0, 0]])
        >>> a.is_zero_matrix
        True
        >>> b.is_zero_matrix
        True
        >>> c.is_zero_matrix
        False
        >>> d.is_zero_matrix
        True
        >>> e.is_zero_matrix
        )r  rj   s    rK   r  zMatrixProperties.is_zero_matrix  s    : ((**rL   c                 "    | j                         S )zReturn non-zero values of self.)r  rj   s    rK   valueszMatrixProperties.values  s      ""rL   NT)(r@   rM   rN   ro   re  rj  rr  ry  r{  r  r   r  r  r  r  r  r  r  r  r  r  rb  rs   rh  rm  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rS   rL   rK   r*   r*   4  sn   0A3
"+9 +5
5
 "<
2BE(2 ) ))2E6N)(V /; /;b /; /;b 9 9B (Y ( (
 0 08 *% *%X & &.(>1@ 0 08 +6 +6Z + +<#rL   r*   c                      e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd%dZd Zd Zd&dZ	 	 d'dZed        Zd(dZd)dZd)dZd%dZd*dZd+dZd Zd Zd Zd Zed        Zed        Z d Z!d  Z"d! Z#d" Z$d,d#Z%d,d$Z&y)-r+   zaProvides basic matrix shape and elementwise
    operations.  Should not be instantiated directly.c                 >    | j                         j                         S r   )	transposer  rj   s    rK   _eval_adjointzMatrixOperations._eval_adjoint  s    ~~))++rL   c           
          | j                  | j                  | j                  | D cg c]
  } ||       c}      }|S c c}w r   r}   )rb   fr  outs       rK   _eval_applyfuncz MatrixOperations._eval_applyfunc  s6    ii		499T.Bqt.BC
 /Cs   >c                 V    | j                  t              | j                  t              fS r   )	applyfuncr   r   rj   s    rK   _eval_as_real_imagz#MatrixOperations._eval_as_real_imag  s    r"DNN2$677rL   c                 &    | j                  d       S )Nc                 "    | j                         S r   r~  r  s    rK   r   z2MatrixOperations._eval_conjugate.<locals>.<lambda>  s     rL   r  rj   s    rK   _eval_conjugatez MatrixOperations._eval_conjugate  s    ~~566rL   c                 v     t        |       fd} j                   j                   j                  |      S )Nc                     | |   f   S r   rS   ry   rz   mappingrb   s     rK   r|   z2MatrixOperations._eval_permute_cols.<locals>.entry  s    71:&&rL   r   r]   rp   rq   rb   permr|   r  s   `  @rK   _eval_permute_colsz#MatrixOperations._eval_permute_cols  .    t*	' yyDIIu55rL   c                 v     t        |       fd} j                   j                   j                  |      S )Nc                     |    |f   S r   rS   r  s     rK   r|   z2MatrixOperations._eval_permute_rows.<locals>.entry  s    
A&&rL   r  r  s   `  @rK   _eval_permute_rowsz#MatrixOperations._eval_permute_rows   r  rL   c                 R     t         fdt         j                        D              S )Nc              3   ,   K   | ]  }||f     y wr   rS   r  s     rK   r   z/MatrixOperations._eval_trace.<locals>.<genexpr>
  s     8!41:8r  )sumr   rp   rj   s   `rK   _eval_tracezMatrixOperations._eval_trace	  s    8uTYY'7888rL   c                 X      j                   j                   j                   fd      S )Nc                     || f   S r   rS   ry   rz   rb   s     rK   r   z2MatrixOperations._eval_transpose.<locals>.<lambda>  s    DAJ rL   )r]   rq   rp   rj   s   `rK   _eval_transposez MatrixOperations._eval_transpose  s    yyDII/FGGrL   c                 "    | j                         S )z-Conjugate transpose or Hermitian conjugation.)r  rj   s    rK   adjointzMatrixOperations.adjoint  s    !!##rL   c                 P    t        |      st        d      | j                  |      S )aL  Apply a function to each element of the matrix.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(2, 2, lambda i, j: i*2+j)
        >>> m
        Matrix([
        [0, 1],
        [2, 3]])
        >>> m.applyfunc(lambda i: 2*i)
        Matrix([
        [0, 2],
        [4, 6]])

        z`f` must be callable.)callabler   r  )rb   r  s     rK   r  zMatrixOperations.applyfunc  s(    $ {344##A&&rL   c                 "    | j                         S )z@Returns a tuple containing the (real, imaginary) part of matrix.)r  )rb   deephintss      rK   as_real_imagzMatrixOperations.as_real_imag*  s     &&((rL   c                 "    | j                         S )a#  Return the by-element conjugation.

        Examples
        ========

        >>> from sympy import SparseMatrix, I
        >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
        >>> a
        Matrix([
        [1, 2 + I],
        [3,     4],
        [I,    -I]])
        >>> a.C
        Matrix([
        [ 1, 2 - I],
        [ 3,     4],
        [-I,     I]])

        See Also
        ========

        transpose: Matrix transposition
        H: Hermite conjugation
        sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
        )r  rj   s    rK   r  zMatrixOperations.conjugate/  s    4 ##%%rL   c                 ,    | j                  fd      S )Nc                 (     | j                   di S NrS   )doit)r  r  s    rK   r   z'MatrixOperations.doit.<locals>.<lambda>L  s     rL   r  )rb   r  s    `rK   r   zMatrixOperations.doitK  s    ~~788rL   Nc                 B    ||||||d| j                  fd      S )&Apply evalf() to each element of self.)subsmaxnchopr3  quadverbosec                 *     | j                   fi S r   evalf)ry   r   optionss    rK   r   z(MatrixOperations.evalf.<locals>.<lambda>R  s    (=W(= rL   r  )	rb   r   r#  r$  r%  r3  r&  r'  r+  s	    `      @rK   r*  zMatrixOperations.evalfN  s(    tD6w0~~=>>rL   c	                 L   	 | j                  	f	d      S )a$  Apply core.function.expand to each entry of the matrix.

        Examples
        ========

        >>> from sympy.abc import x
        >>> from sympy import Matrix
        >>> Matrix(1, 1, [x*(x+1)])
        Matrix([[x*(x + 1)]])
        >>> _.expand()
        Matrix([[x**2 + x]])

        c           
      8   	  | j                   	fi S r   )expand)
r  basicr  r  logmodulusmulmultinomial
power_base	power_exps
    rK   r   z)MatrixOperations.expand.<locals>.<lambda>c  s+    ':y#sK)) rL   r  )
rb   r  r1  r4  r5  r2  r0  r3  r/  r  s
    `````````rK   r.  zMatrixOperations.expandT  s!     ~~    	rL   c                 .    | j                   j                  S )a  Return Hermite conjugate.

        Examples
        ========

        >>> from sympy import Matrix, I
        >>> m = Matrix((0, 1 + I, 2, 3))
        >>> m
        Matrix([
        [    0],
        [1 + I],
        [    2],
        [    3]])
        >>> m.H
        Matrix([[0, 1 - I, 2, 3]])

        See Also
        ========

        conjugate: By-element conjugation
        sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
        )r-  Crj   s    rK   HzMatrixOperations.Hg  s    0 vvxxrL   c                    ddl m} |dk(  rd}|dk(  rd}|dk(  rd}|d	vrt        d
j                  |            |dvrt        dj                  |            t	        ||t
        f      st        dj                  |            |dk(  r| j                  n| j                  t        fdt        t        |            D              st        d      |rFt	        ||      s:t	        |d   t
              r'|dk(  rt        t        |            } ||dz         }n ||dz         }|dk(  r| j                  |      S |dk(  r| j                  |      S y)a  Permute the rows or columns of a matrix by the given list of
        swaps.

        Parameters
        ==========

        perm : Permutation, list, or list of lists
            A representation for the permutation.

            If it is ``Permutation``, it is used directly with some
            resizing with respect to the matrix size.

            If it is specified as list of lists,
            (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
            from applying the product of cycles. The direction how the
            cyclic product is applied is described in below.

            If it is specified as a list, the list should represent
            an array form of a permutation. (e.g., ``[1, 2, 0]``) which
            would would form the swapping function
            `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.

        orientation : 'rows', 'cols'
            A flag to control whether to permute the rows or the columns

        direction : 'forward', 'backward'
            A flag to control whether to apply the permutations from
            the start of the list first, or from the back of the list
            first.

            For example, if the permutation specification is
            ``[[0, 1], [0, 2]]``,

            If the flag is set to ``'forward'``, the cycle would be
            formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.

            If the flag is set to ``'backward'``, the cycle would be
            formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.

            If the argument ``perm`` is not in a form of list of lists,
            this flag takes no effect.

        Examples
        ========

        >>> from sympy import eye
        >>> M = eye(3)
        >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
        Matrix([
        [0, 0, 1],
        [1, 0, 0],
        [0, 1, 0]])

        >>> from sympy import eye
        >>> M = eye(3)
        >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
        Matrix([
        [0, 1, 0],
        [0, 0, 1],
        [1, 0, 0]])

        Notes
        =====

        If a bijective function
        `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
        permutation.

        If the matrix `A` is the matrix to permute, represented as
        a horizontal or a vertical stack of vectors:

        .. math::
            A =
            \begin{bmatrix}
            a_0 \\ a_1 \\ \vdots \\ a_{n-1}
            \end{bmatrix} =
            \begin{bmatrix}
            \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
            \end{bmatrix}

        If the matrix `B` is the result, the permutation of matrix rows
        is defined as:

        .. math::
            B := \begin{bmatrix}
            a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
            \end{bmatrix}

        And the permutation of matrix columns is defined as:

        .. math::
            B := \begin{bmatrix}
            \alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
            \cdots & \alpha_{\sigma(n-1)}
            \end{bmatrix}
        r   )Permutationforwardsforward	backwardsbackwardcolumnsrq   )r<  r>  z?direction='{}' is an invalid kwarg. Try 'forward' or 'backward'r   z:orientation='{}' is an invalid kwarg. Try 'rows' or 'cols'zB{} must be a list, a list of lists, or a SymPy permutation object.rp   c              3   >   K   | ]  }d |cxk  xr k  nc   yw)r   NrS   )r   r  	max_indexs     rK   r   z+MatrixOperations.permute.<locals>.<genexpr>  s     D11&Y&&Ds   z`swap` indices out of range.r   )r  N)sympy.combinatoricsr:  r   r   rD   r   r   rp   rq   r   r   r   r   reversedr  r  )rb   r  orientation	directionr:  rA  s        @rK   permutezMatrixOperations.permute  sn   B 	4 
"!I#"I)# K33 ::@&:KM M.. 3396+3FH H $h 78117? ?
 "-!6DIIDII	DT
0CDD;<<
45tAw)I%HTN+t)A+6Dt)A+6D& **400& **400 !rL   c                 *    | j                  |d|      S )zAlias for
        ``self.permute(swaps, orientation='cols', direction=direction)``

        See Also
        ========

        permute
        rq   rD  rE  rF  rb   swapsrE  s      rK   permute_colszMatrixOperations.permute_cols
	       ||Ev|KKrL   c                 *    | j                  |d|      S )zAlias for
        ``self.permute(swaps, orientation='rows', direction=direction)``

        See Also
        ========

        permute
        rp   rH  rI  rJ  s      rK   permute_rowszMatrixOperations.permute_rows	  rM  rL   c                 ,    | j                  fd      S )a  Apply refine to each element of the matrix.

        Examples
        ========

        >>> from sympy import Symbol, Matrix, Abs, sqrt, Q
        >>> x = Symbol('x')
        >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
        Matrix([
        [ Abs(x)**2, sqrt(x**2)],
        [sqrt(x**2),  Abs(x)**2]])
        >>> _.refine(Q.real(x))
        Matrix([
        [  x**2, Abs(x)],
        [Abs(x),   x**2]])

        c                     t        |       S r   r   )r  assumptionss    rK   r   z)MatrixOperations.refine.<locals>.<lambda>2	  s    q+(> rL   r  )rb   rR  s    `rK   r   zMatrixOperations.refine 	  s    $ ~~>??rL   c                 <    | j                  fd      S )a  Replaces Function F in Matrix entries with Function G.

        Examples
        ========

        >>> from sympy import symbols, Function, Matrix
        >>> F, G = symbols('F, G', cls=Function)
        >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
        Matrix([
        [F(0), F(1)],
        [F(1), F(2)]])
        >>> N = M.replace(F,G)
        >>> N
        Matrix([
        [G(0), G(1)],
        [G(1), G(2)]])
        c                 0    | j                        S )N)mapsimultaneousexact)replace)r  FGrW  rU  rV  s    rK   r   z*MatrixOperations.replace.<locals>.<lambda>G	  s    aii1#LPUiV rL   r  )rb   rY  rZ  rU  rV  rW  s    `````rK   rX  zMatrixOperations.replace4	  s    $ ~~VX 	XrL   c                     |dz  }|dk(  r| S |dk(  r| dddddf   j                   S |dk(  r| ddddddf   S |dk(  r| dddddf   j                   S y)a  Rotates Matrix by 90 degrees

        Parameters
        ==========

        k : int
            Specifies how many times the matrix is rotated by 90 degrees
            (clockwise when positive, counter-clockwise when negative).

        Examples
        ========

        >>> from sympy import Matrix, symbols
        >>> A = Matrix(2, 2, symbols('a:d'))
        >>> A
        Matrix([
        [a, b],
        [c, d]])

        Rotating the matrix clockwise one time:

        >>> A.rot90(1)
        Matrix([
        [c, a],
        [d, b]])

        Rotating the matrix anticlockwise two times:

        >>> A.rot90(-2)
        Matrix([
        [d, c],
        [b, a]])
           r   r   NrS  r*  r9   )r-  )rb   r   mods      rK   rot90zMatrixOperations.rot90I	  s{    F c!8K!8"b>###!8"dd
##!8DbD>### rL   c                 ,    | j                  fd      S )aO  Apply simplify to each element of the matrix.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> from sympy import SparseMatrix, sin, cos
        >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
        Matrix([[x*sin(y)**2 + x*cos(y)**2]])
        >>> _.simplify()
        Matrix([[x]])
        c                 (     | j                   di S r  )r  )r  rV   s    rK   r   z+MatrixOperations.simplify.<locals>.<lambda>	  s    


(<V(< rL   r  rb   rV   s    `rK   r  zMatrixOperations.simplifyv	  s     ~~<==rL   c                     t              dk(  rDt        d   t        t        f      s+t	        d         rt        d         st        d         f| j                  fd      S )a[  Return a new matrix with subs applied to each entry.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> from sympy import SparseMatrix, Matrix
        >>> SparseMatrix(1, 1, [x])
        Matrix([[x]])
        >>> _.subs(x, y)
        Matrix([[y]])
        >>> Matrix(_).subs(y, x)
        Matrix([[x]])
        r   r   c                 (     | j                   i S r   )r#  )r  r\   rV   s    rK   r   z'MatrixOperations.subs.<locals>.<lambda>	  s    (?(? rL   )r   rD   dictr`  iterr   r   r  rb   r\   rV   s    ``rK   r#  zMatrixOperations.subs	  s[      t9>:d1gc{#CTRSW^ijnopjq^raM#D~~?@@rL   c                 h    | j                   | j                  k7  r
t               | j                         S )z
        Returns the trace of a square matrix i.e. the sum of the
        diagonal elements.

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix(2, 2, [1, 2, 3, 4])
        >>> A.trace()
        5

        )rp   rq   r%   r  rj   s    rK   tracezMatrixOperations.trace	  s,     99		!&((!!rL   c                 "    | j                         S )aa  
        Returns the transpose of the matrix.

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix(2, 2, [1, 2, 3, 4])
        >>> A.transpose()
        Matrix([
        [1, 3],
        [2, 4]])

        >>> from sympy import Matrix, I
        >>> m=Matrix(((1, 2+I), (3, 4)))
        >>> m
        Matrix([
        [1, 2 + I],
        [3,     4]])
        >>> m.transpose()
        Matrix([
        [    1, 3],
        [2 + I, 4]])
        >>> m.T == m.transpose()
        True

        See Also
        ========

        conjugate: By-element conjugation

        )r  rj   s    rK   r  zMatrixOperations.transpose	  s    B ##%%rL   c                 "    | j                         S )zMatrix transposition)r  rj   s    rK   r-  zMatrixOperations.T	       ~~rL   c                 "    | j                         S )zBy-element conjugationr~  rj   s    rK   r7  zMatrixOperations.C	  rk  rL   c                 &     | j                   |i |S )r"  r)  rf  s      rK   r   zMatrixOperations.n	  s    tzz4*6**rL   c                 ,    | j                  fd      S )ak  Return a new matrix with xreplace applied to each entry.

        Examples
        ========

        >>> from sympy.abc import x, y
        >>> from sympy import SparseMatrix, Matrix
        >>> SparseMatrix(1, 1, [x])
        Matrix([[x]])
        >>> _.xreplace({x: y})
        Matrix([[y]])
        >>> Matrix(_).xreplace({y: x})
        Matrix([[x]])
        c                 &    | j                        S r   )xreplace)r  rules    rK   r   z+MatrixOperations.xreplace.<locals>.<lambda>	  s    

4(8 rL   r  )rb   rq  s    `rK   rp  zMatrixOperations.xreplace	  s     ~~899rL   c                 .    t        j                  | fi |S r   )r+   r  ra  s     rK   _eval_simplifyzMatrixOperations._eval_simplify	  s      ((888rL   c                 <    ddl m | j                  fd      S )Nr   )trigsimpc                      | fi S r   rS   )r  optsru  s    rK   r   z1MatrixOperations._eval_trigsimp.<locals>.<lambda>	  s    (;d(; rL   )sympy.simplify.trigsimpru  r  )rb   rw  ru  s    `@rK   _eval_trigsimpzMatrixOperations._eval_trigsimp	  s    4~~;<<rL   c                 `      fd} j                   j                   j                  |      S )a  Return the elements on and above the kth diagonal of a matrix.
        If k is not specified then simply returns upper-triangular portion
        of a matrix

        Examples
        ========

        >>> from sympy import ones
        >>> A = ones(4)
        >>> A.upper_triangular()
        Matrix([
        [1, 1, 1, 1],
        [0, 1, 1, 1],
        [0, 0, 1, 1],
        [0, 0, 0, 1]])

        >>> A.upper_triangular(2)
        Matrix([
        [0, 0, 1, 1],
        [0, 0, 0, 1],
        [0, 0, 0, 0],
        [0, 0, 0, 0]])

        >>> A.upper_triangular(-1)
        Matrix([
        [1, 1, 1, 1],
        [1, 1, 1, 1],
        [0, 1, 1, 1],
        [0, 0, 1, 1]])

        c                 :    | z   |k  r| |f   S j                   S r   r   ry   rz   r   rb   s     rK   r|   z0MatrixOperations.upper_triangular.<locals>.entry
  $    !"Q!41:::rL   r}   rb   r   r|   s   `` rK   upper_triangularz!MatrixOperations.upper_triangular	  &    B	; yyDIIu55rL   c                 `      fd} j                   j                   j                  |      S )a  Return the elements on and below the kth diagonal of a matrix.
        If k is not specified then simply returns lower-triangular portion
        of a matrix

        Examples
        ========

        >>> from sympy import ones
        >>> A = ones(4)
        >>> A.lower_triangular()
        Matrix([
        [1, 0, 0, 0],
        [1, 1, 0, 0],
        [1, 1, 1, 0],
        [1, 1, 1, 1]])

        >>> A.lower_triangular(-2)
        Matrix([
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [1, 0, 0, 0],
        [1, 1, 0, 0]])

        >>> A.lower_triangular(1)
        Matrix([
        [1, 1, 0, 0],
        [1, 1, 1, 0],
        [1, 1, 1, 1],
        [1, 1, 1, 1]])

        c                 :    | z   |k\  r| |f   S j                   S r   r|  r}  s     rK   r|   z0MatrixOperations.lower_triangular.<locals>.entry?
  r~  rL   r}   r  s   `` rK   lower_triangularz!MatrixOperations.lower_triangular
  r  rL   r  )   Nd   FFNF)TNTTTTTT)rp   r<  )r<  )FTN)r   r  )'r@   rM   rN   ro   r  r  r  r  r  r  r  r  r  r  r  r  r   r*  r.  rs   r8  rF  rL  rO  r   rX  r^  r  r#  rh  r  r-  r7  r   rp  rs  ry  r  r  rS   rL   rK   r+   r+     s    9,87669H$'.)
&89? JN;?&  2G1R	L	L@(X*+$Z>A*"$!&F        +:"9
=$6N$6rL   r+   c                      e Zd ZdZdZd Zd Zd Zd Zd Z	d Z
d	 Zd*dZd Zd Zd Zd Z ed      d        Z ed      d        Z ed      d        Zd Z ed      d        Zd*dZd Zd Z ed      d        Zd*dZ ed      d         Z ed!      d"        Z ed#      d$        Zd*d%Z ed&      d'        Z  ed(      d)        Z!y
)+r,   zUProvides basic matrix arithmetic operations.
    Should not be instantiated directly.gQ$@c                 X      j                   j                   j                   fd      S )Nc                 $    t        | |f         S r   )r   r  s     rK   r   z,MatrixArithmetic._eval_Abs.<locals>.<lambda>M
  s    CQT
O rL   r}   rj   s   `rK   	_eval_AbszMatrixArithmetic._eval_AbsL
  s    yyDII/KLLrL   c                 \      j                   j                   j                   fd      S )Nc                 "    | |f   | |f   z   S r   rS   ry   rz   rc   rb   s     rK   r   z,MatrixArithmetic._eval_add.<locals>.<lambda>Q
  s    d1a4j5A;&> rL   r}   ra   s   ``rK   	_eval_addzMatrixArithmetic._eval_addO
  s%    yyDII>@ 	@rL   c                 `      fd} j                   j                  j                  |      S )Nc                     t        j                        D cg c]  }| |f   ||f   z   }}	 t        | S c c}w # t        t        f$ r t        d |      cY S w xY w)Nc                     | |z   S r   rS   )rn  bs     rK   r   zBMatrixArithmetic._eval_matrix_mul.<locals>.entry.<locals>.<lambda>\
  s
    1q5 rL   )r   rq   r
   r   r	   r   )ry   rz   r   r   rc   rb   s       rK   r|   z0MatrixArithmetic._eval_matrix_mul.<locals>.entryT
  so    16tyy1ABA4!9U1Q3Z'BCB7Cy  C |, 7 0#66	7s   :? AAr}   rb   rc   r|   s   `` rK   _eval_matrix_mulz!MatrixArithmetic._eval_matrix_mulS
  s%    	7 yyEJJ66rL   c                 \      j                   j                   j                   fd      S )Nc                 "    | |f   | |f   z  S r   rS   r  s     rK   r   z?MatrixArithmetic._eval_matrix_mul_elementwise.<locals>.<lambda>a
  s    D1IeAaCj<P rL   r}   ra   s   ``rK   _eval_matrix_mul_elementwisez-MatrixArithmetic._eval_matrix_mul_elementwise`
  s    yyDII/PQQrL   c                 `      fd} j                  j                   j                  |      S )Nc                 \     t         fdt        j                        D              S )Nc              3   <   K   | ]  }|f   |f   z    y wr   rS   )r   r   ry   rz   rc   rb   s     rK   r   zDMatrixArithmetic._eval_matrix_rmul.<locals>.entry.<locals>.<genexpr>e
  s&     GuQqSz$qs)+Gr   )r  r   rq   r  s   ``rK   r|   z1MatrixArithmetic._eval_matrix_rmul.<locals>.entryd
  s    GU5::5FGGGrL   r}   r  s   `` rK   _eval_matrix_rmulz"MatrixArithmetic._eval_matrix_rmulc
  s$    	HyyTYY66rL   c                     |dk(  r| S |dz  dk(  r| | j                  |dz
        }}n| j                  |dz        x}}|j                  |      S )Nr   r*  )_eval_pow_by_recursionmultiply)rb   numrn  r  s       rK   r  z'MatrixArithmetic._eval_pow_by_recursionh
  sX    !8K7a<44S1W=qA//q99Azz!}rL   c                    ddl m} | j                  d   }| j                         }| j	                         dd  } |||      }| j                  |      }| j                  |      }t        |      D ]  }|||   |z  z  }|| z  } |S )Nr   )linrec_coeffsr   )sympy.discrete.recurrencesr  rn   charpolyrY  rH  rP  r   )	rb   expr  r   prT  new_matansry   s	            rK   _eval_pow_by_cayleyz$MatrixArithmetic._eval_pow_by_cayleys
  s    <jjmMMO""12&vs+((3-jjos 	A6!9W$$CtOG	 
rL   Nc                    |dgt        |       z  }|dk(  r| S |dz  dk(  r| | j                  |dz
  |      }}n| j                  |dz  |      x}}|j                  |d      }t        |      }d g|z  }t        |      D ])  }||   rt	        ||   d      \  ||<   ||<   "||   ||<   + |j                  |j                  |j                  |      S )NTr   r*  )prevsimpF)dotprodsimp)withsimp)r   "_eval_pow_by_recursion_dotprodsimpr  r   r   r]   rp   rq   )	rb   r  r  rn  r  rB  lenmelemsry   s	            rK   r  z3MatrixArithmetic._eval_pow_by_recursion_dotprodsimp
  s   vc$i'H!8K7a<@@q% A 'qA ;;C1H% < ' 'A 

1%
0Att 	 A{(4QqTD(I%a(1+Q4a		  vvaffaffe,,rL   c                 \      j                   j                   j                   fd      S )Nc                     | |f   z  S r   rS   r  s     rK   r   z3MatrixArithmetic._eval_scalar_mul.<locals>.<lambda>
  s    D1IeO rL   r}   ra   s   ``rK   _eval_scalar_mulz!MatrixArithmetic._eval_scalar_mul
      yyDII/KLLrL   c                 \      j                   j                   j                   fd      S )Nc                     | |f   z  S r   rS   r  s     rK   r   z4MatrixArithmetic._eval_scalar_rmul.<locals>.<lambda>
  s    E$qs)O rL   r}   ra   s   ``rK   _eval_scalar_rmulz"MatrixArithmetic._eval_scalar_rmul
  r  rL   c                 \      j                   j                   j                   fd      S )Nc                 &    t        | |f         S r   r   r  s     rK   r   z,MatrixArithmetic._eval_Mod.<locals>.<lambda>
  s    CQT
E<R rL   r}   ra   s   ``rK   	_eval_ModzMatrixArithmetic._eval_Mod
  s    yyDII/RSSrL   c                 "    | j                         S )z5Returns a new matrix with entry-wise absolute values.)r  rj   s    rK   __abs__zMatrixArithmetic.__abs__
  s    ~~rL   __radd__c                    t        |t              rt        S t        |      }t	        |d      r>| j
                  |j
                  k7  r%t        d| j
                  d|j
                        t        |dd      r2| |}}|j                  t        ||      k7  r||}}|j                  |      S t        |dd      rt        j                  | |      S t        dt        |       dt        |            )	z?Return self + other, raising ShapeError if shapes do not match.rn   Matrix size mismatch: z + 	is_MatrixFis_MatrixLikezcannot add z and )rD   r!   NotImplemented
_matrixifyr=  rn   r$   getattrrJ   r   r  r,   r   r   )rb   rc   rn  r  s       rK   __add__zMatrixArithmetic.__add__
  s     eY'!!5! 5'"zzU[[( JJ"- . . 5+u-qA{{gam+!1;;q>!5/51#--dE::$t*d5kJKKrL   __rtruediv__c                 &    | | j                   |z  z  S r   r#  ra   s     rK   __truediv__zMatrixArithmetic.__truediv__
  s    txx%'((rL   __rmatmul__c                 z    t        |      }t        |dd      st        |dd      st        S | j                  |      S Nr  Fr  )r  r  r  __mul__ra   s     rK   
__matmul__zMatrixArithmetic.__matmul__
  s9    5!uk51'%Z_:`!!||E""rL   c                 ,    | j                  fd      S )Nc                     | z  S r   rS   )r  rc   s    rK   r   z*MatrixArithmetic.__mod__.<locals>.<lambda>
  s    E	 rL   r  ra   s    `rK   __mod__zMatrixArithmetic.__mod__
  s    ~~122rL   __rmul__c                 $    | j                  |      S )av  Return self*other where other is either a scalar or a matrix
        of compatible dimensions.

        Examples
        ========

        >>> from sympy import Matrix
        >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
        >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
        True
        >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> A*B
        Matrix([
        [30, 36, 42],
        [66, 81, 96]])
        >>> B*A
        Traceback (most recent call last):
        ...
        ShapeError: Matrices size mismatch.
        >>>

        See Also
        ========

        matrix_multiply_elementwise
        )r  ra   s     rK   r  zMatrixArithmetic.__mul__
  s    : }}U##rL   c           
         t        d|      }t        |      }t        |d      rwt        |j                        dk(  r_t        |dd      st        |dd      rE| j                  d   |j                  d   k7  r&t        d	| j                  d
|j                  d      t        |dd      rS| j                  |      }|r>|j                  |j                  |j                  |D cg c]  }t        |       c}      S |S t        |dd      rt        j                  | |      S t        |t              s	 | j                  |      S t"        S c c}w # t         $ r Y t"        S w xY w)a\  Same as __mul__() but with optional simplification.

        Parameters
        ==========

        dotprodsimp : bool, optional
            Specifies whether intermediate term algebraic simplification is used
            during matrix multiplications to control expression blowup and thus
            speed up calculation. Default is off.
        Frn   r*  r  Tr  r   r   r  z * .)r"   r  r=  r   rn   r  r$   r  r]   rp   rq   r   r,   rD   r   r  r   r  rb   rc   r  	isimpboolrB  es         rK   r  zMatrixArithmetic.multiply
  s@    0{C	5! E7#EKK(8A(=UK.UOT2zz!}A. JJ"- . . 5+u-%%e,Avvaffaff.J1|A.JKKH 5/51#44T5AA %*,,U33  /K  s    E/E 	EEc                     | j                   |j                   k7  r/t        dj                  | j                   |j                               | j                  |      S )a  Return the Hadamard product (elementwise product) of A and B

        Examples
        ========

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

        See Also
        ========

        sympy.matrices.matrixbase.MatrixBase.cross
        sympy.matrices.matrixbase.MatrixBase.dot
        multiply
        z!Matrix shapes must agree {} != {})rn   r$   r   r  ra   s     rK   multiply_elementwisez%MatrixArithmetic.multiply_elementwise  sI    * ::$@GG

TYT_T_`aa0077rL   c                 $    | j                  d      S )NrS  )r  rj   s    rK   __neg__zMatrixArithmetic.__neg__8  s    $$R((rL   __rpow__c                 $    | j                  |      S )z$Return self**exp a scalar or symbol.)pow)rb   r  s     rK   __pow__zMatrixArithmetic.__pow__;  s     xx}rL   c                 l   ||dvrt        d      | j                  | j                  k7  r
t               | t	        dd      }t              j                  r(j                  j                  j                  d       S dk(  rS t	        dd      }|2 |       r+j                  j                  j                  fd      S j                  rHdz  d	k(  r@j                  dk(  rj                  d	   z  gg      S d	k  r j                         |d
k(  r		  |      S |dk(  r0j                  rdz  d	k7  rt        d      j                        S |dk(  r0j                  rdz  d	k7  rt        d      j                        S |dk(  r0j                  rdz  d	k7  rt        d      j                        S |j                  rdz  d	k(  rwj                  rt!              j                  dk(  rdkD  r |      S t#        dd      rj                        S dkD  rj                        S j                        S |r		  |      S d	dlm}  |      S # t        $ r	 |d
k(  r Y +w xY w# t$        $ r  j&                  du sj(                  du r Y Lw xY w)a  Return self**exp a scalar or symbol.

        Parameters
        ==========

        method : multiply, mulsimp, jordan, cayley
            If multiply then it returns exponentiation using recursion.
            If jordan then Jordan form exponentiation will be used.
            If cayley then the exponentiation is done using Cayley-Hamilton
            theorem.
            If mulsimp then the exponentiation is done using recursion
            with dotprodsimp. This specifies whether intermediate term
            algebraic simplification is used during naive matrix power to
            control expression blowup and thus speed up calculation.
            If None, then it heuristically decides which method to use.

        N)r  mulsimpjordancayleyzNo such method_matrix_pow_by_jordan_blocksc                     t        | |k(        S r   )r:  r  s     rK   r   z&MatrixArithmetic.pow.<locals>.<lambda>^  s    s16{ rL   r   r  c                 &    | |k(  r
| |f   z  S dS )Nr   rS   )ry   rz   rn  r  s     rK   r   z&MatrixArithmetic.pow.<locals>.<lambda>d  s    a1fq1vs{ RS rL   r   r  r  z.cayley method is only valid for integer powersr  z/mulsimp method is only valid for integer powersr  z0multiply method is only valid for integer powersr*  i Ti'  F)MatPow)r   rp   rq   r%   r  r   rv  r]   	is_Numberinvr#   r   r  r  r  is_Floatr   r"   r&   
is_integerr  sympy.matrices.expressionsr  )rb   r  method
jordan_powr   r  rn  s    `    @rK   r  zMatrixArithmetic.powB  s   & &0["[,--99		!&((Q >E
cl;;66!&&!&&*BCC!8H1mT2HJ66!&&!&&*STT==S1W\vv{vv!c	{m,,QwdEEG X!#&
 x==C!GqL !QRR((--y ==C!GqL !RSS77<<z!==C!GqL !STT++C00^#'Q,||clvv{sV|!#&,T48;;C@@u,,S11//44!#& 	6a~Y  X% &F , 
 >>U*c.@.@E.I /Js$   'I5 J
 5JJ
&J32J3r  c                     | |z   S r   rS   ra   s     rK   r  zMatrixArithmetic.__radd__  s    e|rL   r  c                 z    t        |      }t        |dd      st        |dd      st        S | j                  |      S r  )r  r  r  r  ra   s     rK   r  zMatrixArithmetic.__rmatmul__  s9    5!uk51'%Z_:`!!}}U##rL   r  c                 $    | j                  |      S r   )	rmultiplyra   s     rK   r  zMatrixArithmetic.__rmul__  s    ~~e$$rL   c           
         t        d|      }t        |      }t        |d      r\t        |j                        dk(  rDt        |dd      st        |dd      r*| j                  d   |j                  d   k7  rt        d	      t        |dd      rS| j                  |      }|r>|j                  |j                  |j                  |D cg c]  }t        |       c}      S |S t        |dd      rt        j                  | |      S t        |t              s	 | j                  |      S t"        S c c}w # t         $ r Y t"        S w xY w)
a]  Same as __rmul__() but with optional simplification.

        Parameters
        ==========

        dotprodsimp : bool, optional
            Specifies whether intermediate term algebraic simplification is used
            during matrix multiplications to control expression blowup and thus
            speed up calculation. Default is off.
        Frn   r*  r  Tr  r   r   zMatrix size mismatch.)r"   r  r=  r   rn   r  r$   r  r]   rp   rq   r   r,   rD   r   r  r   r  r  s         rK   r  zMatrixArithmetic.rmultiply  s+    0{C	5! E7#EKK(8A(=UK.UOT2zz!}A. !899 5+u-&&u-Avvaffaff.J1|A.JKKH5/51#55dEBB %*--e44  /K  s   D+D0 0	E E__sub__c                     |  |z   S r   rS   rb   rn  s     rK   __rsub__zMatrixArithmetic.__rsub__  s    {rL   r  c                     | | z   S r   rS   r  s     rK   r  zMatrixArithmetic.__sub__  s    r{rL   r   )"r@   rM   rN   ro   _op_priorityr  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rS   rL   rK   r,   r,   F
  sn   , LM@7R7
	 -4MMT  :&L 'L2 >*) +) =)# *#3 :&$ '$<)V84) :& '\| 9% & <($ )$ 9%% &%&P 9% & :& 'rL   r,   c                       e Zd ZdZdZy)r-   zsAll common matrix operations including basic arithmetic, shaping,
    and special matrices like `zeros`, and `eye`.TN)r@   rM   rN   ro   	_diff_wrtrS   rL   rK   r-   r-     s    5IrL   r-   c                       e Zd ZdZdZ ee      ZdZe	j                  Ze	j                  ZdZdZed        ZddZd Zd	 Zd
 Zd Zed        Zy)_MinimalMatrixa  Class providing the minimum functionality
    for a matrix-like object and implementing every method
    required for a `MatrixRequired`.  This class does not have everything
    needed to become a full-fledged SymPy object, but it will satisfy the
    requirements of anything inheriting from `MatrixRequired`.  If you wish
    to make a specialized matrix type, make sure to implement these
    methods and properties with the exception of `__init__` and `__repr__`
    which are included for convenience.Tr9   Fc                      | |i |S r   rS   r[   s      rK   r]   z_MinimalMatrix._new  s    D#F##rL   Nc           	          t        |      r1t        |      D cg c]  }t        |      D ]  } |||        }}}|||}t        |d||f      \  }}	 |||}t        |d         }t        |      }|D cg c]  }|D ]  }|  }}}t         fd|D               _        ||c _         _	         j                   j                  t        d      y c c}}w c c}}w # t        t
        f$ r Y iw xY w)Nrn   r   c              3   @   K   | ]  }j                  |        y wr   )rU  )r   r  rb   s     rK   r   z*_MinimalMatrix.__init__.<locals>.<genexpr>  s     7aq)7s   z.Cannot initialize matrix with given parameters)r   r   r  r   r   r   r  r   rp   rq   rZ   )	rb   rp   rq   r   r  ry   rz   lr  s	   `        rK   __init__z_MinimalMatrix.__init__  s   c?&+DkG5;Ga3q!9G9GCG<CKCS'D$<8
d	|s1v;Ds8D!-1-a1-1-C- 7377#T	4999		 1%&VWW !2 H .I& 		s)    C$C& ;C C&  C& &C87C8c           	           fd} fd}t        |t              r|\  }}t        |t              st        |t              r |||      \  }}t        t	         j
                              |   t        t	         j                              |   c} fd|D        } j                  t        |      t              |D cg c]  } j                  |    c}      S  |||      } j                  |   S c c}w )Nc                    t        | t              st        | | dz   d      } t        | j                  j                         } t        |t              st        ||dz   d      }t        |j                  j                         }| |fS )zEnsure that row_slice and col_slice do not have
            `None` in their arguments.  Any integers are converted
            to slices of length 1r   N)rD   slicer   rp   rq   )	row_slice	col_slicerb   s     rK   _normalize_slicesz5_MinimalMatrix.__getitem__.<locals>._normalize_slices  sz     i/!)Y]DA	y00;<Ii/!)Y]DA	y00;<Iy))rL   c                 (    | j                   z  |z   S )zXReturn the index in _mat corresponding
            to the (i,j) position in the matrix. r   r  s     rK   _coord_to_indexz3_MinimalMatrix.__getitem__.<locals>._coord_to_index#  s     tyy=1$$rL   c              3   P   K   | ]  }D ]  }|j                   z  |z      y wr   r   )r   ry   rz   r   rb   s      rK   r   z-_MinimalMatrix.__getitem__.<locals>.<genexpr>1  s4      %#%11tyy=1, %, %s   #&)
rD   r  r  r   r   rp   rq   r]   r   r   )	rb   rg   r  r	  ry   rz   r   r   r   s	   `       @rK   rh   z_MinimalMatrix.__getitem__  s    	*	%
 c5!DAq!U#z!U'; )A.1%)%		*:%;A%>%)%		*:%;A%> #(%h %yyXH7>!?!$((1+!?A A
 "!Q'Cxx} "@s    C5c                     	 t        | |       | j                  |j                  k(  xr t        |       t        |      k(  S # t        $ r Y yw xY wr  )r   r   rn   r   ra   s     rK   rd   z_MinimalMatrix.__eq__;  sO    	D%  JJ%++%C$t*U*C	E  		s   A   	AAc                 4    | j                   | j                  z  S r   r   rj   s    rK   rk   z_MinimalMatrix.__len__C  s    yy""rL   c                 d    dj                  | j                  | j                  | j                        S )Nz_MinimalMatrix({}, {}, {}))r   rp   rq   r   rj   s    rK   __repr__z_MinimalMatrix.__repr__F  s(    +22499dii3788= 	=rL   c                 2    | j                   | j                  fS r   r   rj   s    rK   rn   z_MinimalMatrix.shapeJ  s    		499%%rL   )NNF)r@   rM   rN   ro   r  staticmethodr   rU  _class_priorityr   Zeror   Oner  r  is_MatrixExprrr   r]   r  rh   rd   rk   r  rs   rn   rS   rL   rK   r  r    s{    + MG$HO66D
%%CIM$ $X*%NE#= & &rL   r  c                       e Zd Zd Zd Zy)_CastableMatrixc                     | S r   rS   rj   s    rK   
as_mutablez_CastableMatrix.as_mutableP      rL   c                     | S r   rS   rj   s    rK   as_immutablez_CastableMatrix.as_immutableS  r  rL   N)r@   rM   rN   r  r  rS   rL   rK   r  r  O  s    rL   r  c                   *    e Zd ZdZdZdZd Zd Zd Zy)_MatrixWrappera  Wrapper class providing the minimum functionality for a matrix-like
    object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
    math operations should work on matrix-like objects. This one is intended for
    matrix-like objects which use the same indexing format as SymPy with respect
    to returning matrix elements instead of rows for non-tuple indexes.
    FTc                 >    || _         || _        |\  | _        | _        y r   )r   rn   rp   rq   )rb   r   rn   s      rK   r  z_MatrixWrapper.__init__b  s    
$	49rL   c                     t        |t              r$t        | j                  j	                  |            S t        | j                  j	                  || j
                  z  || j                  z  f            S r   )rD   r  r   r   rh   rp   rq   rf   s     rK   rh   z_MatrixWrapper.__getitem__g  sV    c5!488//455txx++SDII-=sTYY,OPQQrL   c                     | j                   | j                  t        fdt        | j                        D              S )Nc              3   ^   K   | ]$  }t              D ]  }t        ||f           & y wr   )r   r   )r   r   r   rq   r   s      rK   r   z*_MatrixWrapper.__iter__.<locals>.<genexpr>q  s0     V1%PT+VQGC1I&V&Vs   *-)r   rq   re  r   rp   )rb   rq   r   s    @@rK   __iter__z_MatrixWrapper.__iter__m  s/    hhyyVdii0@VVVrL   N)	r@   rM   rN   ro   r  r  r  rh   r"  rS   rL   rK   r  r  W  s$     IM%
RWrL   r  c                 X   t        | dd      st        | dd      r| S t        | dd      st        | dd      s| S d}t        | d      r%t        | j                        dk(  r=| j                  }n0t        | d      r$t        | d	      r| j                  | j
                  f}|rt        | |      S | S )
zIf `mat` is a Matrix or is matrix-like,
    return a Matrix or MatrixWrapper object.  Otherwise
    `mat` is passed through without modification.r  Fr  TNrn   r*  rp   rq   )r  r=  r   rn   rp   rq   r  )r   rn   s     rK   r  r  t  s    
 sK'73+O
3T*gc?D.Q
EsGsyy>QIIE	f	'#v"6388$c5))JrL   Nc                     t        | t              s&t        | dd      }| |       } nt        d| d      |#| dk  r| |z  } | dk\  r| |k  st        d| d      t        |       S )z>Return integer after making positive and validating against n.	__index__NzInvalid index a[r   r   zIndex out of range: a[)rD   r:  r  r   )rz   r   jindexs      rK   r   r     sn    aK.Aa9::}q5FAQ1q5A?@@q6MrL   c                    t        | dd      }t        |dd      }d||fvr1| j                  |j                  kD  r| j                  S |j                  S 	 ddl}t	        | |j
                        r|j                  S t	        ||j
                        r| j                  S t        d| j                  d|j                        # t        $ r Y 0w xY w)a  
    Get the type of the result when combining matrices of different types.

    Currently the strategy is that immutability is contagious.

    Examples
    ========

    >>> from sympy import Matrix, ImmutableMatrix
    >>> from sympy.matrices.matrixbase import classof
    >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
    >>> IM = ImmutableMatrix([[1, 2], [3, 4]])
    >>> classof(M, IM)
    <class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
    r  Nr   zIncompatible classes r   )r  r  rJ   numpyrD   ndarrayImportErrorr   )AB
priority_A
priority_Br(  s        rK   r   r     s      -t4J-t4JJ
++q000;;;; a';;a';;
Q[[!++N
OO  s   C   	CCr   )Iro   collectionsr   collections.abcr   inspectr   	functoolsr   sympy.assumptions.refiner   
sympy.corer	   r
   sympy.core.basicr   sympy.core.decoratorsr   sympy.core.logicr   r   sympy.core.numbersr   sympy.core.modr   sympy.core.singletonr   sympy.core.symbolr   sympy.core.sympifyr   $sympy.functions.elementary.complexesr   r   r   sympy.utilities.exceptionsr   	utilitiesr   r   sympy.polys.polytoolsr   sympy.utilities.iterablesr   r   sympy.utilities.miscr   r    sympy.tensor.arrayr!   r"   
exceptionsr#   r$   r%   r&   r'   rT   r   r5   rC   r(   r)   r*   r+   r,   r-   r  r  r  r  r   r   rS   rL   rK   <module>rE     s  	 $ $   + ( ! 7 1 &  " $ & < < @ . & : 3 ( 2   =7D =7@9E4 9Exu
*N u
*p(N (Bo
#~ o
#d\	6~ \	6@X~ Xv#%57Gd& d&N W W:2 "PrL   