
    wg                       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mZ d dlmZ d d	lmZ d d
lmZ d dlmZmZ d dlmZmZ d dlmZ d dlmZ d dl m!Z!m"Z"m#Z# d dl$m%Z% d dl&m'Z'm(Z(m)Z) d dl*m+Z+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7m8Z8 d dl9Z:d dlm;Z; d dl<m=Z= d dl>m?Z? d dl@mAZA d dlmBZB ddlCmDZDmEZF d d lGmHZH d d!l<mIZImJZJ d d"lKmLZLmMZM d d#lNmOZO d d$lPmQZQmRZR d d%lSmTZT d d&l<mUZU dd'lCmVZV dd(lWmXZX dd)lYmZZZm[Z[m\Z\m]Z] dd*lCm^Z^m_Z_ dd+l`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZo dd,lpmqZqmrZrmsZsmtZt dd-lumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZ dd.lmZmZmZmZmZmZmZmZmZ dd/lmZmZmZmZ dd0lmZmZmZmZmZmZmZmZmZmZmZmZmZmZ dd1lmZmZmZmZmZmZmZmZmZ dd2lmZmZmZmZ d3d4giZ G d5 d6e0      Zd7 Zd8 Zd9 Zd: Zd; Zd< Zd@d=Z G d> d?eeU      Zy)A    )defaultdict)Iterable)
isfunction)reducerefine)SympifyErrorAdd)AtomBasic)UndefinedKind)IntegerMod)SymbolDummy)sympify_sympifydiff)cancel)Absreimsstr)MaxMinsqrt)KroneckerDelta
LeviCivita)S)	Printable)
StrPrinter)explog)binomial	factorialN)Callable)reshape)Expr)Pow)uniquely_named_symbol   )_dotprodsimp	_simplify)Poly)flattenis_sequence)as_int
filldedent)call_highest_priority)	fuzzy_and	FuzzyBool)	NDimArray)NotIterable)_get_intermediate_simp_bool)
MatrixKind)MatrixError
ShapeErrorNonSquareMatrixErrorNonInvertibleMatrixError)_iszero_is_zero_after_expand_mul)_find_reasonable_pivot_find_reasonable_pivot_naive	_adjugate	_charpoly	_cofactor_cofactor_matrix_per_det_det_bareiss_det_berkowitz	_det_bird_det_laplace_det_LU_minor_minor_submatrix)_is_echelon_echelon_form_rank_rref)_diagonal_solve_lower_triangular_solve_upper_triangular_solve_cholesky_solve	_LDLsolve_LUsolve_QRsolve_gauss_jordan_solve_pinv_solve_cramer_solve_solve_solve_least_squares)	_pinv_inv_ADJ_inv_GE_inv_LU_inv_CH_inv_LDL_inv_QR_inv
_inv_block)_columnspace
_nullspace	_rowspace_orthogonalize)
_eigenvals_eigenvects_bidiagonalize_bidiagonal_decomposition_is_diagonalizable_diagonalize_is_positive_definite_is_positive_semidefinite_is_negative_definite_is_negative_semidefinite_is_indefinite_jordan_form_left_eigenvects_singular_values)	_rank_decomposition	_cholesky_LDLdecomposition_LUdecomposition_LUdecomposition_Simple_LUdecompositionFF_singular_value_decomposition_QRdecomposition_upper_hessenberg_decomposition)_connected_components#_connected_components_decomposition_strongly_connected_components,_strongly_connected_components_decomposition)zMatrixBase.is_indefinitezMatrixBase.is_positive_definitez#MatrixBase.is_positive_semidefinitezMatrixBase.is_negative_definitez#MatrixBase.is_negative_semidefinite
matplotlibc                      e Zd ZdZdZdZdZdZ ee	      Z
ej                  Zej                  ZdZdZdZdZed        Zd Zd	 Ze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 Z)d Z*d Z+d Z,ed        Z-d Z.d  Z/d! Z0d" Z1d4d#Z2d$ Z3d% Z4ed&        Z5d' Z6d( Z7d) Z8d5d*Z9ed+        Z:ed,        Z;ed-        Z<ed6d/e=fd0       Z>ed1        Z?ed2        Z@ed3        ZAed4dddd5d6       ZBed7d7       ZCed8d.d8d9       ZDed7d:       ZEed7d;       ZFed<        ZGed=        ZHd> ZId? ZJd@ ZKdA ZLdB ZMdC ZNdD ZOdE ZPdF ZQdGeRfdHZSdI ZTdJ ZUdK ZVdL ZWdM ZXdN ZYdO ZZdP Z[dQ Z\dR Z]edS        Z^dT Z_d9dUZ`dV ZaedW        ZbedX        ZcedY        ZdedGeRfdZ       Zeed[        Zfed\        Zged]        Zhd^ Zid9d_Zjed`        Zkeda        Zledb        Zmdc Zndd Zode Zpdf Zqdg Zrdh Zsdi Ztdj Zudk Zvdl Zwdm Zxdn Zydo Zzd9dpZ{dq Z|dr Z}d:dsZ~	 	 d;dtZedu        Zd<dvZd=dwZd=dxZd9dyZd>dzZd?d{Zd| Zd} Zd~ Zd Zed        Zed        Zd Zd Zd Zd Zd4dZd4dZd Zd Zd Zd Zd Zd Zd Zd7dZd Zd Zd Zd Z ed      d        Z ed      d        Z ed      d        Zd Z ed      d        Zd7dZd Zd Z ed      d        Zd7dZ ed      d        Z ed      d        Z ed      d        Zd7dZ ed      d        Z ed      d        ZefdZd ZedfdZd Zd Zd Zd@dZdefdZd@dZd@dZdAdZd Zd@dZd Zej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ed4d4fdZed        Zed4fdZd Zed4ddfdZej                  e_        ej                  e_        ej                  e_        ej                  e_        dBdZdÄ ZdĄ Zdń ZdƄ ZdǄ ZdȄ ZߐdCdɄZdCdʄZdDd˄Zd4efd̄ZdDd̈́Zd΄ Zej                  e_        ej                  e_        ej                  e_        ej                  e_         ee      Zd9dτZdefdЄZdDdфZdEd҄Zd9dӄZd9dԄZedՄ        Zedք        Zedׄ        Zed؄        Zedل        Zd9dڄZdۄ Zd܄ Zej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        e j                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ddݜdބZd߄ Zd Zd Z	d Z
 ed      efdZd Zd Zd Zd Zd@dZd Zd Zd Zd9dZd@dZd Zd Zd ZedGefd       Zd ZedfdZd Zd Z d Z!d7dZ"ed        Z#ed        Z$ed        Z%d Z&d Z'd Z(d Z)d Z*d  Z+d Z,ed        Z-d8dZ.d Z/d Z0d Z1d Z2d Z3e4fd	Z5d
 Z6d Z7d Z8efdZ9d7dZ:dFdZ;d Z<	 	 dGdZ=ed4fdZ>d9dZ?d9dZ@edd4fdZAedd4fdZBd ZCd ZDd ZEd ZFd ZGd ZHd ZId ZJd ZKefd ZLd! ZMdDd"ZNd7d#ZOdHd$ZPdId%ZQdJd&ZRdKd'ZSefd(ZTefd)ZUefd*ZVefd+ZWefd,ZXefd-ZYefd.ZZded4fd/Z[d0 Z\d1 Z]d2 Z^d9d3Z_e`j                  Zaebj                  e>_        ecj                  e?_        edj                  e@_        eej                  eA_        efj                  eB_        egj                  eC_        ehj                  eD_        eij                  eE_        ejj                  eF_        ekj                  eG_        elj                  eH_        emj                  eI_        enj                  eJ_        eoj                  eK_        epj                  eL_        eqj                  eM_        erj                  eN_        esj                  eO_        etj                  eP_        euj                  eQ_        evj                  eR_        ewj                  eS_        exj                  eT_        eyj                  eV_        ezj                  eW_        e{j                  eX_        e|j                  eY_        e}j                  eZ_        e~j                  eU_        ej                  e[_        ej                  e\_        ej                  e]_        ej                  e^_        ej                  e__        y(L  
MatrixBasezsAll common matrix operations including basic arithmetic, shaping,
    and special matrices like `zeros`, and `eye`.gQ$@   T   Nc                     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)clsargskwargss      ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/matrices/matrixbase.py_newzMatrixBase._newv       
 ""CDD    c                     t        d      )Nr   r   selfothers     r   __eq__zMatrixBase.__eq__}   s    !"CDDr   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.r   r   )r   keys     r   __getitem__zMatrixBase.__getitem__   r   r   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
        rowscolsr   s    r   shapezMatrixBase.shape   s      		499%%r   c                 f      fd} j                   j                   j                  dz
  |      S )Nc                 0    |k  r| |f   S | |dz   f   S Nr.    )ijcolr   s     r   entryz'MatrixBase._eval_col_del.<locals>.entry   s(    !"S41:<d1a!e8n<r   r.   r   r   r   )r   r   r   s   `` r   _eval_col_delzMatrixBase._eval_col_del   s'    	=yyDIIM599r   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r   )r   r   r   posr   s     r   r   z*MatrixBase._eval_col_insert.<locals>.entry   sY    3wAqDz!,C%**,,QCZ((1uzz>)**r   r   )r   r   r   r   s   ``` r   _eval_col_insertzMatrixBase._eval_col_insert   s.    	+ yyDII

$:EBBr   c                       j                    fd}t               j                   j                   j                   z    j                  |      S )Nc                 0    | k  r| |f   S | z
  |f   S r   r   )r   r   r   r   r   s     r   r   z(MatrixBase._eval_col_join.<locals>.entry   s+    4xAqDz!T1%%r   )r   classofr   r   )r   r   r   r   s   `` @r   _eval_col_joinzMatrixBase._eval_col_join   sE    yy	&
 tU#((UZZ)?).0 	0r   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   r   ).0r   r   r   colsLists      r   	<genexpr>z+MatrixBase._eval_extract.<locals>.<genexpr>   s%     DA8Da1t8a<D<D   )listr   r   len)r   rowsListr   matindicesr   r   s     `   @r   _eval_extractzMatrixBase._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   )r   anyappend)Mr   to_the_rightto_the_bottomrecurse_sub_blocks
sub_blockss       r   r   z<MatrixBase._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! "r   r   )r   r   r   s    @@r   _eval_get_diag_blocksz MatrixBase._eval_get_diag_blocks   s    
	( 	4 r   c                 f      fd} j                   j                  dz
   j                  |      S )Nc                 0    | k  r| |f   S | dz   |f   S r   r   )r   r   rowr   s     r   r   z'MatrixBase._eval_row_del.<locals>.entry   s(    !"S41:<d1q5!8n<r   r.   r   )r   r   r   s   `` r   _eval_row_delzMatrixBase._eval_row_del   s'    	=yyQ		599r   c                     t        |       }|| j                  z  }t        |      ||| | j                  | j                  |j                  z   | j                  |      S r   )r   r   r   r   )r   r   r   entries
insert_poss        r   _eval_row_insertzMatrixBase._eval_row_insert   sL    t*499_
)-e
:&yyUZZ/GDDr   c                       j                    fd}t               j                   j                   j                   j                   z   |      S )Nc                 0    |k  r| |f   S | |z
  f   S r   r   )r   r   r   r   r   s     r   r   z(MatrixBase._eval_row_join.<locals>.entry   s+    4xAqDz!AH%%r   )r   r   r   r   )r   r   r   r   s   `` @r   _eval_row_joinzMatrixBase._eval_row_join   sE    yy	&
 tU#((DII

4J).0 	0r   c           	      r    t        | j                        D cg c]  }t        | |d d f          c}S c c}w r   )ranger   r   r   r   s     r   _eval_tolistzMatrixBase._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   )r   r   zero)r   dokr   r   r   r   vals          r   _eval_todokzMatrixBase._eval_todok   sg    ZZ
dt 	$A4[ $1a4j$))# #C1I$	$
 
r   c                     | j                   g||z  z  }|j                         D ]  \  \  }}}||||z  |z   <    | j                  |||      S r   )r   itemsr   )r   r   r   r   out_flatr   r   r   s           r   _eval_from_dokzMatrixBase._eval_from_dok   sX    HH:-99; 	)KFQC%(HQX\"	)xxdH--r   c                 b      j                    fd} j                  t               d|      S )Nc                 ,    | z  }| |z  z
  }||f   S r   r   )n_r   r   r   r   s       r   r   z#MatrixBase._eval_vec.<locals>.entry  s'    T	AAHA1:r   r.   )r   r   r   )r   r   r   s   ` @r   	_eval_veczMatrixBase._eval_vec   s*    yy	 yyTAu--r   c                 >   | j                   }g }|r8t        |      D ])  }t        ||      D ]  }|j                  | ||f           + n:t        |      D ],  }t        |dz   |      D ]  }|j                  | ||f           . | j                  t	        |      d|      S r   )r   r   r   r   r   )r   diagonalcvr   r   s         r   
_eval_vechzMatrixBase._eval_vech
  s    II1X )q! )AHHT!Q$Z()) 1X )q1ua )AHHT!Q$Z()) yyQA&&r   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.)r   
IndexErrorformatr   )r   r   s     r   col_delzMatrixBase.col_del  sP    7499CC#$))#9@@EFF!!#&&r   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 {}))typer4   r   r   r>   r   r   r   r   r   s      r   
col_insertzMatrixBase.col_insert  s    , 4:e$$Sk7))c/C7C499_))C99

"K		5::.0 0 $$S%00r   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 {}))r   r   r   col_joinr>   r   r   r   s     r   r   zMatrixBase.col_joinH  s    . 99>dii5::599Q

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

"N		5::.0 0 ""5))r   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
        Nr   )r   r   s     r   r   zMatrixBase.colh  s    ( AqDzr   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   
isinstanceboolr   r   s     r   r   z%MatrixBase.extract.<locals>.<genexpr>       BAJq$/B   c              3   <   K   | ]  }t        |t                y wr   r  r  s     r   r   z%MatrixBase.extract.<locals>.<genexpr>  r  r  )r3   	TypeErrorall	enumeratea2idxr   r   r   )r   r   r   indexitemks         r   extractzMatrixBase.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   r   s    r   get_diag_blockszMatrixBase.get_diag_blocks  s    0 ))++r   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r   r   klss      r   hstackzMatrixBase.hstack  s9     t9>88:47mcllD))r   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   r   )r   r   r   r   s     r   <lambda>z$MatrixBase.reshape.<locals>.<lambda>  s    $q4x!|2D r   )r   r   
ValueErrorr   )r   r   r   s   ` `r   r*   zMatrixBase.reshape  sG    * 99tyy D4K/?4,NOOyyt%DEEr   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.)r   r   r   r   )r   r   s     r   row_delzMatrixBase.row_del  sP    7499CC#$))#6==cBCC!!#&&r   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   r4   r   r   r>   r   r   r   s      r   
row_insertzMatrixBase.row_insert  s    . 99U##Sk7))c/C7C499_))C99

"N		5::.0 0 $$S%00r   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   )r   r   r   r  r>   r   r   r   s     r   r  zMatrixBase.row_join6  s    , 99>dii5::599UZZB/88??99

"K		5::.0 0 ""5))r   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 [, ])r4   r   r   r   r  r5   r   r   )r   r  rvrr   s        r   r   zMatrixBase.diagonalU  s    D 1IQAQBADII~diiIId1a4j!FAFA  Zq499}dii!m)- . / / yyCGR((r   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
        Nr   r   s     r   r   zMatrixBase.row  s    $ AqDzr   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   r   s    r   todokzMatrixBase.todok  s     !!r   c                     |j                         D ci c]  \  }}|| j                  |       }}}| j                  |||      S c c}}w )a  Create a matrix from a dictionary of keys.

        Examples
        ========

        >>> from sympy import Matrix
        >>> d = {(0, 0): 1, (1, 2): 3, (2, 1): 4}
        >>> Matrix.from_dok(3, 3, d)
        Matrix([
        [1, 0, 0],
        [0, 0, 3],
        [0, 4, 0]])
        )r   r   r   )r   r   r   r   ijr   s         r   from_dokzMatrixBase.from_dok  sJ     58IIK@Sr3<<$$@@!!$c22 As   A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()
        []

        )r   r   r   r   r   s     r   tolistzMatrixBase.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Mlolr   Mir   Mijr   s           r   tododzMatrixBase.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   r   s    r   veczMatrixBase.vec  s    0 ~~r   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   )r   r   check_symmetrys      r   vechzMatrixBase.vech  s;    T ~~&&$"3"3"5;<<x((r   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      r   vstackzMatrixBase.vstack>  s9      t9>88:47mcllD))r   c                 4    fd}| j                  |||      S )zUdiag_dict is a defaultdict containing
        all the entries of the diagonal matrix.c                     | |f   S r   r   )r   r   	diag_dicts     r   r   z$MatrixBase._eval_diag.<locals>.entryX  s    aV$$r   r   )r   r   r   r@  r   s      ` r   
_eval_diagzMatrixBase._eval_diagT  s    	%xxdE**r   c                     | j                   g||z  z  }| j                  gt        ||      z  |d d |dz   <   | j                  |||d      S )Nr.   Fcopy)r   oneminr   )r   r   r   valss       r   	_eval_eyezMatrixBase._eval_eye\  sO    z49%''3tT?2XtAvXxxdDux55r   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 r   rF  r   r   r   r   
eigenvalues     r   r   z,MatrixBase._eval_jordan_block.<locals>.entrye  -    6%%UaZ77Nxxr   c                 R    | |k(  rS | dz   |k(  rj                   S j                  S r   rO  rP  s     r   r   z,MatrixBase._eval_jordan_block.<locals>.entryl  rR  r   rA  )r   rK  rQ  bandr   s   ` `  r   _eval_jordan_blockzMatrixBase._eval_jordan_blockb  s)    7?   xxdE**r   c                 4      fd} j                  |||      S )Nc                     j                   S r   rF  r   r   r   s     r   r   z$MatrixBase._eval_ones.<locals>.entryv  s    77Nr   rA  )r   r   r   r   s   `   r   
_eval_oneszMatrixBase._eval_onest  s    	xxdE**r   c                 N    | j                  ||| j                  g||z  z  d      S )NFrD  )r   r   )r   r   r   s      r   _eval_zeroszMatrixBase._eval_zerosz  s(    xxdSXXJT	$:xGGr   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 r   rO  rY  s     r   r   z)MatrixBase._eval_wilkinson.<locals>.entry  s     !eqj3776chh6r      r.   T)unpack)r   diagr   r   Tabs)r   r   r   Dwminuswpluss   `     r   _eval_wilkinsonzMatrixBase._eval_wilkinson~  s    	7 HHQqS1WacAgu-$uaRQ/0>BQSSHCHHT%AE"23DHABQFLu}r   F)strictr`  r   r   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SparseMatrixr   r.   r   zg
                The constructed matrix is {} x {} but a size of {} x {}
                was specified.)sympy.matrices.matrixbaser   sympy.matrices.denserl  sympy.matricesrn  getr   r3   r  r   intr   r   r.  _handle_creation_inputsr   hasattrr  r  r5   r   rB  )r  rh  r`  r   r   r   r   r   rl  rn  klassdiag_entriesrmaxcmaxmr   r&  r   smatr   r   mis                         r   ra  zMatrixBase.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9r   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 positiver   )r  r   rr  r4   rI  r  r   r   r   rv  s        r   eyezMatrixBase.eye  sn     <D!8tax @@FtT@RT T

5#&D\6$<dtT**r   )rT  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
        r   eigenvalNzMust supply an eigenvaluez=Inconsistent values are given: 'eigenval'={}, 'eigenvalue'={}zMust supply a matrix size)poprr  r  r   r4   rU  )r  rK  rQ  rT  r   rv  r  s          r   jordan_blockzMatrixBase.jordan_block0  s    ^ 

5#&::j$/("28998#Xz4J(J""(&:">@ @ #%
<899d|''j$??r   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
        r   )rr  r4   rZ  r  s        r   oneszMatrixBase.ones  sB     <D

5#&D\6$<dd++r   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   r~  r   )r  r   rr  r4   r\  r  s        r   zeroszMatrixBase.zeros  sp     <D!8tax @@FtT@RT T

5#&D\6$<d  t,,r   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.   rO  )r   r   coeffsr  rK  s     r   r   z#MatrixBase.companion.<locals>.entry  s;    D1H}rAv&a!eww88Or   )
r   r  r1   r  r   is_monicis_univariatedegree
all_coeffsr   )r  polyr   r  rK  s   `  @@r   	companionzMatrixBase.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**r   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.

        r   )rr  r4   rg  )r  r   r   rv  s       r   	wilkinsonzMatrixBase.wilkinson  s/    H 

5#&1I$$Q''r   c                     d | D        S )Nc              3   F   K   | ]  }|t         j                  us|  y wr   )r"   Zeror  s     r   r   z/MatrixBase._eval_iter_values.<locals>.<genexpr>  s     3a1AFF?3s   !!r   r   s    r   _eval_iter_valueszMatrixBase._eval_iter_values  s    3433r   c                 4    t        | j                               S r   )r   iter_valuesr   s    r   _eval_valueszMatrixBase._eval_values  s    D$$&''r   c              #      K   t        | j                        D ]1  }t        | j                        D ]  }| ||f   s||f| ||f   f  3 y wr   r   r   r   r   r   r   s      r   _eval_iter_itemszMatrixBase._eval_iter_items  sX     tyy! 	-A499% -1:a&$q!t*,,-	-s
   8AAc                 6   | j                         }t        |      | j                  | j                  z  k  r,t	        t
        j                  |      rt
        j                  h}n
t               } |j                  |D cg c]  } |j                  |  c} S c c}w r   )
valuesr   r   r   r  r"   r  setunionatoms)r   typesr  sr   s        r   _eval_atomszMatrixBase._eval_atoms!  sn    v;TYY..:affe3LAAqww&9Q%9::9s   <Bc                 l     t               j                  d t        | j                               D         S )Nc              3   4   K   | ]  }|j                     y wr   )free_symbolsr  s     r   r   z0MatrixBase._eval_free_symbols.<locals>.<genexpr>*  s     HQ^^H   )r  r  r  r   s    r   _eval_free_symbolszMatrixBase._eval_free_symbols)  s&    su{{HS5GHIIr   c                 H    t        fd| j                         D              S )Nc              3   <   K   | ]  } |j                      y wr   )has)r   apatternss     r   r   z'MatrixBase._eval_has.<locals>.<genexpr>-  s     @5155(#@r   )r   r  r   r  s    `r   	_eval_haszMatrixBase._eval_has,  s    @T-=-=-?@@@r   c                 ,    | j                  t              S r   )r  r   r   s    r   _eval_is_symboliczMatrixBase._eval_is_symbolic/  s    xxr   c                 X      fdt        fd j                         D              S )Nc                 ^     | |f   || f   j                         z
        j                  S r   )	conjugateis_zeror   r   r   simpfuncs     r   r  z6MatrixBase._eval_is_matrix_hermitian.<locals>.<lambda>6  s0    HT!Q$Z$q!t*2F2F2H%HIQQ r   c              3   <   K   | ]  \  \  }}} ||        y wr   r   )r   r   r   r   herms       r   r   z7MatrixBase._eval_is_matrix_hermitian.<locals>.<genexpr>7       G	AaGr   r7   
iter_items)r   r  r  s   ``@r   _eval_is_matrix_hermitianz$MatrixBase._eval_is_matrix_hermitian5  s     QGT__5FGGGr   c                 B    t        d | j                         D              S )Nc              3   4   K   | ]  }|j                     y wr   r  )r   r   s     r   r   z2MatrixBase._eval_is_zero_matrix.<locals>.<genexpr>:  s     ?q?r  )r7   r  r   s    r   _eval_is_zero_matrixzMatrixBase._eval_is_zero_matrix9  s    ?D,<,<,>???r   returnc                     | j                   | j                  fdt        fd| j                         D              S )Nc                     | |k(  r|u S |u S r   r   )r   r   r   rF  r   s      r   r  z.MatrixBase._eval_is_Identity.<locals>.<lambda>?  s    AFS T	 r   c              3   >   K   | ]  \  \  }}} |||        y wr   r   )r   r   r   r   idents       r   r   z/MatrixBase._eval_is_Identity.<locals>.<genexpr>@  s!     Eifq!a5Aq>E   )rF  r   r  r  )r   r  rF  r   s    @@@r   _eval_is_IdentityzMatrixBase._eval_is_Identity<  s2    hhyyAE4??3DEEEr   c                 B    t        d | j                         D              S )Nc              3   L   K   | ]  \  \  }}}||k7  s|j                     y wr   r  r   r   r   r   s       r   r   z/MatrixBase._eval_is_diagonal.<locals>.<genexpr>C  s"     Pyv1qaP   $$r  r   s    r   _eval_is_diagonalzMatrixBase._eval_is_diagonalB  s    PDOO4EPPPr   c                 B    t        d | j                         D              S )Nc              3   L   K   | ]  \  \  }}}||k  s|j                     y wr   r  r  s       r   r   z,MatrixBase._eval_is_lower.<locals>.<genexpr>F  "     I!Q1q5199Ir  r  r  r   s    r   _eval_is_lowerzMatrixBase._eval_is_lowerE      Idoo.?IIIr   c                 B    t        d | j                         D              S )Nc              3   L   K   | ]  \  \  }}}||kD  s|j                     y wr   r  r  s       r   r   z,MatrixBase._eval_is_upper.<locals>.<genexpr>I  r  r  r  r   s    r   _eval_is_upperzMatrixBase._eval_is_upperH  r  r   c                 B    t        d | j                         D              S )Nc              3   R   K   | ]  \  \  }}}|d z   |k  s|j                    ! ywr.   Nr  r  s       r   r   z7MatrixBase._eval_is_lower_hessenberg.<locals>.<genexpr>L  s&     M!Q1q519199M   ''r  r   s    r   _eval_is_lower_hessenbergz$MatrixBase._eval_is_lower_hessenbergK      Mdoo.?MMMr   c                 B    t        d | j                         D              S )Nc              3   R   K   | ]  \  \  }}}||d z   kD  s|j                    ! ywr  r  r  s       r   r   z7MatrixBase._eval_is_upper_hessenberg.<locals>.<genexpr>O  s&     M!Q1q1u9199Mr  r  r   s    r   _eval_is_upper_hessenbergz$MatrixBase._eval_is_upper_hessenbergN  r  r   c                 X      fdt        fd j                         D              S )Nc                 B     | |f   || f   z
        j                   S r   r  r  s     r   r  z/MatrixBase._eval_is_symmetric.<locals>.<lambda>R  s'    8DAJad$;<DD r   c              3   <   K   | ]  \  \  }}} ||        y wr   r   )r   r   r   r   syms       r   r   z0MatrixBase._eval_is_symmetric.<locals>.<genexpr>S  s     Fyv1qQFr   r  )r   r  r  s   ``@r   _eval_is_symmetriczMatrixBase._eval_is_symmetricQ  s     DFDOO4EFFFr   c                 X      fdt        fd j                         D              S )Nc                 B     | |f   || f   z         j                   S r   r  r  s     r   r  z4MatrixBase._eval_is_anti_symmetric.<locals>.<lambda>V  s'    HT!Q$Z$q!t*%<=EE r   c              3   <   K   | ]  \  \  }}} ||        y wr   r   )r   r   r   r   antis       r   r   z5MatrixBase._eval_is_anti_symmetric.<locals>.<genexpr>W  r  r   r  )r   r  r  s   ``@r   _eval_is_anti_symmetricz"MatrixBase._eval_is_anti_symmetricU  s     EGT__5FGGGr   c                 d      fdt         j                        D        }t        d |D              S )Nc              3   ,   K   | ]  }||f     y wr   r   r   r   r   s     r   r   z5MatrixBase._has_positive_diagonals.<locals>.<genexpr>Z       A1DAJA   c              3   4   K   | ]  }|j                     y wr   )is_positiver   xs     r   r   z5MatrixBase._has_positive_diagonals.<locals>.<genexpr>[  s     A1Ar  r   r   r7   r   diagonal_entriess   ` r   _has_positive_diagonalsz"MatrixBase._has_positive_diagonalsY  s)    Adii0@AA0@AAAr   c                 d      fdt         j                        D        }t        d |D              S )Nc              3   ,   K   | ]  }||f     y wr   r   r  s     r   r   z8MatrixBase._has_nonnegative_diagonals.<locals>.<genexpr>^  r  r  c              3   4   K   | ]  }|j                     y wr   )is_nonnegativer  s     r   r   z8MatrixBase._has_nonnegative_diagonals.<locals>.<genexpr>_  s     Da))Dr  r  r  s   ` r   _has_nonnegative_diagonalsz%MatrixBase._has_nonnegative_diagonals]  s)    Adii0@AD3CDDDr   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   )r  r   )r   ts     r   r   z#MatrixBase.atoms.<locals>.<genexpr>u  s"     K:a.aDG;Ks   '))tupler   r  )r   r  s     r   r  zMatrixBase.atomsa  s1    ( KUKKGEt''r   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}
        )r  r   s    r   r  zMatrixBase.free_symbolsz  s     &&((r   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
        )r  r  s     r   r  zMatrixBase.has  s    . t~~x((r   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   r   r  s    r   r  z.MatrixBase.is_anti_symmetric.<locals>.<lambda>      a r   F)r   _utilities_simplifyr8  r  r   simplifyr  s      r   is_anti_symmetriczMatrixBase.is_anti_symmetric  s7    ~ (#.6*KH~~++H55r   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.MatrixBase.is_diagonalizable
        diagonalize
        )r  r   s    r   is_diagonalzMatrixBase.is_diagonal  s    R %%''r   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  r   	summationr   r   r   s      r   test_rowz:MatrixBase.is_weakly_diagonally_dominant.<locals>.test_row<  s[    		I4[ 16T!Q$Z0I1 QT
Oi/???r   c              3   .   K   | ]  } |        y wr   r   r   r   r  s     r   r   z;MatrixBase.is_weakly_diagonally_dominant.<locals>.<genexpr>C       :!:   r8  r   r7   r   r   r   r   r  s   ` @@r   is_weakly_diagonally_dominantz(MatrixBase.is_weakly_diagonally_dominant  s:    H ~~ZZ
d	@ :eDk:::r   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      r   r  z<MatrixBase.is_strongly_diagonally_dominant.<locals>.test_rown  s[    		I4[ 16T!Q$Z0I1 QT
Oi/<<<r   c              3   .   K   | ]  } |        y wr   r   r  s     r   r   z=MatrixBase.is_strongly_diagonally_dominant.<locals>.<genexpr>u  r  r  r  r  s   ` @@r   is_strongly_diagonally_dominantz*MatrixBase.is_strongly_diagonally_dominantE  s9    H ~~ZZ
d	= :eDk:::r   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)r8  r  r
  r   s    r   is_hermitianzMatrixBase.is_hermitianw  s     : ~~--.ABBr   c                 <    | j                   sy| j                         S )NF)r8  r  r   s    r   is_IdentityzMatrixBase.is_Identity  s    ~~%%''r   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  r   s    r   is_lower_hessenbergzMatrixBase.is_lower_hessenberg      6 --//r   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  r   s    r   is_lowerzMatrixBase.is_lower  s    V ""$$r   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   r   s    r   r8  zMatrixBase.is_square  s    , yyDII%%r   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  r   s    r   is_symboliczMatrixBase.is_symbolic  s     %%''r   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   r   r  s    r   r  z)MatrixBase.is_symmetric.<locals>.<lambda>I  r	  r   F)r   r
  r8  r  r  s      r   r9  zMatrixBase.is_symmetric  s7    n (#.6*KH~~&&x00r   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  r   s    r   is_upper_hessenbergzMatrixBase.is_upper_hessenbergP  r&  r   c                 "    | j                         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
        )r  r   s    r   is_upperzMatrixBase.is_upperm  s    T ""$$r   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  r   s    r   is_zero_matrixzMatrixBase.is_zero_matrix  s    : ((**r   c                 "    | j                         S )a  Return non-zero values of self.

        Examples
        ========

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

        See Also
        ========

        iter_values
        tolist
        flat
        )r  r   s    r   r  zMatrixBase.values  s    $   ""r   c                 "    | j                         S )a  
        Iterate over non-zero values of self.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix([[0, 1], [2, 3]])
        >>> list(m.iter_values())
        [1, 2, 3]

        See Also
        ========

        values
        )r  r   s    r   r  zMatrixBase.iter_values  s    " %%''r   c                 "    | j                         S )aC  Iterate over indices and values of nonzero items.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix([[0, 1], [2, 3]])
        >>> list(m.iter_items())
        [((0, 1), 1), ((1, 0), 2), ((1, 1), 3)]

        See Also
        ========

        iter_values
        todok
        )r  r   s    r   r  zMatrixBase.iter_items  s    " $$&&r   c                 >    | j                         j                         S r   )	transposer  r   s    r   _eval_adjointzMatrixBase._eval_adjoint  s    ~~))++r   c                    | j                   }| j                  | j                   z  }| j                         }|j                         D ci c]  }| ||       }}t	        |      |k  r |t
        j                        x}t
        j                  urX|g|z  }|j                         D ]  \  \  }	}
}||   ||	|z  |
z   <    | j                  | j                  | j                   |      }|S |j                         D ci c]  \  }}|||    }}}| j                  | j                  | j                   |      }|S c c}w c c}}w r   )
r   r   r)  r  r   r"   r  r   r   r,  )r   fr   rK  r   r   valmapfzeror   r   r   outr+  fdoks                 r   _eval_applyfunczMatrixBase._eval_applyfunc  s   yyyy"jjl#&::<0a!QqT'00s8d?!AFF)!3AFF Bwt|H YY[ 1	A'-ay4!$1))DIItyy(;C
 
 03yy{;eb!Bq	M;D;--		499d;C
 1 <s   D7;D<c                 V    | j                  t              | j                  t              fS r   )	applyfuncr   r   r   s    r   _eval_as_real_imagzMatrixBase._eval_as_real_imag  s    r"DNN2$677r   c                 &    | j                  d       S )Nc                 "    | j                         S r   r  r  s    r   r  z,MatrixBase._eval_conjugate.<locals>.<lambda>  s     r   rB  r   s    r   _eval_conjugatezMatrixBase._eval_conjugate
  s    ~~566r   c                 v     t        |       fd} j                   j                   j                  |      S )Nc                     | |   f   S r   r   r   r   mappingr   s     r   r   z,MatrixBase._eval_permute_cols.<locals>.entry  s    71:&&r   r   r   r   r   r   permr   rL  s   `  @r   _eval_permute_colszMatrixBase._eval_permute_cols  .    t*	' yyDIIu55r   c                 v     t        |       fd} j                   j                   j                  |      S )Nc                     |    |f   S r   r   rK  s     r   r   z,MatrixBase._eval_permute_rows.<locals>.entry  s    
A&&r   rM  rN  s   `  @r   _eval_permute_rowszMatrixBase._eval_permute_rows  rQ  r   c                 R     t         fdt         j                        D              S )Nc              3   ,   K   | ]  }||f     y wr   r   r  s     r   r   z)MatrixBase._eval_trace.<locals>.<genexpr>   s     8!41:8r  )sumr   r   r   s   `r   _eval_tracezMatrixBase._eval_trace  s    8uTYY'7888r   c                 X      j                   j                   j                   fd      S )Nc                     || f   S r   r   r   r   r   s     r   r  z,MatrixBase._eval_transpose.<locals>.<lambda>#  s    DAJ r   )r   r   r   r   s   `r   _eval_transposezMatrixBase._eval_transpose"  s    yyDII/FGGr   c                 "    | j                         S )z-Conjugate transpose or Hermitian conjugation.)r9  r   s    r   adjointzMatrixBase.adjoint%  s    !!##r   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@  )r   r;  s     r   rB  zMatrixBase.applyfunc)  s(    $ {344##A&&r   c                 "    | j                         S )z@Returns a tuple containing the (real, imaginary) part of matrix.)rC  )r   deephintss      r   as_real_imagzMatrixBase.as_real_imag@  s     &&((r   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
        )rH  r   s    r   r  zMatrixBase.conjugateE  s    4 ##%%r   c                 ,    | j                  fd      S )Nc                 (     | j                   di S Nr   )doit)r  rc  s    r   r  z!MatrixBase.doit.<locals>.<lambda>b  s     r   rG  )r   rc  s    `r   ri  zMatrixBase.doita  s    ~~788r   c                 B    ||||||d| j                  fd      S )&Apply evalf() to each element of self.)subsmaxnchoprh  quadverbosec                 *     | j                   fi S r   evalf)r   r   optionss    r   r  z"MatrixBase.evalf.<locals>.<lambda>h  s    (=W(= r   rG  )	r   r   rl  rm  rn  rh  ro  rp  rt  s	    `      @r   rs  zMatrixBase.evalfd  s(    tD6w0~~=>>r   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  basicrb  rc  r&   modulusmulmultinomial
power_base	power_exps
    r   r  z#MatrixBase.expand.<locals>.<lambda>y  s+    ':y#sK)) r   rG  )
r   rb  ry  r|  r}  rz  r&   r{  rx  rc  s
    `````````r   rw  zMatrixBase.expandj  s!     ~~    	r   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
        )rb  Cr   s    r   HzMatrixBase.H}  s    0 vvxxr   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columnsr   )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.r   c              3   >   K   | ]  }d |cxk  xr k  nc   yw)r   Nr   )r   r  	max_indexs     r   r   z%MatrixBase.permute.<locals>.<genexpr>	  s     D11&Y&&Dr  z`swap` indices out of range.r.   )rK  N)sympy.combinatoricsr  r
  r   r  r   r  r   r   r  r2   r   r   reversedrT  rP  )r   rO  orientation	directionr  r  s        @r   permutezMatrixBase.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 !r   c                 *    | j                  |d|      S )zAlias for
        ``self.permute(swaps, orientation='cols', direction=direction)``

        See Also
        ========

        permute
        r   r  r  r  r   swapsr  s      r   permute_colszMatrixBase.permute_cols 	       ||Ev|KKr   c                 *    | j                  |d|      S )zAlias for
        ``self.permute(swaps, orientation='rows', direction=direction)``

        See Also
        ========

        permute
        r   r  r  r  s      r   permute_rowszMatrixBase.permute_rows+	  r  r   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    r   r  z#MatrixBase.refine.<locals>.<lambda>H	  s    q+(> r   rG  )r   r  s    `r   r   zMatrixBase.refine6	  s    $ ~~>??r   c                    	 |||d	|ri 	fd}| j                  |      }|fS | 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)]])
        )mapsimultaneousexactc                 X     | j                   fi \  } }j                  |       | S r   )replaceupdate)eijdijFGdr   s     r   funcz MatrixBase.replace.<locals>.funca	  s.    &3;;q!6v6S
r   c                 ,     | j                   fi S r   )r  )r   r  r  r   s    r   r  z$MatrixBase.replace.<locals>.<lambda>j	  s    IAIIa,Ef,E r   rG  )
r   r  r  r  r  r  r  r   r  r   s
    ``     @@r   r  zMatrixBase.replaceJ	  sI    $ lUKA
 t$Aa4K >>"EFFr   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.   Nr  r_  r   )rb  )r   r  mods      r   rot90zMatrixBase.rot90l	  s{    F c!8K!8"b>###!8"dd
##!8DbD>### r   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 rh  r  r  r   s    r   r  z%MatrixBase.simplify.<locals>.<lambda>	      


(<V(< r   rG  r   r   s    `r   r  zMatrixBase.simplify	  s     ~~<==r   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   )rl  r  r   r   s    r   r  z!MatrixBase.subs.<locals>.<lambda>	  s    (?(? r   )r   r  dictr  iterr3   r   rB  r   r   r   s    ``r   rl  zMatrixBase.subs	  s[      t9>:d1gc{#CTRSW^ijnopjq^raM#D~~?@@r   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

        )r   r   r?   rX  r   s    r   tracezMatrixBase.trace	  s,     99		!&((!!r   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\  r   s    r   r8  zMatrixBase.transpose	  s    B ##%%r   c                 "    | j                         S )zMatrix transposition)r8  r   s    r   rb  zMatrixBase.T	       ~~r   c                 "    | j                         S )zBy-element conjugationrF  r   s    r   r  zMatrixBase.C	  r  r   c                 &     | j                   |i |S )rk  rr  r  s      r   r   zMatrixBase.n	  s    tzz4*6**r   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    r   r  z%MatrixBase.xreplace.<locals>.<lambda>
  s    

4(8 r   rG  )r   r  s    `r   r  zMatrixBase.xreplace 
  s     ~~899r   c                 ,    | j                  fd      S )Nc                 (     | j                   di S rh  r  r  s    r   r  z+MatrixBase._eval_simplify.<locals>.<lambda>
  r  r   rG  r  s    `r   _eval_simplifyzMatrixBase._eval_simplify
  s     ~~<==r   c                 <    ddl m | j                  fd      S )Nr   )trigsimpc                      | fi S r   r   )r  optsr  s    r   r  z+MatrixBase._eval_trigsimp.<locals>.<lambda>
  s    (;d(; r   )sympy.simplify.trigsimpr  rB  )r   r  r  s    `@r   _eval_trigsimpzMatrixBase._eval_trigsimp
  s    4~~;<<r   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   r   r   r  r   s     r   r   z*MatrixBase.upper_triangular.<locals>.entry;
  $    !"Q!41:::r   r   r   r  r   s   `` r   upper_triangularzMatrixBase.upper_triangular
  &    B	; yyDIIu55r   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     r   r   z*MatrixBase.lower_triangular.<locals>.entrya
  r  r   r   r  s   `` r   lower_triangularzMatrixBase.lower_triangular@
  r  r   c                 X      j                   j                   j                   fd      S )Nc                 $    t        | |f         S r   )r   r[  s     r   r  z&MatrixBase._eval_Abs.<locals>.<lambda>g
  s    CQT
O r   r   r   s   `r   	_eval_AbszMatrixBase._eval_Absf
  s    yyDII/KLLr   c                 \      j                   j                   j                   fd      S )Nc                 "    | |f   | |f   z   S r   r   r   r   r   r   s     r   r  z&MatrixBase._eval_add.<locals>.<lambda>k
  s    d1a4j5A;&> r   r   r   s   ``r   	_eval_addzMatrixBase._eval_addi
  s%    yyDII>@ 	@r   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   r   )r  bs     r   r  z<MatrixBase._eval_matrix_mul.<locals>.entry.<locals>.<lambda>v
  s
    1q5 r   )r   r   r
   r
  r	   r   )r   r   r  r6  r   r   s       r   r   z*MatrixBase._eval_matrix_mul.<locals>.entryn
  so    16tyy1ABA4!9U1Q3Z'BCB7Cy  C |, 7 0#66	7s   :? AAr   r   r   r   s   `` r   _eval_matrix_mulzMatrixBase._eval_matrix_mulm
  s%    	7 yyEJJ66r   c                 \      j                   j                   j                   fd      S )Nc                 "    | |f   | |f   z  S r   r   r  s     r   r  z9MatrixBase._eval_matrix_mul_elementwise.<locals>.<lambda>{
  s    D1IeAaCj<P r   r   r   s   ``r   _eval_matrix_mul_elementwisez'MatrixBase._eval_matrix_mul_elementwisez
  s    yyDII/PQQr   c                 `      fd} j                  j                   j                  |      S )Nc                 \     t         fdt        j                        D              S )Nc              3   <   K   | ]  }|f   |f   z    y wr   r   )r   r  r   r   r   r   s     r   r   z>MatrixBase._eval_matrix_rmul.<locals>.entry.<locals>.<genexpr>
  s&     GuQqSz$qs)+Gr   )rW  r   r   r  s   ``r   r   z+MatrixBase._eval_matrix_rmul.<locals>.entry~
  s    GU5::5FGGGr   r   r  s   `` r   _eval_matrix_rmulzMatrixBase._eval_matrix_rmul}
  s$    	HyyTYY66r   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)r   numr  r  s       r   r  z!MatrixBase._eval_pow_by_recursion
  sX    !8K7a<44S1W=qA//q99Azz!}r   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  r   charpolyr  r  r  r   )	r   r%   r  r   pr  new_matansr   s	            r   _eval_pow_by_cayleyzMatrixBase._eval_pow_by_cayley
  s    <jjmMMO""12&vs+((3-jjos 	A6!9W$$CtOG	 
r   c                    |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   r   r   )	r   r  r  r  r  rz  lenmelemsr   s	            r   r  z-MatrixBase._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,,r   c                 \      j                   j                   j                   fd      S )Nc                     | |f   z  S r   r   r  s     r   r  z-MatrixBase._eval_scalar_mul.<locals>.<lambda>
  s    D1IeO r   r   r   s   ``r   _eval_scalar_mulzMatrixBase._eval_scalar_mul
      yyDII/KLLr   c                 \      j                   j                   j                   fd      S )Nc                     | |f   z  S r   r   r  s     r   r  z.MatrixBase._eval_scalar_rmul.<locals>.<lambda>
  s    E$qs)O r   r   r   s   ``r   _eval_scalar_rmulzMatrixBase._eval_scalar_rmul
  r  r   c                 \      j                   j                   j                   fd      S )Nc                 &    t        | |f         S r   r   r  s     r   r  z&MatrixBase._eval_Mod.<locals>.<lambda>
  s    CQT
E<R r   r   r   s   ``r   	_eval_ModzMatrixBase._eval_Mod
  s    yyDII/RSSr   c                 "    | j                         S )z5Returns a new matrix with entry-wise absolute values.)r  r   s    r   __abs__zMatrixBase.__abs__
  s    ~~r   __radd__c                    t        | |      \  }}|dk7  rt        S | j                  |j                  k7  r&t        d| j                   d|j                   d      | |}}|j                  t        ||      k7  r||}}|j                  |      S )z?Return self + other, raising ShapeError if shapes do not match.	is_matrixMatrix size mismatch: z + .)_coerce_operandNotImplementedr   r>   	__class__r   r  )r   r   rb  r  r  s        r   __add__zMatrixBase.__add__
  s     #4/q!!::$5djj\U[[MQRSTT U1;;'!Q-'aqA{{1~r   __rtruediv__c                 &    | | j                   |z  z  S r   rX  r   s     r   __truediv__zMatrixBase.__truediv__
  s    txx%'((r   __rmatmul__c                 Z    t        | |      \  } }}|dk7  rt        S | j                  |      S Nr  )_unify_with_otherr  __mul__r   r   rb  s      r   
__matmul__zMatrixBase.__matmul__
  s1    *47eQ!!||E""r   c                 ,    | j                  fd      S )Nc                     | z  S r   r   )r  r   s    r   r  z$MatrixBase.__mod__.<locals>.<lambda>
  s    E	 r   rG  r   s    `r   __mod__zMatrixBase.__mod__
  s    ~~122r   __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  r   s     r   r  zMatrixBase.__mul__
  s    : }}U##r   c           
         t        d|      }t        | |      \  } }}|dk(  r	 | j                  |      S |dk(  r| j
                  d   |j
                  d   k7  r&t        d| j
                   d|j
                   d      | j                  |      }|r>|j                  |j                  |j                  |D cg c]  }t        |       c}      }|S t        S # t        $ r	 t        cY S w xY wc c}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.
        Fpossible_scalarr  r.   r   r  z * r  )r;   r  r  r
  r  r   r>   r  r   r   r   r/   r   r   r  	isimpboolrb  rz  es          r   r  zMatrixBase.multiply  s     0{C	*47eQ!!&,,U33 +zz!}A. #9$**SUV!WXX%%e,AFF166166Q+GLO+GHH "!!  &%%& ,Hs   C 6C,C)(C)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 {} != {})r   r>   r   r  r   s     r   multiply_elementwisezMatrixBase.multiply_elementwise,  sI    * ::$@GG

TYT_T_`aa0077r   c                 $    | j                  d      S )Nr  )r  r   s    r   __neg__zMatrixBase.__neg__F  s    $$R((r   __rpow__c                 $    | j                  |      S )z$Return self**exp a scalar or symbol.)pow)r   r%   s     r   __pow__zMatrixBase.__pow__I  s     xx}r   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   )rs  )r   r   s     r   r  z MatrixBase.pow.<locals>.<lambda>l  s    s16{ r   r.   r  c                 &    | |k(  r
| |f   z  S dS )Nr   r   )r   r   r  r%   s     r   r  z MatrixBase.pow.<locals>.<lambda>r  s    a1fq1vs{ RS r   r   r3  r4  z.cayley method is only valid for integer powersr2  z/mulsimp method is only valid for integer powersr  z0multiply method is only valid for integer powersr_  i Ti'  F)MatPow)r
  r   r   r?   getattrr   r  r   	is_Numberinvr=   r  r  r  r  is_Floatr   r;   r@   
is_integerr  sympy.matrices.expressionsr8  )r   r%   method
jordan_powr   r8  r  s    `    @r   r/  zMatrixBase.powP  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   r   r   s     r   r  zMatrixBase.__radd__  s    e|r   r  c                 Z    t        | |      \  } }}|dk7  rt        S | j                  |      S r  )r  r  r"  r  s      r   r  zMatrixBase.__rmatmul__  s1    *47eQ!!}}U##r   r  c                 $    | j                  |      S r   )	rmultiplyr   s     r   r"  zMatrixBase.__rmul__  s    ~~e$$r   c           
         t        d|      }t        | |      \  } }}|dk(  r	 | j                  |      S |dk(  r}| j
                  d   |j
                  d   k7  rt        d      | j                  |      }|r>|j                  |j                  |j                  |D cg c]  }t        |       c}      S |S t        S # t        $ r	 t        cY S w xY wc c}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.
        Fr%  r  r   r.   zMatrix size mismatch.)r;   r  r  r
  r  r   r>   r  r   r   r   r/   r&  s          r   rD  zMatrixBase.rmultiply  s     0{C	*47eQ!!&--e44 +zz!}A. !899&&u-Avvaffaff.J1|A.JKKH "!  &%%& /Ks   B< C<CC__sub__c                     |  |z   S r   r   r   r  s     r   __rsub__zMatrixBase.__rsub__  s    {r   rI  c                     | | z   S r   r   rH  s     r   rF  zMatrixBase.__sub__  s    r{r   c                     t        | |      S N)
iszerofuncrK   r   rM  s     r   _eval_det_bareisszMatrixBase._eval_det_bareiss  s    DZ88r   c                     t        |       S r   )rL   r   s    r   _eval_det_berkowitzzMatrixBase._eval_det_berkowitz  s    d##r   c                     t        | ||      S )N)rM  r  )rO   )r   rM  r  s      r   _eval_det_luzMatrixBase._eval_det_lu  s    t
XFFr   c                     t        |       S r   )rM   r   s    r   _eval_det_birdzMatrixBase._eval_det_bird  s    r   c                     t        |       S r   )rN   r   s    r   _eval_det_laplacezMatrixBase._eval_det_laplace      D!!r   c                     t        |       S r   rJ   r   s    r   _eval_determinantzMatrixBase._eval_determinant      Dzr   c                     t        | |      S Nr?  )rE   r   r?  s     r   adjugatezMatrixBase.adjugate  s    f--r   lambdac                     t        | ||      S )N)r  r  )rF   r   r  r  s      r   r  zMatrixBase.charpoly  s    X66r   c                      t        | |||      S r_  )rG   r   r   r   r?  s       r   cofactorzMatrixBase.cofactor  s    q!F33r   c                     t        | |      S r_  )rH   ra  s     r   cofactor_matrixzMatrixBase.cofactor_matrix  s    V44r   c                     t        | ||      S )N)r?  rM  r[  )r   r?  rM  s      r   detzMatrixBase.det  s    DJ??r   c                     t        |       S r   )rI   r   s    r   perzMatrixBase.per
  r]  r   c                      t        | |||      S r_  )rP   rg  s       r   minorzMatrixBase.minor  s    dAq00r   c                     t        | ||      S r   )rQ   r  s      r   minor_submatrixzMatrixBase.minor_submatrix  s    a++r   c                      t        | |||      S )N)rM  r  with_pivots)rS   )r   rM  r  rt  s       r   echelon_formzMatrixBase.echelon_form$  s    Tj8') 	)r   c                     t        |       S r   )rR   r   s    r   
is_echelonzMatrixBase.is_echelon(  s    4  r   c                     t        | ||      S N)rM  r  )rT   r   rM  r  s      r   rankzMatrixBase.rank,  s    Tj8DDr   c                     t        | j                  | | j                  | j                        |            \  }}|ddd| j                  f   |dd|j                   df   fS )a  Return reduced row-echelon form of matrix, matrix showing
        rhs after reduction steps. ``rhs`` must have the same number
        of rows as ``self``.

        Examples
        ========

        >>> from sympy import Matrix, symbols
        >>> r1, r2 = symbols('r1 r2')
        >>> Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2]))
        (Matrix([
        [1, 0],
        [0, 1]]), Matrix([
        [ -r1 + r2],
        [2*r1 - r2]]))
        N)rU   r  r  r   r   )r   rhsr&  r   s       r   rref_rhszMatrixBase.rref_rhs/  sY    " T[[txx		':C@A1JTYYJ1sxxij=!111r   c                 "    t        | ||||      S )N)rM  r  pivotsnormalize_last)rU   )r   rM  r  r  r  s        r   rrefzMatrixBase.rrefC  s    Tj8.: 	:r   c                    |dvrt        dj                  ||            |dk(  r| j                  n| j                  }|dk(  rM||n|}||t        dj                  |            d|cxk  r|k  sn t        dj                  ||            |d	k(  r||||hj	                  dg      }t        |      d
kD  r|||hj	                  dg      }t        |      d
k7  rt        dj                  |            |\  }}d|cxk  r|k  sn t        dj                  ||            d|cxk  r|k  sn t        dj                  ||            |dk(  r||n|}||n|}|||t        dj                  |            ||k(  rt        dj                  |            d|cxk  r|k  sn t        dj                  ||            d|cxk  r|k  s4n t        dj                  ||            t        dt        |      z        |||||fS )zValidate the arguments for a row/column operation.  ``error_str``
        can be one of "row" or "col" depending on the arguments being parsed.)n->knn<->mn->n+kmzOUnknown {} operation '{}'. Valid col operations are 'n->kn', 'n<->m', 'n->n+km'r   r  NzEFor a {0} operation 'n->kn' you must provide the kwargs `{0}` and `k`r   z#This matrix does not have a {} '{}'r  r_  zIFor a {0} operation 'n<->m' you must provide the kwargs `{0}1` and `{0}2`r  zPFor a {0} operation 'n->n+km' you must provide the kwargs `{0}`, `k`, and `{0}2`zAFor a {0} operation 'n->n+km' `{0}` and `{0}2` must be different.zinvalid operation %s)r  r   r   r   
differencer   repr)	r   opr   r  col1col2	error_str	self_colsr   s	            r   _normalize_op_argszMatrixBase._normalize_op_argsM  sT    22 ??EviQS?TV V "+e!3DII	 =#dC{ai  "88>y8IK K'i' !F!M!MiY\!]^^7] D$'22D6:D4y1}T4(33TF;4yA~  "<<BF9<MO OJD$(y( !F!M!MiY]!^__(y( !F!M!MiY]!^__9_+$3C<4TD{dlai  "AAG	ART Td{  "117	1BD D'i' !F!M!MiY\!]^^(y( !F!M!MiY]!^__ 3d2h>??34%%r   c                 d      fd} j                   j                   j                  |      S )Nc                 0    |k(  r
| |f   z  S | |f   S r   r   )r   r   r   r  r   s     r   r   z<MatrixBase._eval_col_op_multiply_col_by_const.<locals>.entry  *    Cx41:~%1:r   r   )r   r   r  r   s   ``` r   "_eval_col_op_multiply_col_by_constz-MatrixBase._eval_col_op_multiply_col_by_const  %    	 yyDIIu55r   c                 d      fd} j                   j                   j                  |      S )Nc                 B    |k(  r| f   S |k(  r| f   S | |f   S r   r   )r   r   r  r  r   s     r   r   z+MatrixBase._eval_col_op_swap.<locals>.entry  s;    DyAtG}$dAtG}$1:r   r   )r   r  r  r   s   ``` r   _eval_col_op_swapzMatrixBase._eval_col_op_swap  %    	 yyDIIu55r   c                 h      fd} j                   j                   j                  |      S )Nc                 @    |k(  r| |f   | f   z  z   S | |f   S r   r   )r   r   r   r  r  r   s     r   r   z@MatrixBase._eval_col_op_add_multiple_to_other_col.<locals>.entry  s8    CxAqDzAQW$5551:r   r   )r   r   r  r  r   s   ```` r   &_eval_col_op_add_multiple_to_other_colz1MatrixBase._eval_col_op_add_multiple_to_other_col  %    	 yyDIIu55r   c                 d      fd} j                   j                   j                  |      S )Nc                 B    | k(  r|f   S | k(  r|f   S | |f   S r   r   )r   r   row1row2r   s     r   r   z+MatrixBase._eval_row_op_swap.<locals>.entry  s;    DyD!G}$dD!G}$1:r   r   )r   r  r  r   s   ``` r   _eval_row_op_swapzMatrixBase._eval_row_op_swap  r  r   c                 d      fd} j                   j                   j                  |      S )Nc                 0    | k(  r
| |f   z  S | |f   S r   r   )r   r   r  r   r   s     r   r   z<MatrixBase._eval_row_op_multiply_row_by_const.<locals>.entry  r  r   r   )r   r   r  r   s   ``` r   "_eval_row_op_multiply_row_by_constz-MatrixBase._eval_row_op_multiply_row_by_const  r  r   c                 h      fd} j                   j                   j                  |      S )Nc                 @    | k(  r| |f   |f   z  z   S | |f   S r   r   )r   r   r  r   r  r   s     r   r   z@MatrixBase._eval_row_op_add_multiple_to_other_row.<locals>.entry  s8    CxAqDzAT1W$5551:r   r   )r   r   r  r  r   s   ```` r   &_eval_row_op_add_multiple_to_other_rowz1MatrixBase._eval_row_op_add_multiple_to_other_row  r  r   c                     | j                  |||||d      \  }}}}}|dk(  r| j                  ||      S |dk(  r| j                  ||      S |dk(  r| j                  |||      S y)ad  Performs the elementary column operation `op`.

        `op` may be one of

            * ``"n->kn"`` (column n goes to k*n)
            * ``"n<->m"`` (swap column n and column m)
            * ``"n->n+km"`` (column n goes to column n + k*column m)

        Parameters
        ==========

        op : string; the elementary row operation
        col : the column to apply the column operation
        k : the multiple to apply in the column operation
        col1 : one column of a column swap
        col2 : second column of a column swap or column "m" in the column operation
               "n->n+km"
        r   r  r  r  N)r  r  r  r  )r   r  r   r  r  r  s         r   elementary_col_opzMatrixBase.elementary_col_op      ( "&!8!8S!T4QV!WCD$ =::3BB=))$55?>>sAtLL r   c                     | j                  |||||d      \  }}}}}|dk(  r| j                  ||      S |dk(  r| j                  ||      S |dk(  r| j                  |||      S y)a4  Performs the elementary row operation `op`.

        `op` may be one of

            * ``"n->kn"`` (row n goes to k*n)
            * ``"n<->m"`` (swap row n and row m)
            * ``"n->n+km"`` (row n goes to row n + k*row m)

        Parameters
        ==========

        op : string; the elementary row operation
        row : the row to apply the row operation
        k : the multiple to apply in the row operation
        row1 : one row of a row swap
        row2 : second row of a row swap or row "m" in the row operation
               "n->n+km"
        r   r  r  r  N)r  r  r  r  )r   r  r   r  r  r  s         r   elementary_row_opzMatrixBase.elementary_row_op  r  r   c                     t        | |      S Nr  )rk   r   r  s     r   columnspacezMatrixBase.columnspace  s    D844r   c                     t        | ||      S )N)r  rM  )rl   )r   r  rM  s      r   	nullspacezMatrixBase.nullspace  s    $jIIr   c                     t        | |      S r  )rm   r  s     r   rowspacezMatrixBase.rowspace  s    11r   c                      t        | g|i |S r   )rn   )r   vecsr   s      r   orthogonalizezMatrixBase.orthogonalize  s    c3D3F33r   c                     t        | fd|i|S )Nerror_when_incomplete)ro   )r   r  flagss      r   	eigenvalszMatrixBase.eigenvals  s    $U6KUuUUr   c                      t        | f||d|S )N)r  rM  )rp   )r   r  rM  r  s       r   
eigenvectszMatrixBase.eigenvects  s$    4 07L%0).0 	0r   c                     t        | fd|i|S )N
reals_only)rs   )r   r  r   s      r   is_diagonalizablezMatrixBase.is_diagonalizable  s    !$H:HHHr   c                      t        | |||      S )N)r  sort	normalize)rt   )r   r  r  r  s       r   diagonalizezMatrixBase.diagonalize  s    DZd#% 	%r   c                     t        | |      S NrJ  )rq   r   rJ  s     r   bidiagonalizezMatrixBase.bidiagonalize  s    d%00r   c                     t        | |      S r  )rr   r  s     r   bidiagonal_decompositionz#MatrixBase.bidiagonal_decomposition  s    (U;;r   c                     t        |       S r   )ru   r   s    r   is_positive_definitezMatrixBase.is_positive_definite      $T**r   c                     t        |       S r   )rv   r   s    r   is_positive_semidefinitez#MatrixBase.is_positive_semidefinite      (..r   c                     t        |       S r   )rw   r   s    r   is_negative_definitezMatrixBase.is_negative_definite   r  r   c                     t        |       S r   )rx   r   s    r   is_negative_semidefinitez#MatrixBase.is_negative_semidefinite$  r  r   c                     t        |       S r   )ry   r   s    r   is_indefinitezMatrixBase.is_indefinite(  s    d##r   c                     t        | fd|i|S )Ncalc_transform)rz   )r   r  r   s      r   jordan_formzMatrixBase.jordan_form,  s    DJJ6JJr   c                     t        | fi |S r   )r{   r   r  s     r   left_eigenvectszMatrixBase.left_eigenvects/  s    ...r   c                     t        |       S r   )r|   r   s    r   singular_valueszMatrixBase.singular_values2      %%r   )evaluatec                n    ddl m}  || g|d|i}t        | t              s|r|j	                         S |S )ae  Calculate the derivative of each element in the matrix.

        Examples
        ========

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

        See Also
        ========

        integrate
        limit
        r   )ArrayDerivativer  )$sympy.tensor.array.array_derivativesr  r  r   
as_mutable)r   r  r   r   r  derivs         r   r   zMatrixBase.diffD  s<    * 	I?t?h?$&8##%%r   c                 ,    | j                  fd      S )Nc                 &    | j                        S r   r   )r  args    r   r  z-MatrixBase._eval_derivative.<locals>.<lambda>a  s    s r   rG  )r   r  s    `r   _eval_derivativezMatrixBase._eval_derivative`  s    ~~344r   c                 0    | j                  fd      S )a  Integrate each element of the matrix.  ``args`` will
        be passed to the ``integrate`` function.

        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy.abc import x, y
        >>> M = Matrix([[x, y], [1, 0]])
        >>> M.integrate((x, ))
        Matrix([
        [x**2/2, x*y],
        [     x,   0]])
        >>> M.integrate((x, 0, 2))
        Matrix([
        [2, 2*y],
        [2,   0]])

        See Also
        ========

        limit
        diff
        c                 (     | j                   i S r   )	integrater  s    r   r  z&MatrixBase.integrate.<locals>.<lambda>|  s    T(DV(D r   rG  r  s    ``r   r  zMatrixBase.integratec  s    2 ~~DEEr   c                     ddl m} t        |      s j                         j                  d   dk(  r j                  d   }n- j                  d   dk(  r j                  d   }nt        d      j                  d   dk(  rj                  d   }n-j                  d   dk(  rj                  d   }nt        d       j                  || fd      S )a  Calculates the Jacobian matrix (derivative of a vector-valued function).

        Parameters
        ==========

        ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n).
        X : set of x_i's in order, it can be a list or a Matrix

        Both ``self`` and X can be a row or a column matrix in any order
        (i.e., jacobian() should always work).

        Examples
        ========

        >>> from sympy import sin, cos, Matrix
        >>> from sympy.abc import rho, phi
        >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
        >>> Y = Matrix([rho, phi])
        >>> X.jacobian(Y)
        Matrix([
        [cos(phi), -rho*sin(phi)],
        [sin(phi),  rho*cos(phi)],
        [   2*rho,             0]])
        >>> X = Matrix([rho*cos(phi), rho*sin(phi)])
        >>> X.jacobian(Y)
        Matrix([
        [cos(phi), -rho*sin(phi)],
        [sin(phi),  rho*cos(phi)]])

        See Also
        ========

        hessian
        wronskian
        r   rj  r.   z)``self`` must be a row or a column matrixz"X must be a row or a column matrixc                 2    |    j                  |         S r   r   )r   r   Xr   s     r   r  z%MatrixBase.jacobian.<locals>.<lambda>  s    DGLL1,> r   )ro  r   r  r   r   r
  )r   r  r   rz  r   s   ``   r   jacobianzMatrixBase.jacobian~  s    H 	9!Z(		!A ::a=A

1AZZ]a

1AGHH771:?
AWWQZ1_
A@AA yyA>??r   c                 ,    | j                  fd      S )a  Calculate the limit of each element in the matrix.
        ``args`` will be passed to the ``limit`` function.

        Examples
        ========

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

        See Also
        ========

        integrate
        diff
        c                 "     | j                    S r   )limit)r  r   s    r   r  z"MatrixBase.limit.<locals>.<lambda>  s     r   rG  )r   r   s    `r   r  zMatrixBase.limit  s    * ~~677r   c                 &    | j                  |      S )Nr  )r  re  s      r   berkowitz_charpolyzMatrixBase.berkowitz_charpoly  s    }}q}!!r   c                 &    | j                  d      S )zeComputes determinant using Berkowitz method.

        See Also
        ========

        det
        	berkowitzr`  rl  r   s    r   berkowitz_detzMatrixBase.berkowitz_det  s     xx{x++r   c                 &     | j                   di |S )z8Computes eigenvalues of a Matrix using Berkowitz method.r   )r  r  s     r   berkowitz_eigenvalszMatrixBase.berkowitz_eigenvals  s    t~~&&&r   c                     | j                   g }}| j                         D ]  }|j                  ||d   z         | } t        |      S )z1Computes principal minors using Berkowitz method.r  )rF  r  r   r  )r   signminorsr  s       r   berkowitz_minorszMatrixBase.berkowitz_minors  sL    xxfNN$ 	DMM$b/*5D	 V}r   c                    ddl m} d}| s|S | j                  s
t               | | j                  }}dg|dz
  z  }t        |dd      D ]  } ||dz   |      |dz
  }}||d |f    |d ||f   }
}	|d |d |f   |||f    }}|
g}t        d|dz
        D ]  }|j                  |||   z          t        |      D ]  \  }}|	|z  d   ||<    | j                  |g|z   }t        |      D ]  }|d ||z
  dz    ||d |f<    |||dz
  <    | j                  | j                  |d    g      g}t        |      D ]  \  }}|j                  |||   z          |t        t        t        |            z   S )Nr   r  )r.   r.   r  r_  r   r   )rq  r  r8  r?   r   r   r   r  rF  r   r  r  )r   r  berkAN
transformsr   rb  r  Rr  r  r   r   Bpolyss                   r   r  zMatrixBase.berkowitz  s   (K~~&((TYY1SAE]
q!R 	"AQ?AEqAa!eH9aAhqARaR!V9qAwhqACE1a!e_ +Qq\*+ "%( )1E4=a) XXqME)E1X - !a%!),!"a%- !"Jq1u'	"* DHHqwh/01j) 	'DAqLLU1X&	' eCu-...r   c                 &    | j                  |      S r_  )rj  ra  s     r   cofactorMatrixzMatrixBase.cofactorMatrix  s    ##6#22r   c                     t        |       S r   rN  r   s    r   
det_bareiszMatrixBase.det_bareis  rY  r   c                 &    | j                  d      S )a  Compute matrix determinant using LU decomposition.


        Note that this method fails if the LU decomposition itself
        fails. In particular, if the matrix has no inverse this method
        will fail.

        TODO: Implement algorithm for sparse matrices (SFF),
        http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.

        See Also
        ========


        det
        berkowitz_det
        lur`  r  r   s    r   det_LU_decompositionzMatrixBase.det_LU_decomposition  s    $ xxtx$$r   c                 (    | j                  ||      S )N)rK  rQ  )r  )r   r  r   s      r   jordan_cellzMatrixBase.jordan_cell,  s      aH ==r   c                 L    | j                         \  }}||j                         fS r   )r  r  )r   calc_transformationPJs       r   jordan_cellszMatrixBase.jordan_cells/  s(    !1!##%%%r   c                 *    | j                  |||      S r_  )rp  rg  s       r   
minorEntryzMatrixBase.minorEntry3  s    zz!Qvz..r   c                 &    | j                  ||      S r   )rr  r  s      r   minorMatrixzMatrixBase.minorMatrix6  s    ##Aq))r   c                 (    | j                  |d      S )zEPermute the rows of the matrix with the given permutation in reverse.r  r  r  r   rO  s     r   permuteBkwdzMatrixBase.permuteBkwd9  s       <<r   c                 (    | j                  |d      S )z:Permute the rows of the matrix with the given permutation.r  r  r  r   s     r   
permuteFwdzMatrixBase.permuteFwd=  s       ;;r   c                     | j                         D ch c]  }|j                   }}t        |      dk(  r|\  }t	        |      S t        }t	        |      S c c}w r   )flatkindr   r   r<   )r   r(  
elem_kindselemkinds       r   r&  zMatrixBase.kindA  sV    &*iik2aff2
2z?a"IH (## %H(## 3s   Ac                     t        | j                        D cg c]#  }t        | j                        D ]	  }| ||f    % c}}S c c}}w )a"  
        Returns a flat list of all elements in the matrix.

        Examples
        ========

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

        See Also
        ========

        tolist
        values
        r  r  s      r   r%  zMatrixBase.flatJ  s>    $ %*$))$4OqeDII>NOQT
O
OOOs   (Ac                 @    ||st        d      ddlm}  || |      S )Nz=Cannot implement copy=False when converting Matrix to ndarrayr.   )matrix2numpy)dtype)r
  denser+  )r   r,  rE  r+  s       r   	__array__zMatrixBase.__array__^  s&    D[\\'D..r   c                 4    | j                   | j                  z  S )zkReturn the number of elements of ``self``.

        Implemented mainly so bool(Matrix()) == False.
        r   r   s    r   __len__zMatrixBase.__len__d  s    
 yy499$$r   c                 2   ddl m}m} d }| j                         \  }}|j	                         }|D cg c]
  } ||       }}|D ]  } |||        | j                  |j                   ||       j                  |j                                     S c c}w )Nr   )ra  MutableMatrixc                    | j                   d   }| d   }|j                  r_|dk(  r|j                  r	||z  | d<   n|j                  r|j                  st	        d      t        |      D ]  }t        ||      | d|f<    nLt        |      D ]>  }t        ||      }t        |t              r|j                         }|||z
  z  |z  | d|f<   @ t        |      D ].  }t        d||z
        D ]  }| |dz
  ||z   dz
  f   | |||z   f<    0 y )Nr   r  r.   zANon-invertible matrix can only be raised to a nonnegative integer)
r   r  r  r=  r@   r   r    r'   r  _eval_expand_func)jcr   r  lr   bnr   s          r   jordan_cell_powerzBMatrixBase._matrix_pow_by_jordan_blocks.<locals>.jordan_cell_powern  s!   A3Ayy6a..dBsG,,1+;+;23vww"1X 7"0A"61Q37 q *A!!QB!"h/113!A#hrkBqsG	*
 1X /q!A# /A "AaC!AIBq1uI//r   )rq  ra  r2  r  r  r   r  r;  )	r   r  ra  r2  r8  r  r  r  r   s	            r   r5  z'MatrixBase._matrix_pow_by_jordan_blocksk  s    6	/* !1((*2>?Qa(?? 	&Aa%	&yyD,$78!%%'"$ 	$ @s   Bc                     t         j                  | j                  v rd| j                  d| j                  dS dt        | j                               z  S )NMatrix(r#  , [])z
Matrix(%s))r"   r  r   r   r   strr.  r   s    r   __str__zMatrixBase.__str__  s;    66TZZ+/99dii@@c$++-000r   c                    |s
t               }t        j                  | j                  v rd| j                  d| j
                  dS | j                  dk(  rd| j                  |d      z  S d| j                  |d      z  S )	Nr:  r#  r;  r.   zMatrix([%s])z,
)rowsepzMatrix([
%s]))r$   r"   r  r   r   r   table)r   printers     r   _format_strzMatrixBase._format_str  sj     lG66TZZ+/99dii@@99>!DJJwuJ$EEE$**WU*"CCCr   c                    t        |      }|D cg c]   }t        |d      r|j                         n|" c}t        t	        t                          }D cg c]  }|j                   }}t	        |      D cg c]  }|j                  d       }}t        fd|D              }	g }
t        |      rg }t        |      D ]Q  \  }}|j                  |   ||    ddf          ||xx   dz  cc<   ||   dk(  s;|s>|j                  d      ||<   S t        |      |	k7  rt        t        d            |
j                  |       t        |      r| j                  |
      S c c}w c c}w c c}w )a%  Return a matrix filled by the given matrices which
      are listed in order of appearance from left to right, top to
      bottom as they first appear in the matrix. They must fill the
      matrix completely.

      Examples
      ========

      >>> from sympy import ones, Matrix
      >>> Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
      ...   ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7)
      Matrix([
        [1, 2, 2, 2, 3, 3],
        [1, 2, 2, 2, 3, 3],
        [4, 2, 2, 2, 5, 5],
        [6, 6, 7, 7, 5, 5]])
      as_explicitr   c              3   <   K   | ]  }|   j                     y wr   r   )r   r   r  s     r   r   z'MatrixBase.irregular.<locals>.<genexpr>  s     +q1+r   Nr.   z^
                Matrices provided do not appear to fill
                the space completely.)r4   ru  rD  r   r   r   r   r  rW  r   r  extendr  r5   r   r   )r   ntopmatricesr   r   qdatr   activer   r   r&  r  r   r  s                 @r   	irregularzMatrixBase.irregular  s`   & D\d  &a71==?Q> a
uSV}
aQVVc"'+.Qa.f.+F++ddH!' 'dahhqtSVGQJ'(!fkfQ1eeAh&)	'
 Vt^Z )) * + + ++a. H XXd^'  .s   %E(E-<E2c                    |j                         }t        |j                        dk(  rO|j                  d   |j                  d   }}|j                         D cg c]  }| j	                  |       }}|||fS t        |j                        dk(  r0|D cg c]  }| j	                  |       }}|j                  d   d|fS t        d      c c}w c c}w )Nr_  r   r.   z&SymPy supports just 1D and 2D matrices)r.  r   r   ravelr   r   )r   r  arrr   r   r   	flat_lists          r   _handle_ndarrayzMatrixBase._handle_ndarray  s    
 mmosyy>Q1syy|$D25))+>Qa>I>y((^q 256Qa6I699Q<I--%8: : ? 7s   CCc                    ddl m} ddlm ddlm d}t        |      dk(  rt        |d   |      r9|d   j                  |d   j                  t        |d   j                               fS t        |d   t              r0|d   j                  |d   j                  |d   j                         fS t        |d   t              rM|d   j                  r>|d   j                  |d   j                  |d   j!                         j                         fS t        |d   t"        j$                        r<|d   }|D cg c]  }| j'                  |       }}|j                  |j                  |fS t)        |d   d      r| j+                  |d         S t-        |d         rt        |d   t.              s~t1        |d         }fdfd	|j3                  d
d      r6fdfd}t        |t0        t4        f      r|D 	cg c]
  }	 ||	       }}	|g g gfv rdx}
}g }nt7        fd|D              s1|D cg c]  }| j'                  |       }}t        |      }
|
rdnd}nŉrt9        fd|D              r|D ch c]$  }t7        |j:                        s|j                  & }}|rht        |      dk7  rt=        d      |D cg c]   }|j                         D ]  }|D ]  }|  " }}}}|j?                         }t        |      |z  }
ndx}
}g }nrEt7        fd|D              r0tA               }g }|D ]  } |      rg|jC                  |j                         D cg c]  }|D ]  }|  c}}       t7        |j:                        r|jE                  |j                         nu |      rK|rk|jE                  t        |             |jC                  |D cg c]  }| j'                  |       c}       n"|jE                  d       |jG                  |       t        |      dkD  st=        d       |j?                         }t        |      |z  }
ng }tA               }dx}
}|D ]E  }	t-        |	      stI        |	dd      st=        d      t)        |	d      rd|	j:                  v rBrt9        fd|	D              rp| jK                  |	D cg c]  }|jL                   c}      \  }}}tO        ||g      }tQ        |      D cg c]  }tQ        |      D ]
  }||   |     c}}}||}}n>d}tI        |	dd      rd}|	g}n)t        |	      }|	D cg c]  }| j'                  |       }}|jE                  |       t        |      dkD  rt=        d      |jC                  |       |
|z  }
H |r|j?                         nd}nUt        |      dk(  r2tS        |d         }
tS        |d         }|
dk  s|dk  rt=        djU                  |
|            t        |      dk(  rt        |d   tV              rt|d   }g }tQ        |
      D ]^  }|jC                  tQ        |      D cg c]8  }| j'                   || j'                  |      | j'                  |                  : c}       ` npt        |      dk(  rbt-        |d         rT|d   }t        |      |
|z  k7  rt=        d      |D cg c]  }| j'                  |       }}nt        |      dk(  rdx}
}g }|tY        t[        d            
|fS c c}w c c}	w c c}w c c}w c c}}}w c c}}w c c}w c c}w c c}}w c c}w c c}w c c}w )a}  Return the number of rows, cols and flat matrix elements.

        Examples
        ========

        >>> from sympy import Matrix, I

        Matrix can be constructed as follows:

        * from a nested list of iterables

        >>> Matrix( ((1, 2+I), (3, 4)) )
        Matrix([
        [1, 2 + I],
        [3,     4]])

        * from un-nested iterable (interpreted as a column)

        >>> Matrix( [1, 2] )
        Matrix([
        [1],
        [2]])

        * from un-nested iterable with dimensions

        >>> Matrix(1, 2, [1, 2] )
        Matrix([[1, 2]])

        * from no arguments (a 0 x 0 matrix)

        >>> Matrix()
        Matrix(0, 0, [])

        * from a rule

        >>> Matrix(2, 2, lambda i, j: i/(j + 1) )
        Matrix([
        [0,   0],
        [1, 1/2]])

        See Also
        ========
        irregular - filling a matrix with irregular blocks
        r   rm  )MatrixSymbol)BlockMatrixNr.   r.  c                 L    t        | t              xr xs t        | f      S r   )r  r   )r   rT  rS  r  s    r   r  z4MatrixBase._handle_creation_inputs.<locals>.<lambda>$  s+    *Q
"; #LJ
1{L.I J r   c                 0    t        |       xr	  |        S r   )r3   )r   ismats    r   r  z4MatrixBase._handle_creation_inputs.<locals>.<lambda>&  s    A ?uQx< r   r  Tc                     t        |       r| j                         S t        |       r,t        d | j                  D              r| j                         S | S )zmake Block and Symbol explicitc              3   4   K   | ]  }|j                     y wr   )
is_Integer)r   r   s     r   r   zLMatrixBase._handle_creation_inputs.<locals>.make_explicit.<locals>.<genexpr>0  s     @_RS@_r  )r  rD  r  r   )r  rT  rS  s    r   make_explicitz9MatrixBase._handle_creation_inputs.<locals>.make_explicit,  sH    %a5#$==?2'<8S@_WXW^W^@_=_#$==?2#$Hr   c                 v    t        | t        t        f      r| D cg c]
  } |       c}S  |       S c c}w r   )r  r   r  )r   r  r[  s     r   make_explicit_rowz=MatrixBase._handle_creation_inputs.<locals>.make_explicit_row5  s8    %cD%=9>A#BM!$4#BB#0#55 $Cs   6c              3   B   K   | ]  } |      xs  |        y wr   r   )r   r   rW  raws     r   r   z5MatrixBase._handle_creation_inputs.<locals>.<genexpr>B  s!     =ASV/uQx/=s   c              3   .   K   | ]  } |        y wr   r   r   r   rW  s     r   r   z5MatrixBase._handle_creation_inputs.<locals>.<genexpr>G       %<1eAh%<r  zmismatched dimensionsc              3   .   K   | ]  } |        y wr   r   ra  s     r   r   z5MatrixBase._handle_creation_inputs.<locals>.<genexpr>S  rb  r  	is_MatrixFzexpecting list of listsc              3   .   K   | ]  } |        y wr   r   ra  s     r   r   z5MatrixBase._handle_creation_inputs.<locals>.<genexpr>w  s     +BE!H+Br  r   r~  r_  z+List length should be equal to rows*columnszf
                Data type not understood; expecting list of lists
                or lists of values.).rq  rn  "sympy.matrices.expressions.matexprrS  &sympy.matrices.expressions.blockmatrixrT  r   r  r   r   r2   r.  r   r%  r   rd  rD  mpmatrixr   ru  rQ  r3   DeferredVectorr   rr  r  r   r  r   r  r  r  rF  addr   r9  rt  rb  r*   r   r4   r   r)   r
  r5   )r   r   r   rn  rP  r   r  rJ  r]  r   r   r   r   ncolr&  r   r   r  r+  r   flatTrb  r%  r  rT  rS  r  rW  r[  r_  s                           @@@@@@r   rt  z"MatrixBase._handle_creation_inputs  s   \ 	0CF	t9>$q'<0Aw||T!W\\747>>;K3LLL DGZ0Aw||T!W\\47<<>AA DGU+Q0A0AAw||T!W\\473F3F3H3M3M3OOODGRYY/G678S\\!_8	8vvqvvy00 a+.**4733 T!W%&tAw?47mL?!::j$7 %6 "#e}5ADE#05EE2t*$"#OD4 "I===:= >Qa >I >y>D $1!D#%<%<"<,/@q3qww<AFF@D@t9>",-D"EE03$S$S1QXXZ$SQR$SAQ$SQ$SQ$S	$S#xxz"9~t3&'t$&	#%<%<"<5D "I  F 8%,,,-HHJ Bq B1 B BD"177| $ 0 V  $Q 0 ) 0 0Q1Or#,,r2B1O P HHQK%,,Q/t9q=",-D"EEF  88:Dy>4/D
 !#I5D"#OD4" "*3/$+Ce$D",-F"GG"34 CII~ (#+Bc+B(B*-*E*E.1 2 2+4KAq% 's 3A27( MQE!H Mq1a M M !#$aqA !A&sK?$%(+u$'HAD'EAQ'E'Et9q=",-D"EE!((.	9": *.488:1DY!^$q'?D$q'?Dax4!8  "DDJF4QUDVX X 4yA~*T!Wh"?!W	t 0A$$"'+/ ba#,,q/&JK /00 TaKQ$8 G	y>TD[0$EG G6?@S\\!_@	@ Y!^OD4IJ (' ( ) ) T9$$s 9H F !?
 A %T !C 2P4 !3 !N (F,/ AsN   ;]] ]]"]%]!3](/].
%]3
]8*]>;=^
^c                    ddl m} t        |t              }| j	                  |      x\  }}}t        |t
              }t        |t              st        |t              rQ|r| j                  ||       yt        |t              st        |      r| j                  ||       yt        d|z        |s%t        |t              st        |      r
 ||      }d}|r|r9t        t        || j                         t        t        || j                         f}n2t        |||j                  z         t        |||j                  z         f}| j                  ||       y||| j                  |      fS )am  Helper to set value at location given by key.

        Examples
        ========

        >>> from sympy import Matrix, I, zeros, ones
        >>> m = Matrix(((1, 2+I), (3, 4)))
        >>> m
        Matrix([
        [1, 2 + I],
        [3,     4]])
        >>> m[1, 0] = 9
        >>> m
        Matrix([
        [1, 2 + I],
        [9,     4]])
        >>> m[1, 0] = [[0, 1]]

        To replace row r you assign to position r*m where m
        is the number of columns:

        >>> M = zeros(4)
        >>> m = M.cols
        >>> M[3*m] = ones(1, m)*2; M
        Matrix([
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [2, 2, 2, 2]])

        And to replace column c you can assign to position c:

        >>> M[2] = ones(m, 1)*4; M
        Matrix([
        [0, 0, 4, 0],
        [0, 0, 4, 0],
        [0, 0, 4, 0],
        [2, 2, 4, 2]])
        r.   rk  Nzunexpected value: %sT)r-  rl  r  slicekey2ijr   copyin_matrixr+   r3   copyin_listr  r   divmodr   r   r   )r   r   valuerl  is_slicer   r   is_mats           r   _setitemzMatrixBase._setitem  sD   P 	"c5)[[%%1sE:.a:a#7""3.eT*{5/A  e,3e;<<"5%0[5Gu &DII"67 &DII"679C !A

N3 A

N35C""3.  !T]]5111r   c                     | |z   S )zReturn self + b.r   r   r  s     r   rk  zMatrixBase.add  s    axr   c                 `    | s| j                   S | j                         }t        | t        | z  S )a{  Returns the condition number of a matrix.

        This is the maximum singular value divided by the minimum singular value

        Examples
        ========

        >>> from sympy import Matrix, S
        >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])
        >>> A.condition_number()
        100

        See Also
        ========

        singular_values
        )r   r  r   r   )r   singularvaluess     r   condition_numberzMatrixBase.condition_number  s4    & 99--/N#c>&:::r   c                 l    | j                  | j                  | j                  | j                               S )z
        Returns the copy of a matrix.

        Examples
        ========

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

        )r   r   r   r%  r   s    r   rE  zMatrixBase.copy  s%     yyDIItyy{;;r   c           
      <   ddl m} t        |t        |f      s$t	        dj                  |t        |                  | j                  | j                  z  |j                  |j                  z  cxk(  rdk(  s?n t        d| j                  | j                  fd|j                  |j                  f      | j                  | j                  | j                  | d   |d   z  | d   |d   z  z
  | d   |d   z  | d   |d   z  z
  | d   |d   z  | d   |d   z  z
  f      S )	a-  
        Return the cross product of ``self`` and ``b`` relaxing the condition
        of compatible dimensions: if each has 3 elements, a matrix of the
        same type and shape as ``self`` will be returned. If ``b`` has the same
        shape as ``self`` then common identities for the cross product (like
        `a \times b = - b \times a`) will hold.

        Parameters
        ==========
            b : 3x1 or 1x3 Matrix

        See Also
        ========

        dot
        hat
        vee
        multiply
        multiply_elementwise
        r   )
MatrixExprz{} must be a Matrix, not {}.r   z(Dimensions incorrect for cross product: z x r.   r_  )rf  r  r  r   r
  r   r   r   r   r>   r   )r   r  r  s      r   crosszMatrixBase.cross'  s   * 	B!j*56.55aaAC C 		DII%!&&=A=#yy$))4qvvqvv6FH I I 99TYY		a1Q4$q'AaD.0a1Q4$q'AaD.0a1Q4$q'AaD.043 4 4r   c                     | j                   dk7  r!t        dt        | j                         z         | \  }}}| j                  ddd| ||d| | |df	      S )a  
        Return the skew-symmetric matrix representing the cross product,
        so that ``self.hat() * b`` is equivalent to  ``self.cross(b)``.

        Examples
        ========

        Calling ``hat`` creates a skew-symmetric 3x3 Matrix from a 3x1 Matrix:

        >>> from sympy import Matrix
        >>> a = Matrix([1, 2, 3])
        >>> a.hat()
        Matrix([
        [ 0, -3,  2],
        [ 3,  0, -1],
        [-2,  1,  0]])

        Multiplying it with another 3x1 Matrix calculates the cross product:

        >>> b = Matrix([3, 2, 1])
        >>> a.hat() * b
        Matrix([
        [-4],
        [ 8],
        [-4]])

        Which is equivalent to calling the ``cross`` method:

        >>> a.cross(b)
        Matrix([
        [-4],
        [ 8],
        [-4]])

        See Also
        ========

        dot
        cross
        vee
        multiply
        multiply_elementwise
        )r   r.   z+Dimensions incorrect, expected (3, 1), got r   r   )r   r>   r<  r   )r   r  yzs       r   hatzMatrixBase.hatK  ss    Z ::J _- . . GAq!99QQBQQ$  r   c                     | j                   dk7  r!t        dt        | j                         z         | j                         st	        d      | j                  dd| d   | d   | d   f      S )	ao  
        Return a 3x1 vector from a skew-symmetric matrix representing the cross product,
        so that ``self * b`` is equivalent to  ``self.vee().cross(b)``.

        Examples
        ========

        Calling ``vee`` creates a vector from a skew-symmetric Matrix:

        >>> from sympy import Matrix
        >>> A = Matrix([[0, -3, 2], [3, 0, -1], [-2, 1, 0]])
        >>> a = A.vee()
        >>> a
        Matrix([
        [1],
        [2],
        [3]])

        Calculating the matrix product of the original matrix with a vector
        is equivalent to a cross product:

        >>> b = Matrix([3, 2, 1])
        >>> A * b
        Matrix([
        [-4],
        [ 8],
        [-4]])

        >>> a.cross(b)
        Matrix([
        [-4],
        [ 8],
        [-4]])

        ``vee`` can also be used to retrieve angular velocity expressions.
        Defining a rotation matrix:

        >>> from sympy import rot_ccw_axis3, trigsimp
        >>> from sympy.physics.mechanics import dynamicsymbols
        >>> theta = dynamicsymbols('theta')
        >>> R = rot_ccw_axis3(theta)
        >>> R
        Matrix([
        [cos(theta(t)), -sin(theta(t)), 0],
        [sin(theta(t)),  cos(theta(t)), 0],
        [            0,              0, 1]])

        We can retrive the angular velocity:

        >>> Omega = R.T * R.diff()
        >>> Omega = trigsimp(Omega)
        >>> Omega.vee()
        Matrix([
        [                      0],
        [                      0],
        [Derivative(theta(t), t)]])

        See Also
        ========

        dot
        cross
        hat
        multiply
        multiply_elementwise
        )r   r   z+Dimensions incorrect, expected (3, 3), got zMatrix is not skew-symmetricr   r.   )r_  r.   )r   r_  )r.   r   )r   r>   r<  r  r  r   r   s    r   veezMatrixBase.vee  sx    H ::J _- . .'');<<99Qddd$  r   c                 b    ddl m} | j                  dk7  rt        | j                   |d      z  S )a  Return Dirac conjugate (if ``self.rows == 4``).

        Examples
        ========

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

        If the matrix does not have 4 rows an AttributeError will be raised
        because this property is only defined for matrices with 4 rows.

        >>> Matrix(eye(2)).D
        Traceback (most recent call last):
        ...
        AttributeError: Matrix has no attribute D.

        See Also
        ========

        sympy.matrices.matrixbase.MatrixBase.conjugate: By-element conjugation
        sympy.matrices.matrixbase.MatrixBase.H: Hermite conjugation
        r   )mgammar  )sympy.physics.matricesr  r   AttributeErrorr  )r   r  s     r   rd  zMatrixBase.D  s.    D 	299>
 ! vvq	!!r   c                 F   ddl m} t        |t              st	        |      rkt        |      | j                  k7  r<t        |      | j                  k7  r$t        d| j                  dt        |            | j                   ||            S t        dt        |      z        d| j                  vsd|j                  vrt        t        |       t        |      k7  r%t        d| j                  d|j                        | }t        |      }|j                  d|fk7  r|j                  d|      }|j                  |dfk7  r|j                  |d      }||d}|r|d}|dk(  r5|dv r|j                         }n |d	v r|j                         }nt        d
      ||z  d   S )a4  Return the dot or inner product of two vectors of equal length.
        Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b``
        must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n.
        A scalar is returned.

        By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are
        complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``)
        to compute the hermitian inner product.

        Possible kwargs are ``hermitian`` and ``conjugate_convention``.

        If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``,
        the conjugate of the first vector (``self``) is used.  If ``"right"``
        or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
        >>> v = Matrix([1, 1, 1])
        >>> M.row(0).dot(v)
        6
        >>> M.col(0).dot(v)
        12
        >>> v = [3, 2, 1]
        >>> M.row(0).dot(v)
        10

        >>> from sympy import I
        >>> q = Matrix([1*I, 1*I, 1*I])
        >>> q.dot(q, hermitian=False)
        -3

        >>> q.dot(q, hermitian=True)
        3

        >>> q1 = Matrix([1, 1, 1*I])
        >>> q.dot(q1, hermitian=True, conjugate_convention="maths")
        1 - 2*I
        >>> q.dot(q1, hermitian=True, conjugate_convention="physics")
        1 + 2*I


        See Also
        ========

        cross
        multiply
        multiply_elementwise
        r.   rk  z&Dimensions incorrect for dot product: r#  z2`b` must be an ordered iterable or Matrix, not %s.Tmaths)r  leftmath)physicsrightzUnknown conjugate_convention was entered. conjugate_convention must be one of the following: math, maths, left, physics or right.r   )r-  rl  r  r   r3   r   r   r   r>   r   dotr
  r   r*   r  r  )r   r  	hermitianconjugate_conventionrl  r   r   s          r   r  zMatrixBase.dot  s   h 	"!Z(1~q6TYY&3q6TYY+>$ JJA01 1 xxq	**HG  TZZQagg%5t9ABF**aggVX X H99A++a#C77q!f		!QA  +	0AI-5#* #'@@mmo%)==KKM  "T U U a|r   c           
         ddl m} | ddddf   | j                  }} ||      }| j                         r|S t	        d|      D ]N  }t	        d|      D ]=  }d}t	        d|      D ]  }|t        ||d|      |d|f   z  z  } ||||f<   | |||f<   ? P t	        d|      D ]S  }	d}t	        d|      D ],  }
t	        d|      D ]  }|t        d|	|
|      ||
|f   z  z  } . |dz  }| |d|	f<   |||	df<   U |S )a  Returns the dual of a matrix.

        A dual of a matrix is:

        ``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l`

        Since the levicivita method is anti_symmetric for any pairwise
        exchange of indices, the dual of a symmetric matrix is the zero
        matrix. Strictly speaking the dual defined here assumes that the
        'matrix' `M` is a contravariant anti_symmetric second rank tensor,
        so that the dual is a covariant second rank tensor.

        r   r  Nr.   r_  )rq  r  r   r9  r   r!   )r   r  r   r   workr   r   acumr  r6  r  r  s               r   dualzMatrixBase.dualb  sN    	)AqDz4991QxKq! 	#A1a[ #q! =AJq!Q2Qq!tW<<D=!QT
"UQT
#	# q! 	AD1a[ =q! =AJq!Q2Qq!tW<<D== AIDDAJDAJ	 r   c                     | j                   }| d   }t        |      }t        |      D ci c]  }||t        |      z   }}ddlm} | j                   |||            S c c}w )a   A helper function to compute an exponential of a Jordan block
        matrix

        Examples
        ========

        >>> from sympy import Symbol, Matrix
        >>> l = Symbol('lamda')

        A trivial example of 1*1 Jordan block:

        >>> m = Matrix.jordan_block(1, l)
        >>> m._eval_matrix_exp_jblock()
        Matrix([[exp(lamda)]])

        An example of 3*3 Jordan block:

        >>> m = Matrix.jordan_block(3, l)
        >>> m._eval_matrix_exp_jblock()
        Matrix([
        [exp(lamda), exp(lamda), exp(lamda)/2],
        [         0, exp(lamda),   exp(lamda)],
        [         0,          0,   exp(lamda)]])

        References
        ==========

        .. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition
        r  r.   banded)r   r%   r   r(   sparsetoolsr  r  )r   rK  r6  exp_lr   bandsr  s          r   _eval_matrix_exp_jblockz"MatrixBase._eval_matrix_exp_jblock  sb    < yyJA27+>QEIaL((>>'~~fT5122 ?s   A c                    t        |      t        |      }}| j                  st        |j                  st	        dj                  |            ||j                  vrt	        dj                  ||            || j                  v rt	        dj                  ||             | j                         }t        |j                               }i }|}t        |dz
        D ]  }t        ||      }|||dz   <    | j                  d   }| j                  |      }	| j                  |d      }
d}|D ]X  }||   }|j                  ||      |
|<   |
|   j                  r-|
|   j                   st	        dj                  ||
|               d}t        |      D ]  }||	||f<   ||z  } |dkD  rt        |      D cg c]  }d }}d}|dkD  r|dz   }|dz  }||   j                  ||      }|j                  r*|j                   st	        dj                  ||   |            ||
|<   t        |      D ]E  }||z
  dz   dk  rd|	||f<   d||<   ||   ||z
  dz   z  ||<   ||   t#        |||z
        z  |	||f<   G |dz  }|dkD  r|dz  }[ |	j%                  |
      }| j                  |      }| j'                  |      }t        |      D ]  }|||   |z  z   }|| z  } |S c c}w )a  
        Computes f(A) where A is a Square Matrix
        and f is an analytic function.

        Examples
        ========

        >>> from sympy import Symbol, Matrix, S, log

        >>> x = Symbol('x')
        >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
        >>> f = log(x)
        >>> m.analytic_func(f, x)
        Matrix([
        [     0, log(2)],
        [log(2),      0]])

        Parameters
        ==========

        f : Expr
            Analytic Function
        x : Symbol
            parameter of f

        z{} must be a symbol.z{} must be a parameter of {}.z!{} must not be a parameter of {}.r.   r   z_Cannot evaluate the function because the function {} is not analytic at the given eigenvalue {}zaCannot evaluate the function because the derivative {} is not analytic at the given eigenvalue {})r   r8  r?   	is_symbolr  r   r  r  maxr  r   r   r   r  rl  	is_number
is_complexr/  solver  )r   r;  r  eigenmax_mul
derivativeddr   r   r&  f_valr   rz  r   r  iicoederid_ir   r  pres                         r   analytic_funczMatrixBase.analytic_func  sB   8 {HQK1~~&&{{3::1=>>ANN"/66q!<> >!!!3::1dCE E  elln%
w{# 	#Ab!B "Jq1u	# JJqMJJqM

1a  !	A(C1E#JSz##E#J,A,A $$*F1eCj$9; ; C1X #q&	q Qw#(8,Rq,,Ag'C1HC$T*//15C}}S^^(,,2F:d3CS,IK K "%E#J"1X <t8a<1,()Ac1fI%&CF$!$QTA!6A$'F3q!d(+;$;#q&	< AID# Ag$ 1HCC!	D GGENjjmhhqkq 	A!S.C4KC	 
7 -s   5	Kc                    | j                   st        d      	 | j                         \  }}|j                         }|D cg c]  }|j                          }}ddlm}  || }|j                  |d      j                  |j                         d      }t        d | j                         D              r t        |       t        |            S  t        |       |      S # t        $ r t        d      w xY wc c}w )a  Return the exponential of a square matrix.

        Examples
        ========

        >>> from sympy import Symbol, Matrix

        >>> t = Symbol('t')
        >>> m = Matrix([[0, 1], [-1, 0]]) * t
        >>> m.exp()
        Matrix([
        [    exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2],
        [I*exp(I*t)/2 - I*exp(-I*t)/2,      exp(I*t)/2 + exp(-I*t)/2]])
        z0Exponentiation is valid only for square matricesz`Exponentiation is implemented only for matrices for which the Jordan normal form can be computedr   ra  Nr  c              3   4   K   | ]  }|j                     y wr   )is_real)r   rt  s     r   r   z!MatrixBase.exp.<locals>.<genexpr>/  s     8u}}8r  )r8  r?   r  r  r=   r   r  rq  ra  r  r;  r  r  r   r   )	r   r  r  cellscellblocksra  eJrets	            r   r%   zMatrixBase.exp  s     ~~&BD D	t##%DAq%%'E
 >CCT$..0CC'6]jjj.77T7R8$++-884:bg&&4:c?"  	t%rt t	t Ds   #C!  C9!C6c                    | j                   }| d   }|j                  rt        dj                  |            dt	        |      i}t        d|      D ]  }| | z   |z  ||<    ddlm} | j                   |||            S )az  Helper function to compute logarithm of a jordan block.

        Examples
        ========

        >>> from sympy import Symbol, Matrix
        >>> l = Symbol('lamda')

        A trivial example of 1*1 Jordan block:

        >>> m = Matrix.jordan_block(1, l)
        >>> m._eval_matrix_log_jblock()
        Matrix([[log(lamda)]])

        An example of 3*3 Jordan block:

        >>> m = Matrix.jordan_block(3, l)
        >>> m._eval_matrix_log_jblock()
        Matrix([
        [log(lamda),    1/lamda, -1/(2*lamda**2)],
        [         0, log(lamda),         1/lamda],
        [         0,          0,      log(lamda)]])
        r  zBCould not take logarithm or reciprocal for the given eigenvalue {}r   r.   r  )	r   r  r=   r   r&   r   r  r  r  )r   rK  r6  r  r   r  s         r   _eval_matrix_log_jblockz"MatrixBase._eval_matrix_log_jblock4  s    0 yyJ99  &q	+ + CFq$ 	)A"!}q(E!H	) 	(~~fT5122r   c                    | j                   st        d      	 |r ||       j                         \  }}n| j                         \  }}|j                         }|D cg c]  }|j                          }}ddlm}  || }|r5 |||z   ||j                               z        }	| j                  |	      }	|	S ||z  |j                         z  }	|	S # t        $ r t        d      w xY wc c}w )aH  Return the logarithm of a square matrix.

        Parameters
        ==========

        simplify : function, bool
            The function to simplify the result with.

            Default is ``cancel``, which is effective to reduce the
            expression growing for taking reciprocals and inverses for
            symbolic matrices.

        Examples
        ========

        >>> from sympy import S, Matrix

        Examples for positive-definite matrices:

        >>> m = Matrix([[1, 1], [0, 1]])
        >>> m.log()
        Matrix([
        [0, 1],
        [0, 0]])

        >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
        >>> m.log()
        Matrix([
        [     0, log(2)],
        [log(2),      0]])

        Examples for non positive-definite matrices:

        >>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]])
        >>> m.log()
        Matrix([
        [         I*pi/2, log(2) - I*pi/2],
        [log(2) - I*pi/2,          I*pi/2]])

        >>> m = Matrix(
        ...     [[0, 0, 0, 1],
        ...      [0, 0, 1, 0],
        ...      [0, 1, 0, 0],
        ...      [1, 0, 0, 0]])
        >>> m.log()
        Matrix([
        [ I*pi/2,       0,       0, -I*pi/2],
        [      0,  I*pi/2, -I*pi/2,       0],
        [      0, -I*pi/2,  I*pi/2,       0],
        [-I*pi/2,       0,       0,  I*pi/2]])
        z+Logarithm is valid only for square matricesz[Logarithm is implemented only for matrices for which the Jordan normal form can be computedr   r  )r8  r?   r  r  r=   r   r  rq  ra  r;  r  )
r   r  r  r  r  r  r  ra  r  r  s
             r   r&   zMatrixBase.log[  s   h ~~&=? ?
	:~1131'')1%%'E  ((*  	(6]1r6HQUUW$556C..%C 
 b&1557"C
#  	:%9: :	:
s   ?C C'C$c                     | sy| j                   st        d      t        d| d       }| j                  |      }|j                  d   || j
                  z  k(  ryy)a  Checks if a matrix is nilpotent.

        A matrix B is nilpotent if for some integer k, B**k is
        a zero matrix.

        Examples
        ========

        >>> from sympy import Matrix
        >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
        >>> a.is_nilpotent()
        True

        >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])
        >>> a.is_nilpotent()
        False
        Tz,Nilpotency is valid only for square matricesr  c                     d| z   S )Nr   r   )r  s    r   r  z)MatrixBase.is_nilpotent.<locals>.<lambda>  s
    cAg r   )modifyr   F)r8  r?   r-   r  r   r   )r   r  r  s      r   is_nilpotentzMatrixBase.is_nilpotent  s^    $ ~~&>@ @!#t4EFMM!66!9TYY&r   c                    |D cg c]  }t        |t               c}\  }}|r6| j                  sdx}}nC|d   j                  | j                        dd \  }}nt	        |d   | j                        }|dz   }|r6| j
                  sdx}}nC|d   j                  | j
                        dd \  }}nt	        |d   | j
                        }|dz   }||||fS c c}w )zConverts a key with potentially mixed types of keys (integer and slice)
        into a tuple of ranges and raises an error if any index is out of ``self``'s
        range.

        See Also
        ========

        key2ij
        r   Nr_  r.   )r  ro  r   r   r  r   )	r   keysr  islicejslicerlorhiclochis	            r   
key2boundszMatrixBase.key2bounds  s     9==1*Q.=99c7??4995bq9SQ+C'C99c7??4995bq9SQ+C'CCc!!# >s   Cc                    t        |      r^t        |      dk(  st        d      t        || j                        D cg c]#  \  }}t        |t              st        ||      n|% c}}S t        |t              r|j                  t        |             dd S t        t        |t        |             | j                        S c c}}w )zConverts key into canonical form, converting integers or indexable
        items into valid integers for ``self``'s range or returning slices
        unchanged.

        See Also
        ========

        key2bounds
        r_  z"key must be a sequence of length 2N)r3   r   r
  zipr   r  ro  r  r   rs  r   )r   r   r   r   s       r   rp  zMatrixBase.key2ij  s     ss8q= DEE #C 461 (2!U';E!QKB 6 6U#;;s4y)"1--%SY/;;6s   (C c                    | j                   dk7  r| j                  dk7  rt        d      | j                          |      r(| j	                  | j                   | j                        }|S | j                  fd      }|S )a  Return the normalized version of ``self``.

        Parameters
        ==========

        iszerofunc : Function, optional
            A function to determine whether ``self`` is a zero vector.
            The default ``_iszero`` tests to see if each element is
            exactly zero.

        Returns
        =======

        Matrix
            Normalized vector form of ``self``.
            It has the same length as a unit vector. However, a zero vector
            will be returned for a vector with norm 0.

        Raises
        ======

        ShapeError
            If the matrix is not in a vector form.

        See Also
        ========

        norm
        r.   z'A Matrix must be a vector to normalize.c                     | z  S r   r   )r   norms    r   r  z'MatrixBase.normalized.<locals>.<lambda>  s    1t8 r   )r   r   r>   r  r  rB  )r   rM  r>  r  s      @r   
normalizedzMatrixBase.normalized  sn    < 99>dii1nFGGyy{d**TYY		2C 
 ..!34C
r   c           
         t        | j                               xs dg}t        j                  | j                  v rdv rt        t        d |D               S dk(  rt        d |D         S t        j                  u rt        |D cg c]  }t        |       c} S t        j                  u rt        |D cg c]  }t        |       c} S 	 t        t        fd|D         t        j                  z        S dk(  rV| j!                  t              }t        t#        |j$                        D cg c]  }t'        |j)                  |             c} S dk(  rt        | j+                          S d	k(  rt        | j+                          S t        j                  u rV| j!                  t              }t        t#        |j,                        D cg c]  }t'        |j/                  |             c} S "t1        t2              r2j5                         d
v r | j7                         j9                  d      S t        d      c c}w c c}w # t        t        f$ r t        d      w xY wc c}w c c}w )a  Return the Norm of a Matrix or Vector.

        In the simplest case this is the geometric size of the vector
        Other norms can be specified by the ord parameter


        =====  ============================  ==========================
        ord    norm for matrices             norm for vectors
        =====  ============================  ==========================
        None   Frobenius norm                2-norm
        'fro'  Frobenius norm                - does not exist
        inf    maximum row sum               max(abs(x))
        -inf   --                            min(abs(x))
        1      maximum column sum            as below
        -1     --                            as below
        2      2-norm (largest sing. value)  as below
        -2     smallest singular value       as below
        other  - does not exist              sum(abs(x)**ord)**(1./ord)
        =====  ============================  ==========================

        Examples
        ========

        >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo
        >>> x = Symbol('x', real=True)
        >>> v = Matrix([cos(x), sin(x)])
        >>> trigsimp( v.norm() )
        1
        >>> v.norm(10)
        (sin(x)**10 + cos(x)**10)**(1/10)
        >>> A = Matrix([[1, 1], [1, 1]])
        >>> A.norm(1) # maximum sum of absolute values of A is 2
        2
        >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm)
        2
        >>> A.norm(-2) # Inverse spectral norm (smallest singular value)
        0
        >>> A.norm() # Frobenius Norm
        2
        >>> A.norm(oo) # Infinity Norm
        2
        >>> Matrix([1, -2]).norm(oo)
        2
        >>> Matrix([-1, 2]).norm(-oo)
        1

        See Also
        ========

        normalized
        r   r_  Nc              3   8   K   | ]  }t        |      d z    ywr  rc  r  s     r   r   z"MatrixBase.norm.<locals>.<genexpr>Z  s     !<!#a&A+!<s   r.   c              3   2   K   | ]  }t        |        y wr   r  r  s     r   r   z"MatrixBase.norm.<locals>.<genexpr>]  s     2SV2s   c              3   :   K   | ]  }t        |      z    y wr   r  )r   r   ords     r   r   z"MatrixBase.norm.<locals>.<genexpr>h  s      =1Q3 =s   z'Expected order to be Number, Symbol, oor_  )r;  fro	frobeniusvector)r  zMatrix Norms under development)r   r  r"   Oner   r   r
   Infinityr   rc  NegativeInfinityr   r,   r   r
  r  rB  r   r   rW  r   r  r   r   r  r<  rM  r6  r  )r   r  rH  r   rz  s    `   r   r  zMatrixBase.norm"  s   j DKKM")qc55DJJiC!<t!<=>>2T233

"T2SV233***T2SV233L3 = =>LL axNN3'E!&&MBqSq]BCCD00233D00233

"NN3'E!&&MBqSq]BCC+C,/"158YY[364 xxz1-- **JKKK 3 3 (3 L !JKKL C Cs$   I8I+I 1!I+!I0I(c                 Z   g }t        | j                        D ]w  }g }t        | j                        D ]8  }| ||f   dk(  r|j                  d       |j                  t	        |             : |j                  ddj                  |      z         y t        dj                  |             y)a  Shows location of non-zero entries for fast shape lookup.

        Examples
        ========

        >>> from sympy import Matrix, eye
        >>> m = Matrix(2, 3, lambda i, j: i*3+j)
        >>> m
        Matrix([
        [0, 1, 2],
        [3, 4, 5]])
        >>> m.print_nonzero()
        [ XX]
        [XXX]
        >>> m = eye(4)
        >>> m.print_nonzero("x")
        [x   ]
        [ x  ]
        [  x ]
        [   x]

        r    z[%s] 
N)r   r   r   r   r<  joinprint)r   symbr  r   liner   s         r   print_nonzerozMatrixBase.print_nonzero  s    . tyy! 	-AD499% +1:?KK$KKD	*	+
 HHVbggdm+,	- 	diilr   c                 N    || j                  |      |j                  |      z  z  S )a^  Return the projection of ``self`` onto the line containing ``v``.

        Examples
        ========

        >>> from sympy import Matrix, S, sqrt
        >>> V = Matrix([sqrt(3)/2, S.Half])
        >>> x = Matrix([[1, 0]])
        >>> V.project(x)
        Matrix([[sqrt(3)/2, 0]])
        >>> V.project(-x)
        Matrix([[sqrt(3)/2, 0]])
        )r  )r   r   s     r   projectzMatrixBase.project  s$     DHHQK!%%(*++r   c                 ^   t         j                  | j                  v ryg }dg| j                  z  }t	        | j
                        D ]r  }	|j                  g        t	        | j                        D ]G  }
|j                  | |	|
f         }|d   j                  |       t        t        |      ||
         ||
<   I t ddddddd|   }t        |      D ]J  \  }	}t        |      D ]  \  }
} t        ||      ||
         ||
<    ||j                  |      z   |z   ||	<   L |j                  |      S )a  
        String form of Matrix as a table.

        ``printer`` is the printer to use for on the elements (generally
        something like StrPrinter())

        ``rowstart`` is the string used to start each row (by default '[').

        ``rowend`` is the string used to end each row (by default ']').

        ``rowsep`` is the string used to separate rows (by default a newline).

        ``colsep`` is the string used to separate columns (by default ', ').

        ``align`` defines how the elements are aligned. Must be one of 'left',
        'right', or 'center'.  You can also use '<', '>', and '^' to mean the
        same thing, respectively.

        This is used by the string printer for Matrix.

        Examples
        ========

        >>> from sympy import Matrix, StrPrinter
        >>> M = Matrix([[1, 2], [-33, 4]])
        >>> printer = StrPrinter()
        >>> M.table(printer)
        '[  1, 2]\n[-33, 4]'
        >>> print(M.table(printer))
        [  1, 2]
        [-33, 4]
        >>> print(M.table(printer, rowsep=',\n'))
        [  1, 2],
        [-33, 4]
        >>> print('[%s]' % M.table(printer, rowsep=',\n'))
        [[  1, 2],
        [-33, 4]]
        >>> print(M.table(printer, colsep=' '))
        [  1 2]
        [-33 4]
        >>> print(M.table(printer, align='center'))
        [ 1 , 2]
        [-33, 4]
        >>> print(M.table(printer, rowstart='{', rowend='}'))
        {  1, 2}
        {-33, 4}
        z[]r   r  ljustrjustcenter)r  r  r  <>^)r"   r  r   r   r   r   r   _printr  r   r  r9  r  )r   rA  rowstartrowendr?  colsepalignresmaxlenr   r   r  r   elems                 r   r@  zMatrixBase.table  sB   d 66TZZtyytyy! 	3AJJrN499% 3NN41:.Bq!Aq	2q	3	3 
   n 	:FAs$S> 94-u-fQi8A9C 0069CF	: {{3r   c                     t        | ||      S ry  )r}   rz  s      r   rank_decompositionzMatrixBase.rank_decomposition  s    "4J!# 	#r   c                     t        d      Nz;This function is implemented in DenseMatrix or SparseMatrixr   r   r  s     r   choleskyzMatrixBase.cholesky
      !"_``r   c                     t        d      r  r   r  s     r   LDLdecompositionzMatrixBase.LDLdecomposition  r  r   c                      t        | |||      S N)rM  r  	rankcheck)r   r   rM  r  r  s       r   LUdecompositionzMatrixBase.LUdecomposition  s    h#% 	%r   c                      t        | |||      S r  )r   r  s       r   LUdecomposition_Simplez!MatrixBase.LUdecomposition_Simple  s    &t
!Y8 	8r   c                     t        |       S r   )r   r   s    r   LUdecompositionFFzMatrixBase.LUdecompositionFF  s    !$''r   c                     t        |       S r   )r   r   s    r   singular_value_decompositionz'MatrixBase.singular_value_decomposition  s    ,T22r   c                     t        |       S r   )r   r   s    r   QRdecompositionzMatrixBase.QRdecomposition   r  r   c                     t        |       S r   )r   r   s    r   upper_hessenberg_decompositionz)MatrixBase.upper_hessenberg_decomposition#  s    .t44r   c                     t        | |      S r   )rV   r   r}  s     r   diagonal_solvezMatrixBase.diagonal_solve&      tS))r   c                     t        d      r  r   r  s     r   lower_triangular_solvez!MatrixBase.lower_triangular_solve)  r  r   c                     t        d      r  r   r  s     r   upper_triangular_solvez!MatrixBase.upper_triangular_solve,  r  r   c                     t        | |      S r   )rY   r  s     r   cholesky_solvezMatrixBase.cholesky_solve/  r  r   c                     t        | |      S r   )rZ   r  s     r   LDLsolvezMatrixBase.LDLsolve2  s    s##r   c                     t        | ||      S rL  )r[   )r   r}  rM  s      r   LUsolvezMatrixBase.LUsolve5  s    cj99r   c                     t        | |      S r   )r\   ry  s     r   QRsolvezMatrixBase.QRsolve8  s    a  r   c                     t        | ||      S )N)freevar)r]   )r   r	  r   s      r   gauss_jordan_solvezMatrixBase.gauss_jordan_solve;  s    "4G<<r   c                     t        | ||      S )N)arbitrary_matrix)r^   )r   r	  r#  s      r   
pinv_solvezMatrixBase.pinv_solve>  s    45EFFr   c                     t        | ||      S )N)
det_method)r_   )r   r}  r&  s      r   cramer_solvezMatrixBase.cramer_solveA  s    T3:>>r   c                     t        | ||      S r_  )r`   r   r}  r?  s      r   r  zMatrixBase.solveD  s    dC//r   c                     t        | ||      S r_  )ra   r)  s      r   solve_least_squareszMatrixBase.solve_least_squaresG  s    #D#f==r   c                     t        | |      S r_  )rb   ra  s     r   pinvzMatrixBase.pinvJ  s    T&))r   c                     t        | |      S rL  )rc   rO  s     r   inverse_ADJzMatrixBase.inverse_ADJM      44r   c                     t        | |      S rL  )rj   rO  s     r   inverse_BLOCKzMatrixBase.inverse_BLOCKP  s    $:66r   c                     t        | |      S rL  )rd   rO  s     r   
inverse_GEzMatrixBase.inverse_GES      t
33r   c                     t        | |      S rL  )re   rO  s     r   
inverse_LUzMatrixBase.inverse_LUV  r5  r   c                     t        | |      S rL  )rf   rO  s     r   
inverse_CHzMatrixBase.inverse_CHY  r5  r   c                     t        | |      S rL  )rg   rO  s     r   inverse_LDLzMatrixBase.inverse_LDL\  r0  r   c                     t        | |      S rL  )rh   rO  s     r   
inverse_QRzMatrixBase.inverse_QR_  r5  r   c                      t        | |||      S )N)r?  rM  try_block_diag)ri   )r   r?  rM  r?  s       r   r;  zMatrixBase.invb  s    DJ-/ 	/r   c                     t        |       S r   )r   r   s    r   connected_componentszMatrixBase.connected_componentsf  s    $T**r   c                     t        |       S r   )r   r   s    r   "connected_components_decompositionz-MatrixBase.connected_components_decompositioni  s    2488r   c                     t        |       S r   )r   r   s    r   strongly_connected_componentsz(MatrixBase.strongly_connected_componentsl  s    -d33r   c                     t        | |      S )N)rM  )r   )r   rM  s     r   +strongly_connected_components_decompositionz6MatrixBase.strongly_connected_components_decompositiono  s    ;DNNr   )r   )TTr  r   )NN)T)   Nd   FFNF)TNTTTTTT)r   r  )r  )FTNr  )r  )bareissN)r   )r  NNNN)F)FFF)r  )[r$  r  r#  r  )laplace)GJ)CH)RD(  __name__
__module____qualname____doc___op_priority__array_priority__rd  _class_prioritystaticmethodr   r   r"   r  r   r  rF  	_diff_wrtr   r   r0   classmethodr   r   r   propertyr   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,  r.  r4  r6  r;  r=  rB  rI  rs  rU  rZ  r\  rg  ra  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r8   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r!  r#  r%  r(  r8  r+  r9  r/  r1  r3  r  r  r  r9  r@  rC  rH  rP  rT  rX  r\  r^  rB  rd  r  ri  rs  rw  r  r  r  r  r   r  r  r  rl  r  r8  rb  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r	  r  r6   r  r  r  r!  r  r  r*  r,  r0  r/  r  r  r"  rD  rI  rF  rB   rP  rR  rA   rT  rV  rX  r\  rb  r
  r  rh  rj  rl  rn  rp  rr  rC   rD   rK   rL   rM   rN   rO   rJ   rE   rF   rG   rH   rI   rP   rQ   ru  rw  r{  r~  r  rS   rR   rT   rU   r  r  r  r  r  r  r  r  r  r  r  r  r  rk   rl   rm   rn   r  r  r  r  r  r  r  r  r  r  r  r  r  r  ro   rp   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   rq   rr   r   r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r!  r#  r<   r&  r%  objectr.  r0  r5  r=  rB  rL  rQ  rt  rw  rk  r|  rE  r  r  r  rd  r  r  r  r  r%   r  r   r&   r  r  rp  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/  r2  r4  r7  r9  r;  r=  r;  rA  rC  rE  rG  r   _sage_r}   r~   r   r   r   r   r   r   r   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   rj   ri   r   r   r   r   r   r   r   r   r   b   s   5 L IOG$H66D
%%CIDDIE EEE & &":
	C	044:
E	0; . .	.'''1R*@,<6|,4 * *&F2'(1T*>0)d(" 3 3"#>2 40)d * ** + + 6 6
 +c + +" + +
 H H 	 	  %dD K: K:Z + +. _@g _@ _@B , ,( - -. '+ '+T %( %(T4(-;JA H@F9 FQJJNNGHBE(2 ) ))2E6N)(V /; /;b /; /;b C CB (Y ( (
 0 08 *% *%X & &.(>1@ 0 08 )% )%V + +<#((&'&,$87669H$'.)
&89? JN;?&  2G1R	L	L@( GD+$Z>A*"$!&F        +:">
=$6L$6LM@7R7
	 -4MMT  :& '$ >*) +) =)# *#3 :&$ '$<#"J84) :& '\| 9% & <($ )$ 9%% &% "D 9% & :& ' ,E 9$ '. G". ",? 745@1, ,B+I+I"+G+O+O (+7+?+?+9+A+A(1(9(9N+7+?+?+2??L+/<<+4+<+<H+4+<+<H+4+<+<H+;+C+CO+/<<CK+/<<CK+1>>EM+;+C+CO&-5 ) ! ! & E2( &d:
 )00L&..J ==DL ==DL5&n666666M<M<5 "'7 J24 )00K&..I%--H*22M'6MV 04 0I%1< + + / / + + / / $ $K/& *4););I)4)<)<J);)C)C)5)=)=K)>)F)F )B)J)J$)>)F)F )B)J)J$)7)?)?M)5)=)=K)9)A)AO)9)A)AO)7)?)?M)B)J)J$#' 85F68@t8. $)?=P ",'&/P3"%(>&/*=< $j $ $P( %4 /%$B1
D ' 'R : :  [% [%zDL;0<""4H5nM^ (" ("TdL&P%3P\~!#F%3N " Pd:":<( %, %NcLJ D,  ?C!(K Z -4e #aa *14%
 18$8
(3&5*aa*$ '. :!=G?0>* &- 5 (/ 7 %, 4 %, 4 %, 4 &- 5 %, 4 '% /+94O \\F%8%@%@%.%6%6H%6%>%>%5%=%=O%<%D%D"%7%?%?+H+P+P (%5%=%=O-L-T-T"*%4%<%<N%<%D%D"%<%D%D"%4%<%<N%.%6%6H%-%5%5GO%-%5%5GO%8%@%@%0%8%8J%2%:%:L%+^^EM%9%A%A%*]]DL%-%5%5K%,__J%,__J%,__J%-%5%5K%,__J%/%7%7M%)\\CK%:%B%B +33 '. 	'.. ") 	5<< 07r   r   c                     ddl m} t        |dd      r)t        ||      s | g |j                  t        |       S  | |      S )z$Convert mat to a Matrix of type typ.r   rj  rd  F)ro  r   r9  r  r   r   )typr   r   s      r   _convert_matrixr_    s@    4sK'
3
0K
 )CII)tCy))3xr   c                 b    t        | dd       }|yt        |t              xr t        |      dk(  S )Nr   Fr_  )r9  r  r  r   )r   r   s     r   _has_matrix_shapera    s2    E7D)E}eU#7E
a7r   c                 6    t        | d      xr t        | d      S )Nr   r   )ru  )r   s    r   _has_rows_colsrc    s    5&!<geV&<<r   c                     d}t        |t              r|S t        |dd      }|r|dfS |-t        |      st	        |      rt        t        |       |      dfS t        |t              s|dfS |S )z8Convert other to a Matrix, or check for possible scalar.)Ninvalid_typerd  Nr  r%  )r  r9   r9  ra  rc  r_  r   r   )r   r   INVALIDrd  s       r   r  r    s     #G %#{D1I k!! U#~e'<"4:u5{BB eX&'''Nr   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'>
    rV  Nr   zIncompatible classes r#  )r9  rV  r  numpyr  ndarrayImportErrorr
  )r  r	  
priority_A
priority_Brh  s        r   r   r     s      -t4J-t4JJ
++q000;;;; a';;a';;
Q[[!++N
OO  s   C   	CCc                     t        | |      \  }}|dk(  rBt        | |      }|| j                  k7  rt        ||       } ||j                  k7  rt        ||      }| ||fS )zDUnify self and other into a single matrix type, or check for scalar.r  )r  r   r  r_  )r   r   rb  r^  s       r   r  r    sb    tU+HE1KdE"$.. "3-D%//!#C/E>r   c                     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[)r  rs  r9  r   )r   r   jindexs      r   r  r    sn    aK.Aa9::}q5FAQ1q5A?@@q6Mr   c                   "    e Zd ZdZd Zd Zd Zy)rj  a5  A vector whose components are deferred (e.g. for use with lambdify).

    Examples
    ========

    >>> from sympy import DeferredVector, lambdify
    >>> X = DeferredVector( 'X' )
    >>> X
    X
    >>> expr = (X[0] + 2, X[2] + 3)
    >>> func = lambdify( X, expr)
    >>> func( [1, 2, 3] )
    (3, 6)
    c                 h    |dk(  rd}|dk  rt        d      d| j                  |fz  }t        |      S )Nr   z!DeferredVector index out of rangez%s[%d])r   namer   )r   r   component_names      r   r   zDeferredVector.__getitem__$  s>    7Aq5@AA!TYYN2n%%r   c                     t        |       S r   r   r   s    r   r=  zDeferredVector.__str__,  r]  r   c                      d| j                   z  S )NzDeferredVector('%s'))rs  r   s    r   __repr__zDeferredVector.__repr__/  s    %		11r   N)rP  rQ  rR  rS  r   r=  rw  r   r   r   rj  rj    s    &2r   rj  r   )collectionsr   collections.abcr   inspectr   	functoolsr   sympy.assumptions.refiner   
sympy.corer	   r
   sympy.core.basicr   r   sympy.core.kindr   sympy.core.numbersr   sympy.core.modr   sympy.core.symbolr   r   sympy.core.sympifyr   r   sympy.core.functionr   sympy.polysr   $sympy.functions.elementary.complexesr   r   r   sympy.printingr   (sympy.functions.elementary.miscellaneousr   r   r   (sympy.functions.special.tensor_functionsr    r!   sympy.core.singletonr"   sympy.printing.defaultsr#   sympy.printing.strr$   &sympy.functions.elementary.exponentialr%   r&   (sympy.functions.combinatorial.factorialsr'   r(   mpmathrh  r)   sympy.utilities.iterablesr*   sympy.core.exprr+   sympy.core.powerr,   r-   	utilitiesr/   r0   r
  sympy.polys.polytoolsr1   r2   r3   sympy.utilities.miscr4   r5   sympy.core.decoratorsr6   sympy.core.logicr7   r8   sympy.tensor.arrayr9   r:   r;   r&  r<   
exceptionsr=   r>   r?   r@   rA   rB   determinantrC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   
reductionsrR   rS   rT   rU   solversrV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   inverserb   rc   rd   re   rf   rg   rh   ri   rj   	subspacesrk   rl   rm   rn   r  ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   decompositionsr}   r~   r   r   r   r   r   r   r   graphr   r   r   r   __doctest_requires__r   r_  ra  rc  r  r   r  r  rj  r   r   r   <module>r     sh   # $   + ( ( ) &  + 0 $  < <  C C O " - ) ; H  $ -     3 E & : 3 7 1 ( 1 2   :     A @> > > >
   K J6 6 6 6V V V
R R, /;^ yP= yP=xa
8=6"PJ 2V[ 2r   