U
    9%e&                    @   s  d dl Zd dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ 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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"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-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZDmEZEmFZF ddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZT ddlUmVZVmWZWmXZXmYZY ddlZm[Z[m\Z\m]Z]m^Z^ ddl_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZm ddlnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZw dd lxmyZymzZzm{Z{m|Z| dd!l}m~Z~mZmZmZmZmZmZmZmZmZmZ dd"lmZmZmZmZmZmZmZmZmZmZ G d#d$ d$ee5ZG d%d& d&e<ZG d'd( d(eZG d)d* d*eZG d+d, d,eZG d-d. d.e<ZG d/d0 d0e<ZejeeAd1d2 ZejeAeAd3d4 ZG d5d6 d6eeee<e0ZdS )7    N)Callable)Add)Basicdiff)Expr)_NumberKindUndefinedKind)Mul)Pow)S)DummySymboluniquely_named_symbol)sympify_sympify)binomial	factorial)re)explog)MaxMinsqrt)KroneckerDelta
LeviCivita)cancelsstr)	Printable)
StrPrinter)flattenNotIterableis_sequencereshape)as_int
filldedent   )MatrixCommonMatrixErrorNonSquareMatrixErrorNonInvertibleMatrixError
ShapeError
MatrixKinda2idx)_iszero_is_zero_after_expand_mul	_simplify)_find_reasonable_pivot_find_reasonable_pivot_naive	_adjugate	_charpoly	_cofactor_cofactor_matrix_per_det_det_bareiss_det_berkowitz_det_LU_minor_minor_submatrix)_is_echelon_echelon_form_rank_rref)_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)_diagonal_solve_lower_triangular_solve_upper_triangular_solve_cholesky_solve	_LDLsolve_LUsolve_QRsolve_gauss_jordan_solve_pinv_solve_solve_solve_least_squares)
_pinv_inv_mod_inv_ADJ_inv_GE_inv_LU_inv_CH_inv_LDL_inv_QR_inv
_inv_blockc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	DeferredVectora5  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                 C   s2   |dkrd}|dk rt dd| j|f }t|S )Nr   z!DeferredVector index out of rangez%s[%d])
IndexErrornamer   )selfiZcomponent_name r|   V/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sympy/matrices/matrices.py__getitem__T   s    zDeferredVector.__getitem__c                 C   s   t | S Nr   rz   r|   r|   r}   __str__\   s    zDeferredVector.__str__c                 C   s
   d| j  S )NzDeferredVector('%s'))ry   r   r|   r|   r}   __repr___   s    zDeferredVector.__repr__N)__name__
__module____qualname____doc__r~   r   r   r|   r|   r|   r}   rw   D   s   rw   c                   @   s   e Zd ZdZefddZdd ZedfddZd	d
 Z	dddZ
defddZdddZd ddZd!ddZdd Zd"ddZdd Zeje_eje_eje_eje_eje_eje	_eje
_eje_eje_eje_eje_eje_eje_eje_dS )#MatrixDeterminantzProvides basic matrix determinant operations. Should not be instantiated
    directly. See ``determinant.py`` for their implementations.c                 C   s   t | |dS N)
iszerofuncr:   rz   r   r|   r|   r}   _eval_det_bareissg   s    z#MatrixDeterminant._eval_det_bareissc                 C   s   t | S r   )r;   r   r|   r|   r}   _eval_det_berkowitzj   s    z%MatrixDeterminant._eval_det_berkowitzNc                 C   s   t | ||dS )N)r   simpfunc)r<   )rz   r   r   r|   r|   r}   _eval_det_lum   s    zMatrixDeterminant._eval_det_luc                 C   s   t | S r   r9   r   r|   r|   r}   _eval_determinantp   s    z#MatrixDeterminant._eval_determinant	berkowitzc                 C   s   t | |dS Nmethod)r4   rz   r   r|   r|   r}   adjugates   s    zMatrixDeterminant.adjugatelambdac                 C   s   t | ||dS )N)xsimplify)r5   rz   r   r   r|   r|   r}   charpolyv   s    zMatrixDeterminant.charpolyc                 C   s   t | |||dS r   )r6   rz   r{   jr   r|   r|   r}   cofactory   s    zMatrixDeterminant.cofactorc                 C   s   t | |dS r   )r7   r   r|   r|   r}   cofactor_matrix|   s    z!MatrixDeterminant.cofactor_matrixbareissc                 C   s   t | ||dS )N)r   r   r   )rz   r   r   r|   r|   r}   det   s    zMatrixDeterminant.detc                 C   s   t | S r   )r8   r   r|   r|   r}   per   s    zMatrixDeterminant.perc                 C   s   t | |||dS r   )r=   r   r|   r|   r}   minor   s    zMatrixDeterminant.minorc                 C   s   t | ||S r   )r>   rz   r{   r   r|   r|   r}   minor_submatrix   s    z!MatrixDeterminant.minor_submatrix)r   )r   )r   )r   N)r   ) r   r   r   r   r0   r   r   r/   r   r   r   r1   r   r   r   r   r   r   r   r2   r3   r:   r;   r<   r9   r4   r5   r6   r7   r8   r=   r>   r|   r|   r|   r}   r   c   s6   




r   c                   @   s   e Zd ZdZeddfddZedd ZedfddZedd	d	fd
dZ	e
je_eje_eje_eje	_d!ddZdd Zdd Zdd Zdd Zdd Zdd Zd"ddZd#dd ZdS )$MatrixReductionszProvides basic matrix row/column operations. Should not be instantiated
    directly. See ``reductions.py`` for some of their implementations.Fc                 C   s   t | |||dS )N)r   r   with_pivots)r@   )rz   r   r   r   r|   r|   r}   echelon_form   s    zMatrixReductions.echelon_formc                 C   s   t | S r   )r?   r   r|   r|   r}   
is_echelon   s    zMatrixReductions.is_echelonc                 C   s   t | ||dS N)r   r   )rA   rz   r   r   r|   r|   r}   rank   s    zMatrixReductions.rankTc                 C   s   t | ||||dS )N)r   r   pivotsnormalize_last)rB   )rz   r   r   r   r   r|   r|   r}   rref   s     zMatrixReductions.rrefcolc           	      C   s&  |dkrt d|||dkr&| jn| j}|dkr|dk	r@|n|}|dksT|dkrbt d|d|  krv|k sn t d||n|d	kr@||||hdg}t|d
kr|||hdg}t|d
krt d||\}}d|  kr|k sn t d||d|  kr,|k sn t d||n|dkr|dkrX|n|}|dkrj|n|}|dks|dks|dkrt d|||krt d|d|  kr|k sn t d||d|  kr|k sn t d||nt dt| |||||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      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)
ValueErrorformatcolsrows
differencelenrepr)	rz   opr   kcol1col2Z	error_strZ	self_colsr   r|   r|   r}   _normalize_op_args   sX     


z#MatrixReductions._normalize_op_argsc                    s"    fdd} jj|S )Nc                    s$   | kr| |f  S | |f S r   r|   r{   r   r   r   rz   r|   r}   entry   s    zBMatrixReductions._eval_col_op_multiply_col_by_const.<locals>.entry_newr   r   )rz   r   r   r   r|   r   r}   "_eval_col_op_multiply_col_by_const   s    z3MatrixReductions._eval_col_op_multiply_col_by_constc                    s"    fdd} jj|S )Nc                    s4   | kr| f S |kr(|  f S | |f S r   r|   r   r   r   rz   r|   r}   r      s
    z1MatrixReductions._eval_col_op_swap.<locals>.entryr   )rz   r   r   r   r|   r   r}   _eval_col_op_swap   s    z"MatrixReductions._eval_col_op_swapc                    s$    fdd} jj|S )Nc                    s0   | kr$| |f | f   S | |f S r   r|   r   r   r   r   rz   r|   r}   r      s    zFMatrixReductions._eval_col_op_add_multiple_to_other_col.<locals>.entryr   )rz   r   r   r   r   r|   r   r}   &_eval_col_op_add_multiple_to_other_col   s    z7MatrixReductions._eval_col_op_add_multiple_to_other_colc                    s"    fdd} jj|S )Nc                    s4   |  kr|f S | kr( |f S | |f S r   r|   r   row1row2rz   r|   r}   r     s
    z1MatrixReductions._eval_row_op_swap.<locals>.entryr   )rz   r   r   r   r|   r   r}   _eval_row_op_swap  s    z"MatrixReductions._eval_row_op_swapc                    s"    fdd} jj|S )Nc                    s$   | kr | |f  S | |f S r   r|   r   r   rowrz   r|   r}   r     s    zBMatrixReductions._eval_row_op_multiply_row_by_const.<locals>.entryr   )rz   r   r   r   r|   r   r}   "_eval_row_op_multiply_row_by_const  s    z3MatrixReductions._eval_row_op_multiply_row_by_constc                    s$    fdd} jj|S )Nc                    s0   | kr$| |f  |f   S | |f S r   r|   r   r   r   r   rz   r|   r}   r     s    zFMatrixReductions._eval_row_op_add_multiple_to_other_row.<locals>.entryr   )rz   r   r   r   r   r|   r   r}   &_eval_row_op_add_multiple_to_other_row  s    z7MatrixReductions._eval_row_op_add_multiple_to_other_rowr   Nc                 C   s`   |  |||||d\}}}}}|dkr2| ||S |dkrF| ||S |dkr\| |||S dS )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   )rz   r   r   r   r   r   r|   r|   r}   elementary_col_op  s    z"MatrixReductions.elementary_col_opc                 C   s`   |  |||||d\}}}}}|dkr2| ||S |dkrF| ||S |dkr\| |||S dS )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   )rz   r   r   r   r   r   r|   r|   r}   elementary_row_op7  s    z"MatrixReductions.elementary_row_op)r   )r   NNNN)r   NNNN)r   r   r   r   r/   r   propertyr   r   r   r@   r?   rA   rB   r   r   r   r   r   r   r   r   r   r|   r|   r|   r}   r      s*   


7		
r   c                   @   sb   e Zd ZdZdddZdefddZdddZd	d
 Ze	je_e
je_eje_eje_eeZdS )MatrixSubspaceszProvides methods relating to the fundamental subspaces of a matrix.
    Should not be instantiated directly. See ``subspaces.py`` for their
    implementations.Fc                 C   s   t | |dS N)r   )rC   rz   r   r|   r|   r}   columnspace[  s    zMatrixSubspaces.columnspacec                 C   s   t | ||dS )N)r   r   )rD   )rz   r   r   r|   r|   r}   	nullspace^  s    zMatrixSubspaces.nullspacec                 C   s   t | |dS r   )rE   r   r|   r|   r}   rowspacea  s    zMatrixSubspaces.rowspacec                 O   s   t | f||S r   )rF   )clsZvecskwargsr|   r|   r}   orthogonalizeg  s    zMatrixSubspaces.orthogonalizeN)F)F)r   r   r   r   r   r/   r   r   r   rC   rD   rE   rF   classmethodr|   r|   r|   r}   r   V  s   

r   c                   @   s  e Zd ZdZd!ddZdefddZd"dd	Zd#d
dZd$ddZ	d%ddZ
edd Zedd Zedd Zedd Zedd Zd&ddZdd Zdd Zeje_eje_eje_eje_eje_eje_eje_eje_eje_eje_eje_eje_e je	_e!je
_d S )'MatrixEigenzProvides basic matrix eigenvalue/vector operations.
    Should not be instantiated directly. See ``eigen.py`` for their
    implementations.Tc                 K   s   t | fd|i|S )Nerror_when_incomplete)rG   )rz   r   flagsr|   r|   r}   	eigenvalsw  s    zMatrixEigen.eigenvalsc                 K   s   t | f||d|S )N)r   r   )rH   )rz   r   r   r   r|   r|   r}   
eigenvectsz  s
    zMatrixEigen.eigenvectsFc                 K   s   t | fd|i|S )N
reals_only)rK   )rz   r   r   r|   r|   r}   is_diagonalizable~  s    zMatrixEigen.is_diagonalizablec                 C   s   t | |||dS )N)r   sort	normalize)rL   )rz   r   r   r   r|   r|   r}   diagonalize  s    zMatrixEigen.diagonalizec                 C   s   t | |dS N)upper)rI   rz   r   r|   r|   r}   bidiagonalize  s    zMatrixEigen.bidiagonalizec                 C   s   t | |dS r   )rJ   r   r|   r|   r}   bidiagonal_decomposition  s    z$MatrixEigen.bidiagonal_decompositionc                 C   s   t | S r   )rM   r   r|   r|   r}   is_positive_definite  s    z MatrixEigen.is_positive_definitec                 C   s   t | S r   )rN   r   r|   r|   r}   is_positive_semidefinite  s    z$MatrixEigen.is_positive_semidefinitec                 C   s   t | S r   )rO   r   r|   r|   r}   is_negative_definite  s    z MatrixEigen.is_negative_definitec                 C   s   t | S r   )rP   r   r|   r|   r}   is_negative_semidefinite  s    z$MatrixEigen.is_negative_semidefinitec                 C   s   t | S r   )rQ   r   r|   r|   r}   is_indefinite  s    zMatrixEigen.is_indefinitec                 K   s   t | fd|i|S )Ncalc_transform)rR   )rz   r   r   r|   r|   r}   jordan_form  s    zMatrixEigen.jordan_formc                 K   s   t | f|S r   )rS   rz   r   r|   r|   r}   left_eigenvects  s    zMatrixEigen.left_eigenvectsc                 C   s   t | S r   )rT   r   r|   r|   r}   singular_values  s    zMatrixEigen.singular_valuesN)T)F)FFF)T)T)T)"r   r   r   r   r   r/   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rG   rH   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rI   rJ   r|   r|   r|   r}   r   r  sD   










r   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )MatrixCalculusz,Provides calculus-related matrix operations.c                 O   sF   ddl m} |dd || f|ddi}t| ts>| S |S dS )a  Calculate the derivative of each element in 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.diff(x)
        Matrix([
        [1, 0],
        [0, 0]])

        See Also
        ========

        integrate
        limit
        r   )ArrayDerivativeevaluateTN)Z$sympy.tensor.array.array_derivativesr   
setdefault
isinstancer   Z
as_mutable)rz   argsr   r   Zderivr|   r|   r}   r     s    
zMatrixCalculus.diffc                    s   |   fddS )Nc                    s
   |   S r   r   r   argr|   r}   <lambda>      z1MatrixCalculus._eval_derivative.<locals>.<lambda>	applyfunc)rz   r  r|   r  r}   _eval_derivative  s    zMatrixCalculus._eval_derivativec                    s   |   fd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                    s   | j  S r   )	integrater  r   r   r|   r}   r    r  z*MatrixCalculus.integrate.<locals>.<lambda>r  )rz   r   r   r|   r
  r}   r	    s    zMatrixCalculus.integratec                    s   t  ts  jd dkr.jd }n"jd dkrHjd }ntd jd dkrj jd }n" jd dkr jd }ntd|| fd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   r'   z)``self`` must be a row or a column matrixz"X must be a row or a column matrixc                    s   |    | S r   r   )r   r{   Xrz   r|   r}   r  .  r  z)MatrixCalculus.jacobian.<locals>.<lambda>)r   
MatrixBaser   shape	TypeError)rz   r  mnr|   r  r}   jacobian  s    $

zMatrixCalculus.jacobianc                    s   |   fd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                    s
   | j   S r   )limitr  r   r|   r}   r  E  r  z&MatrixCalculus.limit.<locals>.<lambda>r  )rz   r   r|   r  r}   r  0  s    zMatrixCalculus.limitN)	r   r   r   r   r   r  r	  r  r  r|   r|   r|   r}   r     s   9r   c                   @   s   e Zd ZdZedefddZdd Zdd Zd	d
 Z	dd Z
d"ddZdd Zdd Zdd Zd#ddZd$ddZdd Zdd Zdd  Zd!S )%MatrixDeprecatedz+A class to house deprecated matrix methods.r   c                 C   s   | j |dS )Nr  )r   r   r|   r|   r}   berkowitz_charpolyK  s    z#MatrixDeprecated.berkowitz_charpolyc                 C   s   | j ddS )zwComputes determinant using Berkowitz method.

        See Also
        ========

        det
        berkowitz
        r   r   r   r   r|   r|   r}   berkowitz_detN  s    	zMatrixDeprecated.berkowitz_detc                 K   s   | j f |S )zwComputes eigenvalues of a Matrix using Berkowitz method.

        See Also
        ========

        berkowitz
        )r   r   r|   r|   r}   berkowitz_eigenvalsY  s    z$MatrixDeprecated.berkowitz_eigenvalsc                 C   s:   | j g  }}|  D ]}|||d   | }qt|S )zpComputes principal minors using Berkowitz method.

        See Also
        ========

        berkowitz
        )oner   appendtuple)rz   signZminorsZpolyr|   r|   r}   berkowitz_minorsc  s
    z!MatrixDeprecated.berkowitz_minorsc                 C   s  ddl m} d}| s|S | js$t | | j }}dg|d  }t|ddD  ]}||d ||d  }}||d |f  |d ||f  }	}
|d |d |f |||f   }}|
g}td|d D ]}||||   qt|D ]\}}|	| d ||< q| j|g| }t|D ]&}|d || d  ||d |f< q|||d < qJ| 	| j|d  gg}t|D ]\}}||||   qj|t
tt
| S )Nr   zeros)r'   r'   r  r   r   r   )sympy.matricesr!  	is_squarer*   r   ranger  	enumerater  r   r  map)rz   r!  ZberkANZ
transformsr  Tr   RCaitemsr{   BZpolysr|   r|   r}   r   s  s2    $$$zMatrixDeprecated.berkowitzr   c                 C   s   | j |dS r   )r   r   r|   r|   r}   cofactorMatrix  s    zMatrixDeprecated.cofactorMatrixc                 C   s   t | S r   r   r   r|   r|   r}   
det_bareis  s    zMatrixDeprecated.det_bareisc                 C   s   | j d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
        det_bareiss
        berkowitz_det
        Zlur   r  r   r|   r|   r}   det_LU_decomposition  s    z%MatrixDeprecated.det_LU_decompositionc                 C   s   | j ||dS )N)sizeZ
eigenvalue)Zjordan_block)rz   Zeigenvalr  r|   r|   r}   jordan_cell  s    zMatrixDeprecated.jordan_cellTc                 C   s   |   \}}|| fS r   )r   get_diag_blocks)rz   Zcalc_transformationPJr|   r|   r}   jordan_cells  s    zMatrixDeprecated.jordan_cellsc                 C   s   | j |||dS r   )r   r   r|   r|   r}   
minorEntry  s    zMatrixDeprecated.minorEntryc                 C   s   |  ||S r   )r   r   r|   r|   r}   minorMatrix  s    zMatrixDeprecated.minorMatrixc                 C   s   | j |ddS )zEPermute the rows of the matrix with the given permutation in reverse.Zbackward	directionZpermute_rowsrz   permr|   r|   r}   permuteBkwd  s    zMatrixDeprecated.permuteBkwdc                 C   s   | j |ddS )z:Permute the rows of the matrix with the given permutation.forwardr<  r>  r?  r|   r|   r}   
permuteFwd  s    zMatrixDeprecated.permuteFwdN)r   )T)r   )r   r   r   r   r   r1   r  r  r  r  r   r1  r2  r3  r5  r9  r:  r;  rA  rC  r|   r|   r|   r}   r  I  s   
(


r  c                 C   s*   t |ts||  } }t| |j}t|S )z
    Return MatrixKind. The element kind is selected by recursive dispatching.
    Do not need to dispatch in reversed order because KindDispatcher
    searches for this automatically.
    )r   r-   r
   _kind_dispatcherelement_kindZk1Zk2Zelemkr|   r|   r}   num_mat_mul  s    

rG  c                 C   s   t | j|j}t|S )zS
    Return MatrixKind. The element kind is selected by recursive dispatching.
    )r
   rD  rE  r-   rF  r|   r|   r}   mat_mat_mul  s    rH  c                   @   s  e Zd ZdZdZdZdZeeZ	e
jZe
jZeedddZdd	 Zefd
dZdd Zdd Zdd ZdddZedd Zedd Zedd Zdd Zdd Zdd  Zd!d" Z d#d$ Z!ed%d& Z"dd'd(Z#d)d* Z$d+d, Z%d-d. Z&d/d0 Z'd1d2 Z(e)fd3d4Z*d5d6 Z+d7d8 Z,d9d: Z-e.fd;d<Z/dd=d>Z0dd@dAZ1dBdC Z2ddIdJZ3e.dKfdLdMZ4ddNdOZ5ddPdQZ6e.ddKfdRdSZ7e.ddKfdTdUZ8dVdW Z9dXdY Z:dZd[ Z;d\d] Z<d^d_ Z=d`da Z>dbdc Z?ddde Z@dfdg ZAe.fdhdiZBdjdk ZCddldmZDddndoZEddqdrZFddtduZGddwdxZHdydz ZIe.fd{d|ZJe.fd}d~ZKe.fddZLe.fddZMe.fddZNe.fddZOe.fddZPde.dKfddZQdd ZRdd ZSdd ZTdddZUeVjWZWeXje4_eYje5_eZje6_e[je7_e\je8_e]je9_e^je:_e_je;_e`je<_eaje=_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eL_epjeM_eqjeN_erjeO_esjeP_etjeK_eujeQ_evjeR_ewjeS_exjeT_eyjeU_dS )r  zBase class for matrix objects.   T   )returnc                 C   s2   dd |   D }t|dkr&|\}nt}t|S )Nc                 S   s   h | ]
}|j qS r|   )kind).0er|   r|   r}   	<setcomp>  s     z"MatrixBase.kind.<locals>.<setcomp>r'   )flatr   r	   r-   )rz   Z
elem_kindsZelemkindr|   r|   r}   rL    s
    zMatrixBase.kindc                    s    fddt  jD S )Nc                    s(   g | ] }t  jD ]} ||f qqS r|   )r&  r   )rM  r{   r   r   r|   r}   
<listcomp>   s       z#MatrixBase.flat.<locals>.<listcomp>)r&  r   r   r|   r   r}   rP    s    zMatrixBase.flatc                 C   s   ddl m} || |dS )Nr'   )matrix2numpy)dtype)denserR  )rz   rS  rR  r|   r|   r}   	__array__  s    zMatrixBase.__array__c                 C   s   | j | j S )zkReturn the number of elements of ``self``.

        Implemented mainly so bool(Matrix()) == False.
        )r   r   r   r|   r|   r}   __len__  s    zMatrixBase.__len__c                    sp   ddl m}m  dd }|  \}}| } fdd|D }|D ]}||| qB| ||| | S )Nr   )diagMutableMatrixc                 S   s   | j d }| d }|jrl|dkr4|jr4|| | d< q|jr@|jsJtdqt|D ]}t||| d|f< qRnBt|D ]8}t||}t|tr|	 }|||  | | d|f< qtt|D ]<}td|| D ](}| |d || d f | ||| f< qqd S )Nr   r#  r'   zANon-invertible matrix can only be raised to a nonnegative integer)
r  is_zeroZis_nonnegative
is_integerr+   r&  r   r   r   Z_eval_expand_func)Zjcr  r*  lr{   Zbnr   r|   r|   r}   jordan_cell_power  s"    



zBMatrixBase._matrix_pow_by_jordan_blocks.<locals>.jordan_cell_powerc                    s   g | ]} |qS r|   r|   rM  r   rX  r|   r}   rQ  (  s     z;MatrixBase._matrix_pow_by_jordan_blocks.<locals>.<listcomp>)r$  rW  rX  r   r6  r   multiplyinv)rz   numrW  r\  r7  r8  r9  r   r|   r^  r}   _matrix_pow_by_jordan_blocks  s    z'MatrixBase._matrix_pow_by_jordan_blocksc                 C   s,   t j| jkrd| j| jf S dt|   S )NMatrix(%s, %s, [])z
Matrix(%s))r   Zeror  r   r   strtolistr   r|   r|   r}   r   .  s    zMatrixBase.__str__Nc                 C   sT   |s
t  }tj| jkr&d| j| jf S | jdkrBd| j|dd S d| j|dd S )Nrc  r'   zMatrix([%s])z,
)rowsepzMatrix([
%s]))r    r   rd  r  r   r   table)rz   printerr|   r|   r}   _format_str3  s    
zMatrixBase._format_strc                    s   t |}dd |D  ttt dd  D }fddt|D }t fdd|D }g }t|rg }t|D ]V\}	}
| |
 ||
  ddf  ||
  d8  < ||
 dkrxrxd||	< qxt||krt	t
d	|| qd| |S )
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]])
      c                 S   s"   g | ]}t |d r| n|qS )as_explicit)hasattrrk  rM  r{   r|   r|   r}   rQ  R  s   z(MatrixBase.irregular.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r|   )r   rm  r|   r|   r}   rQ  U  s     c                    s   g | ]}  d qS )r   )poprM  _)qr|   r}   rQ  V  s     c                    s   g | ]} | j qS r|   )r   rm  )br|   r}   rQ  W  s     Nr'   r   z^
                Matrices provided do not appear to fill
                the space completely.)r%   listr&  r   sumanyr'  extendrn  r   r&   r  r   )r   ZntopZmatricesr   datactiver   r   rr.  r   r|   )rr  rq  r}   	irregular=  s(     zMatrixBase.irregularc                    s   |  }t|jdkrL|jd |jd  }} fdd| D }|||fS t|jdkr| fdd|D }|jd d|fS tdd S )Nr   r   r'   c                    s   g | ]}  |qS r|   r   rm  r   r|   r}   rQ  o  s     z.MatrixBase._handle_ndarray.<locals>.<listcomp>c                    s   g | ]}  |qS r|   r{  rm  r|  r|   r}   rQ  r  s     z&SymPy supports just 1D and 2D matrices)rU  r   r  ZravelNotImplementedError)r   r  Zarrr   r   	flat_listr|   r|  r}   _handle_ndarrayg  s    
zMatrixBase._handle_ndarrayc                    s  ddl m} ddlm ddlm  d}t|dkrt|d |rf|d j|d j	t
|d  fS t|d tr|d j|d j	|d  fS t|d tr|d jr|d j|d j	|d   fS t|d tjr|d }fdd|D }|j|j	|fS t|d d	r$|d S t|d rt|d tst|d } fd
dfdd|ddr fddfddt|ttfrfdd|D }|g g gfkrd }}g }qtfdd|D sfdd|D }t|}|rdnd}qrtfdd|D rdd |D }	|	rt|	dkrftddd |D }|	 }t|| }nd }}g }qrtfdd|D rt }	g }|D ]r|dd  D  tj rR|	!j	 nLr>rR|	!t |fddD  n|	!d |" t|	dkrtdq|	 }t|| }qg }t }	d }}|D ] }
t|
st#|
dd std!t|
d	rd|
j krqn
|
sqrPtfd"d|
D rP$d#d |
D \
}}t%||g
fd$dt&|D }|
 
}n8d
t#|
dd rnd}|
g}nt|
}fd%d|
D }|	!| t|	dkrtd|| |
7 }q|	r|	 nd}nt|d&krt'|d }t'|d }|dk s|dk rtd'(||t|d&krzt|d( t)rz|d( 	g }t&|D ]&|	fd)dt&|D  qPnPt|d&krt|d( r|d( }t||| krtd*fd+d|D }nt|dkrd }}g }|dkrt*t+d,|||fS )-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   )SparseMatrix)MatrixSymbol)BlockMatrixNr'   c                    s   g | ]}  |qS r|   r{  rM  r   r|  r|   r}   rQ    s     z6MatrixBase._handle_creation_inputs.<locals>.<listcomp>rU  c                    s"   t | to p t |  p t | S r   )r   r  r{   )r  r  r   r|   r}   r    s   
z4MatrixBase._handle_creation_inputs.<locals>.<lambda>c                    s   t | o |  S r   )r#   r  ismatr|   r}   r    r  r   Tc                    s@   t |  r|  S t | r8tdd | jD r8|  S | S dS )zmake Block and Symbol explicitc                 s   s   | ]}|j V  qd S r   )Z
is_Integerro  r|   r|   r}   	<genexpr>  s     zLMatrixBase._handle_creation_inputs.<locals>.make_explicit.<locals>.<genexpr>N)r   rk  allr  r  )r  r  r|   r}   make_explicit  s
    
z9MatrixBase._handle_creation_inputs.<locals>.make_explicitc                    s,   t | ttfr  fdd| D S  | S d S )Nc                    s   g | ]} |qS r|   r|   r  r  r|   r}   rQ    s     zQMatrixBase._handle_creation_inputs.<locals>.make_explicit_row.<locals>.<listcomp>)r   rs  r  )r   r  r|   r}   make_explicit_row  s    z=MatrixBase._handle_creation_inputs.<locals>.make_explicit_rowc                    s   g | ]} |qS r|   r|   )rM  r   )r  r|   r}   rQ    s     c                 3   s   | ]}|p |V  qd S r   r|   rm  )r  rawr|   r}   r    s     z5MatrixBase._handle_creation_inputs.<locals>.<genexpr>c                    s   g | ]}  |qS r|   r{  rm  r|  r|   r}   rQ    s     c                 3   s   | ]} |V  qd S r   r|   rm  r  r|   r}   r    s     c                 S   s   h | ]}t |jr|jqS r|   )ru  r  r   rm  r|   r|   r}   rO    s     
 z5MatrixBase._handle_creation_inputs.<locals>.<setcomp>zmismatched dimensionsc                 S   s(   g | ] }|  D ]}|D ]}|qqqS r|   )rf  )rM  r{   ry  rp  r|   r|   r}   rQ    s     
    c                 3   s   | ]} |V  qd S r   r|   rm  r  r|   r}   r    s     c                 S   s   g | ]}|D ]}|qqS r|   r|   )rM  r   r   r|   r|   r}   rQ    s       c                    s   g | ]}  |qS r|   r{  )rM  Zijr|  r|   r}   rQ    s     	is_MatrixFzexpecting list of listsc                 3   s   | ]} |V  qd S r   r|   rm  r  r|   r}   r    s     c                 S   s   g | ]
}|j qS r|   )r+  rm  r|   r|   r}   rQ    s     c                    s&   g | ]}t D ]} | | qqS r|   )r&  )rM  r   r{   )r+  ry  r|   r}   rQ  "  s     
  c                    s   g | ]}  |qS r|   r{  rm  r|  r|   r}   rQ  +  s     rJ  z@Cannot create a {} x {} matrix. Both dimensions must be positiver   c              	      s(   g | ] }      |qS r|   r{  r]  )r   r{   r   r|   r}   rQ  A  s   z+List length should be equal to rows*columnsc                    s   g | ]}  |qS r|   r{  rm  r|  r|   r}   rQ  J  s     zf
                Data type not understood; expecting list of lists
                or lists of values.),r$  r  "sympy.matrices.expressions.matexprr  Z&sympy.matrices.expressions.blockmatrixr  r   r   r   r   r!   rf  r  rP  r   r  rk  mpmatrixrl  r  r#   rw   rs  getr  ru  r  r   rn  setrv  r  addr  getattr_handle_creation_inputsr$   r&  r%   r   r   r  r&   )r   r   r   r  r~  Mrw  r   r   Zncolr   cZflatTrP  r|   )r  r  r+  r   r   r{   r  r  r  r   ry  r  r}   r  x  s   .""	









 

z"MatrixBase._handle_creation_inputsc                 C   s  ddl m} t|t}| | \}}}t|t}t|tsFt|tr|rZ| || dS t|ts|t|r|| 	|| dS t
d| n|st|tst|r||}d}|r|rtt|| j tt|| j f}n t|||j t|||j f}| || n||| |fS dS d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'   MatrixNzunexpected value: %sT)rT  r  r   slicekey2ijr  Zcopyin_matrixr   r#   Zcopyin_listr   r   divmodr   r   r   )rz   keyvaluer  Zis_slicer{   r   Zis_matr|   r|   r}   _setitemZ  s<    (

zMatrixBase._setitemc                 C   s   | | S )zReturn self + b.r|   rz   rr  r|   r|   r}   r    s    zMatrixBase.addc                 C   s"   | s
| j S |  }t| t|  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
        )zeror   r   r   )rz   Zsingularvaluesr|   r|   r}   condition_number  s    zMatrixBase.condition_numberc                 C   s   |  | 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   rP  r   r|   r|   r}   copy  s    zMatrixBase.copyc              
   C   s   ddl m} t|t|fs.td|t|| j| j |j|j   krRdksvn t	d| j| jf|j|jff nl| 
| j| j| d |d  | d |d   | d |d  | d |d   | d |d  | d |d   fS d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
        multiply
        multiply_elementwise
        r   )
MatrixExprz{} must be a Matrix, not {}.rJ  z/Dimensions incorrect for cross product: %s x %sr'   r   N)r  r  r   r  r  r   typer   r   r,   r   )rz   rr  r  r|   r|   r}   cross  s    &zMatrixBase.crossc                 C   s(   ddl m} | jdkrt| j|d 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.common.MatrixCommon.conjugate: By-element conjugation
        sympy.matrices.common.MatrixCommon.H: Hermite conjugation
        r   )mgamma   )Zsympy.physics.matricesr  r   AttributeErrorH)rz   r  r|   r|   r}   D  s    "
zMatrixBase.Dc                 C   s\  ddl m} t|tsnt|r^t|| jkrPt|| jkrPtd| j	t|f | 
||S tdt| d| j	ksd|j	krtt| t|krtd| j	|j	f | }t|}|j	d|fkr|d|}|j	|dfkr||d}|dk	r|dkrd}|r|dkrd}|dkrP|dkr4| }n|d	krH| }ntd
|| 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'   r  z,Dimensions incorrect for dot product: %s, %sz2`b` must be an ordered iterable or Matrix, not %s.NTmaths)r  leftmath)ZphysicsrightzUnknown conjugate_convention was entered. conjugate_convention must be one of the following: math, maths, left, physics or right.r   )rT  r  r   r  r#   r   r   r   r,   r  dotr  r  r$   	conjugater   )rz   rr  	hermitianZconjugate_conventionr  matr  r|   r|   r}   r    sN    4
 	




zMatrixBase.dotc              	   C   s   ddl m} | ddddf | j }}||}|  r<|S td|D ]`}td|D ]P}d}td|D ]"}|t||d||d|f  7 }qf||||f< | |||f< qTqFtd|D ]h}	d}td|D ]2}
td|D ]"}|td|	|
|||
|f  7 }qq|d }| |d|	f< |||	df< q|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   )r$  r!  r   Zis_symmetricr&  r   )rz   r!  r  r  Zworkr{   r   Zacumr   r[  r.  rr  r|   r|   r}   dual  s*     "zMatrixBase.dualc                    sH   | j }| d }t|  fddt|D }ddlm} | |||S )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#  c                    s   i | ]}| t | qS r|   )r   rm  Zexp_lr|   r}   
<dictcomp>  s      z6MatrixBase._eval_matrix_exp_jblock.<locals>.<dictcomp>r'   banded)r   r   r&  sparsetoolsr  	__class__)rz   r4  r[  bandsr  r|   r  r}   _eval_matrix_exp_jblock  s    z"MatrixBase._eval_matrix_exp_jblockc                 C   s  t |t | }}| jst|js0td|||jkrJtd|||| jkrdtd|| |  }t|	 }i }|}t
|d D ]}t||}|||d < q| jd }| |}	| |d}
d}|D ]j}|| }||||
|< |
| jr|
| jstd||
| d}t
|D ]}||	||f< ||9 }q&|dkr4dd t
|D }d}|dkr4|d }|d8 }|| ||}|jr|jstd	|| |||
|< t
|D ]f}|| d dkrd|	||f< d||< q|| || d  ||< || t|||  |	||f< q|d7 }qb|d7 }q|	|
}| |}| |}t
|D ]}||| |  }|| 9 }qd|S )
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 {}c                 S   s   g | ]}d qS r"  r|   )rM  iir|   r|   r}   rQ    s     z,MatrixBase.analytic_func.<locals>.<listcomp>zaCannot evaluate the function because the derivative {} is not analytic at the given eigenvalue {})r   r%  r*   Z	is_symbolr   r   Zfree_symbolsr   maxvaluesr&  r   r  r!  subsZ	is_numberZ
is_complexpowsolveeye)rz   fr   eigenZmax_mulZ
derivativeddr{   r  ry  f_valr   mulvalr.  ZcoeZderiZd_ir  Zansprer|   r|   r}   analytic_func  s    







 

 "



zMatrixBase.analytic_funcc                 C   s   | j stdz|  \}}| }W n tk
rB   tdY nX dd |D }ddlm} || }|j|ddj|	 dd}t
d	d
 |  D rt| t|S t| |S dS )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 computedc                 S   s   g | ]}|  qS r|   )r  rM  cellr|   r|   r}   rQ  H  s     z"MatrixBase.exp.<locals>.<listcomp>r   rW  N)Zdotprodsimpc                 s   s   | ]}|j V  qd S r   )Zis_real)rM  r  r|   r|   r}   r  M  s     z!MatrixBase.exp.<locals>.<genexpr>)r%  r*   r   r6  r)   r}  r$  rW  r_  r`  r  r  r  r   )rz   r7  r8  cellsblocksrW  eJretr|   r|   r}   r   /  s$    
zMatrixBase.expc                 C   sp   | j }| d }|jr"td|dt|i}td|D ]}| |   | ||< q8ddlm} | |||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   rY  r)   r   r   r&  r  r  r  )rz   r4  r[  r  r{   r  r|   r|   r}   _eval_matrix_log_jblockR  s    z"MatrixBase._eval_matrix_log_jblockc           	      C   s   | j stdz.|r&||  \}}n|  \}}| }W n tk
rX   tdY nX dd |D }ddlm} || }|r||| ||  }| 	|}n|| |  }|S )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 computedc                 S   s   g | ]}|  qS r|   )r  r  r|   r|   r}   rQ    s   z"MatrixBase.log.<locals>.<listcomp>r   r  )
r%  r*   r   r6  r)   r}  r$  rW  r`  r  )	rz   r   r7  r8  r  r  rW  r  r  r|   r|   r}   r   y  s.    4
zMatrixBase.logc                 C   sN   | sdS | j stdtd| dd d}| |}|jd || j krJdS dS )	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                 S   s   d|  S )Nrp  r|   )sr|   r|   r}   r    r  z)MatrixBase.is_nilpotent.<locals>.<lambda>)modifyr   F)r%  r*   r   r   r   r   )rz   r   pr|   r|   r}   is_nilpotent  s    
zMatrixBase.is_nilpotentc                 C   s   dd |D \}}|rD| j s&d }}q\|d | j dd \}}nt|d | j }|d }|r| jspd }}q|d | jdd \}}nt|d | j}|d }||||fS )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
        c                 S   s   g | ]}t |tqS r|   )r   r  )rM  r   r|   r|   r}   rQ    s     z)MatrixBase.key2bounds.<locals>.<listcomp>r   Nr   r'   )r   indicesr.   r   )rz   keysisliceZjsliceZrloZrhiZclochir|   r|   r}   
key2bounds  s    


zMatrixBase.key2boundsc                 C   sl   t |r2t|dkstddd t|| jD S t|trR|t| dd S tt	|t| | j
S dS )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 2c                 S   s(   g | ] \}}t |ts t||n|qS r|   )r   r  r.   )rM  r{   r  r|   r|   r}   rQ    s   z%MatrixBase.key2ij.<locals>.<listcomp>N)r#   r   r  zipr  r   r  r  r  r.   r   )rz   r  r|   r|   r}   r    s    


zMatrixBase.key2ijc                    sT   | j dkr| jdkrtd|   | r>| | j | j}n|  fd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                    s   |   S r   r|   r  normr|   r}   r  =  r  z'MatrixBase.normalized.<locals>.<lambda>)r   r   r,   r  r!  r  )rz   r   outr|   r  r}   
normalized  s    zMatrixBase.normalizedc              	      s  t |  pdg}tj| jkrֈdkr<ttdd |D  S dkrVtdd |D  S tjkrrtdd |D  S tj	krt
d	d |D  S z$ttfd
d|D  tj W S  ttfk
r   tdY nX nʈdkr| t t fddt jD  S dkrt|   S dkr2t
|   S tjkrd| t t fddt jD  S dksttr dkr|  jddS tddS )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                 s   s   | ]}t |d  V  qdS r  absrm  r|   r|   r}   r  x  s     z"MatrixBase.norm.<locals>.<genexpr>r'   c                 s   s   | ]}t |V  qd S r   r  rm  r|   r|   r}   r  {  s     c                 S   s   g | ]}t |qS r|   r  rm  r|   r|   r}   rQ  ~  s     z#MatrixBase.norm.<locals>.<listcomp>c                 S   s   g | ]}t |qS r|   r  rm  r|   r|   r}   rQ    s     c                 3   s   | ]}t |  V  qd S r   r  rm  ordr|   r}   r    s     z'Expected order to be Number, Symbol, ooc                    s   g | ]}t  |qS r|   )rt  r   rm  r  r|   r}   rQ    s     r   c                    s   g | ]}t  |qS r|   )rt  r   rm  r  r|   r}   rQ    s     N)r  ZfroZ	frobeniusZvectorr  zMatrix Norms under development)rs  r  r   Oner  r   r   Infinityr   NegativeInfinityr   r   r}  r  r   r  r  r&  r   r   r   r   re  lowerZvecr  )rz   r  valsr|   )r  r  r}   r  @  sB    5

$




zMatrixBase.normr  c                 C   sx   g }t | jD ]V}g }t | jD ].}| ||f dkr@|d q |t| q |dd|  qtd| dS )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  re  joinprint)rz   Zsymbr  r{   liner   r|   r|   r}   print_nonzero  s    zMatrixBase.print_nonzeroc                 C   s   ||  || |  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  )rz   vr|   r|   r}   project  s    zMatrixBase.project[]r  , r  c                 C   s   t j| jkrdS g }dg| j }t| jD ]T}	|g  t| jD ]:}
|| |	|
f }|d | tt	|||
 ||
< qBq*ddddddd| }t
|D ]F\}	}t
|D ]\}
}t||||
 ||
< q||| | ||	< q||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   rd  r  r   r&  r   r  Z_printr  r   r'  r  r  )rz   ri  ZrowstartZrowendrg  Zcolsepalignresmaxlenr{   r   r  r   elemr|   r|   r}   rh    s0    2
zMatrixBase.tableFc                 C   s   t | ||dS r   )rU   r   r|   r|   r}   rank_decomposition$  s    zMatrixBase.rank_decompositionc                 C   s   t dd S Nz;This function is implemented in DenseMatrix or SparseMatrixr}  rz   r  r|   r|   r}   cholesky(  s    zMatrixBase.choleskyc                 C   s   t dd S r  r  r  r|   r|   r}   LDLdecomposition+  s    zMatrixBase.LDLdecompositionc                 C   s   t | |||dS N)r   r   	rankcheck)rX   rz   r   r   r  r|   r|   r}   LUdecomposition.  s    zMatrixBase.LUdecompositionc                 C   s   t | |||dS r
  )rY   r  r|   r|   r}   LUdecomposition_Simple3  s     z!MatrixBase.LUdecomposition_Simplec                 C   s   t | S r   )rZ   r   r|   r|   r}   LUdecompositionFF8  s    zMatrixBase.LUdecompositionFFc                 C   s   t | S r   )r[   r   r|   r|   r}   singular_value_decomposition;  s    z'MatrixBase.singular_value_decompositionc                 C   s   t | S r   )r\   r   r|   r|   r}   QRdecomposition>  s    zMatrixBase.QRdecompositionc                 C   s   t | S r   )r]   r   r|   r|   r}   upper_hessenberg_decompositionA  s    z)MatrixBase.upper_hessenberg_decompositionc                 C   s
   t | |S r   )rb   rz   rhsr|   r|   r}   diagonal_solveD  s    zMatrixBase.diagonal_solvec                 C   s   t dd S r  r  r  r|   r|   r}   lower_triangular_solveG  s    z!MatrixBase.lower_triangular_solvec                 C   s   t dd S r  r  r  r|   r|   r}   upper_triangular_solveJ  s    z!MatrixBase.upper_triangular_solvec                 C   s
   t | |S r   )re   r  r|   r|   r}   cholesky_solveM  s    zMatrixBase.cholesky_solvec                 C   s
   t | |S r   )rf   r  r|   r|   r}   LDLsolveP  s    zMatrixBase.LDLsolvec                 C   s   t | ||dS r   )rg   )rz   r  r   r|   r|   r}   LUsolveS  s    zMatrixBase.LUsolvec                 C   s
   t | |S r   )rh   r  r|   r|   r}   QRsolveV  s    zMatrixBase.QRsolvec                 C   s   t | ||dS )N)freevar)ri   )rz   r0  r  r|   r|   r}   gauss_jordan_solveY  s    zMatrixBase.gauss_jordan_solvec                 C   s   t | ||dS )N)arbitrary_matrix)rj   )rz   r0  r  r|   r|   r}   
pinv_solve\  s    zMatrixBase.pinv_solveGJc                 C   s   t | ||dS r   )rk   rz   r  r   r|   r|   r}   r  _  s    zMatrixBase.solveCHc                 C   s   t | ||dS r   )rl   r!  r|   r|   r}   solve_least_squaresb  s    zMatrixBase.solve_least_squaresRDc                 C   s   t | |dS r   )rm   r   r|   r|   r}   pinve  s    zMatrixBase.pinvc                 C   s
   t | |S r   )rn   )rz   r  r|   r|   r}   inv_modh  s    zMatrixBase.inv_modc                 C   s   t | |dS r   )ro   r   r|   r|   r}   inverse_ADJk  s    zMatrixBase.inverse_ADJc                 C   s   t | |dS r   )rv   r   r|   r|   r}   inverse_BLOCKn  s    zMatrixBase.inverse_BLOCKc                 C   s   t | |dS r   )rp   r   r|   r|   r}   
inverse_GEq  s    zMatrixBase.inverse_GEc                 C   s   t | |dS r   )rq   r   r|   r|   r}   
inverse_LUt  s    zMatrixBase.inverse_LUc                 C   s   t | |dS r   )rr   r   r|   r|   r}   
inverse_CHw  s    zMatrixBase.inverse_CHc                 C   s   t | |dS r   )rs   r   r|   r|   r}   inverse_LDLz  s    zMatrixBase.inverse_LDLc                 C   s   t | |dS r   )rt   r   r|   r|   r}   
inverse_QR}  s    zMatrixBase.inverse_QRc                 C   s   t | |||dS )N)r   r   try_block_diag)ru   )rz   r   r   r.  r|   r|   r}   r`    s    zMatrixBase.invc                 C   s   t | S r   )r^   r   r|   r|   r}   connected_components  s    zMatrixBase.connected_componentsc                 C   s   t | S r   )r_   r   r|   r|   r}   "connected_components_decomposition  s    z-MatrixBase.connected_components_decompositionc                 C   s   t | S r   )r`   r   r|   r|   r}   strongly_connected_components  s    z(MatrixBase.strongly_connected_componentsc                 C   s   t | |dS )N)r  )ra   )rz   r  r|   r|   r}   +strongly_connected_components_decomposition  s    z6MatrixBase.strongly_connected_components_decomposition)N)NN)N)r  )r  r  r  r  r  )T)T)F)N)r   )r"  )r$  )T)zr   r   r   r   Z__array_priority__r  Z_class_prioritystaticmethodr   r   r   rd  r  r  r  r   r-   rL  rP  objectrU  rV  rb  r   rj  r   rz  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r   r   r  r  r  r/   r  r  r  r  rh  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-  r`  r/  r0  r1  r2  r   Z_sage_rU   rV   rW   rX   rY   rZ   r[   r\   r]   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   rv   ru   r^   r_   r`   ra   r|   r|   r|   r}   r    s   !


)

 bF"
*
f((_#'R'
e
"    
M









r  )Zmpmathr  collections.abcr   Zsympy.core.addr   Zsympy.core.basicr   Zsympy.core.functionr   Zsympy.core.exprr   Zsympy.core.kindr   r	   Zsympy.core.mulr
   Zsympy.core.powerr   Zsympy.core.singletonr   Zsympy.core.symbolr   r   r   Zsympy.core.sympifyr   r   Z(sympy.functions.combinatorial.factorialsr   r   Z$sympy.functions.elementary.complexesr   Z&sympy.functions.elementary.exponentialr   r   Z(sympy.functions.elementary.miscellaneousr   r   r   Z(sympy.functions.special.tensor_functionsr   r   Zsympy.polysr   Zsympy.printingr   Zsympy.printing.defaultsr   Zsympy.printing.strr    Zsympy.utilities.iterablesr!   r"   r#   r$   Zsympy.utilities.miscr%   r&   commonr(   r)   r*   r+   r,   r-   r.   Z	utilitiesr/   r0   r1   Zdeterminantr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   Z
reductionsr?   r@   rA   rB   Z	subspacesrC   rD   rE   rF   r  rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   ZdecompositionsrU   rV   rW   rX   rY   rZ   r[   r\   r]   graphr^   r_   r`   ra   Zsolversrb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   Zinverserm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   r   r   r   r   r   r  rD  registerrG  rH  r  r|   r|   r|   r}   <module>   sh   $<@,408 <F  

