B
    }[>                @   sV  d dl mZmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZmZmZ d d	lmZ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!m"Z" d dl#m$Z$m%Z%m&Z& d dl'm(Z( d dl)m*Z+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3m4Z4 d dl-m5Z5m6Z6m7Z7m8Z8 d dl9m:Z: d dl;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZB d dlCmDZD dd ZEdd ZFG dd dee8ZGG dd  d eBZHG d!d" d"eHZIG d#d$ d$eIZJG d%d& d&eJZKG d'd( d(eBZLG d)d* d*eBZMG d+d, d,eMeLeKeBZNeDd-d.d/d0d1d2 ZOeDd-d/d3d4d<d6d7Z>eEe+fd8d9ZPeEd5fd:d;ZQd5S )=    )print_functiondivision)prec_to_dps)Add)Basic)Expr)
expand_mul)Pow)SymbolDummysymbols_uniquely_named_symbol)Integermod_inverseFloat)S)sympify)sqrtMaxMin)exp	factorial)PurePolyrootscancel)sstr)simplify	nsimplify)reduceas_intstring_typesCallable)flattennumbered_symbols)is_sequencedefault_sort_keyrangeNotIterable)SymPyDeprecationWarning)FunctionType   )a2idxMatrixError
ShapeErrorNonSquareMatrixErrorMatrixCommon)
deprecatedc             C   s    y| j S  tk
r   dS X dS )zReturns True if x is zero.N)is_zeroAttributeError)x r4   6lib/python3.7/site-packages/sympy/matrices/matrices.py_iszero$   s    r6   c             C   s   t | dkS )zNTests by expand_mul only, suitable for polynomials and rational
    functions.r   )r   )r3   r4   r4   r5   _is_zero_after_expand_mul,   s    r7   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	DeferredVectora4  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_namer4   r4   r5   __getitem__B   s    zDeferredVector.__getitem__c             C   s   t | S )N)r   )r;   r4   r4   r5   __str__J   s    zDeferredVector.__str__c             C   s
   d| j  S )NzDeferredVector('%s'))r:   )r;   r4   r4   r5   __repr__M   s    zDeferredVector.__repr__N)__name__
__module____qualname____doc__r=   r>   r?   r4   r4   r4   r5   r8   2   s   r8   c               @   s   e Zd ZdZdd Zdd Z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dZdd Zd
S )%MatrixDeterminantzVProvides basic matrix determinant operations.
    Should not be instantiated directly.c                s   | j dkr&| jdkr&| ddtjgS | d | dddf  } | dddf | ddddf  }}|gx(t| j d D ]}||   q|W  fddD tj| g fdd	}| | jd | j |}||fS )
zReturn (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm
        corresponding to `self` and A is the first principal submatrix.r   r*   )r   r   N   c                s   g | ]}  | d  qS ))r   r   r4   ).0d)Rr4   r5   
<listcomp>v   s    zEMatrixDeterminant._eval_berkowitz_toeplitz_matrix.<locals>.<listcomp>c                s   || krt jS  | |  S )N)r   Zero)r<   j)diagsr4   r5   entryy   s    z@MatrixDeterminant._eval_berkowitz_toeplitz_matrix.<locals>.entry)rowscols_newr   Oner&   append)r;   aCAr<   rM   toeplitzr4   )rH   rL   r5   _eval_berkowitz_toeplitz_matrixU   s    &z1MatrixDeterminant._eval_berkowitz_toeplitz_matrixc             C   sl   | j dkr&| jdkr&| ddtjgS | j dkrT| jdkrT| ddtj| d  gS |  \}}||  S )a   Run the Berkowitz algorithm and return a vector whose entries
            are the coefficients of the characteristic polynomial of `self`.

            Given N x N matrix, efficiently compute
            coefficients of characteristic polynomials of 'self'
            without division in the ground domain.

            This method is particularly useful for computing determinant,
            principal minors and characteristic polynomial when 'self'
            has complicated coefficients e.g. polynomials. Semi-direct
            usage of this algorithm is also important in computing
            efficiently sub-resultant PRS.

            Assuming that M is a square matrix of dimension N x N and
            I is N x N identity matrix, then the Berkowitz vector is
            an N x 1 vector whose entries are coefficients of the
            polynomial

                           charpoly(M) = det(t*I - M)

            As a consequence, all polynomials generated by Berkowitz
            algorithm are monic.

           For more information on the implemented algorithm refer to:

           [1] S.J. Berkowitz, On computing the determinant in small
               parallel time using a small number of processors, ACM,
               Information Processing Letters 18, 1984, pp. 147-150

           [2] M. Keber, Division-Free computation of sub-resultants
               using Bezout matrices, Tech. Report MPI-I-2006-1-006,
               Saarbrucken, 2006
        r   r*   rE   )r   r   )rN   rO   rP   r   rQ   rW   _eval_berkowitz_vector)r;   ZsubmatrV   r4   r4   r5   rX      s    $z(MatrixDeterminant._eval_berkowitz_vectorc                s   d fdd	 t  S )a  Compute matrix determinant using Bareiss' fraction-free
        algorithm which is an extension of the well known Gaussian
        elimination method. This approach is best suited for dense
        symbolic matrices and will result in a determinant with
        minimal number of fractions. It means that less term
        rewriting is needed on resulting formulae.

        TODO: Implement algorithm for sparse matrices (SFF),
        http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
        r*   c                s   j dkrtjS j dkr"d S td d df td\}}d krPtjS dd  }tfddtj D }ttj}	|| fd	d
}|
j d jd | S )Nr   r*   )r   r   )
iszerofuncrE   c             3   s   | ]}| kr|V  qd S )Nr4   )rF   r<   )	pivot_posr4   r5   	<genexpr>   s    zGMatrixDeterminant._eval_det_bareiss.<locals>.bareiss.<locals>.<genexpr>c                sF   | |d f  |d f | df     }|j sBt| |S )Nr*   r   )Zis_Atomr   )r<   rK   ret)cummmatr[   	pivot_valtmp_matr4   r5   rM      s    4zCMatrixDeterminant._eval_det_bareiss.<locals>.bareiss.<locals>.entry)rN   r   rQ   _find_reasonable_pivotr7   rJ   listr&   rO   extractrP   )r_   r^   _signrN   rO   rM   )bareissr;   )r^   r_   r[   r`   ra   r5   rg      s    

z4MatrixDeterminant._eval_det_bareiss.<locals>.bareiss)r*   )r   )r;   r4   )rg   r;   r5   _eval_det_bareiss   s     z#MatrixDeterminant._eval_det_bareissc             C   s    |   }dt|d  |d  S )z8 Use the Berkowitz algorithm to compute the determinant.rZ   r*   )rX   len)r;   berk_vectorr4   r4   r5   _eval_det_berkowitz   s    z%MatrixDeterminant._eval_det_berkowitzNc             C   s   | j dkrtjS | j|dd\}}|||j d |j d f rDtjS t|d rXtj ntj}x"t|j D ]}||||f 9 }qjW |S )a   Computes the determinant of a matrix from its LU decomposition.
        This function uses the LU decomposition computed by
        LUDecomposition_Simple().

        The keyword arguments iszerofunc and simpfunc are passed to
        LUDecomposition_Simple().
        iszerofunc is a callable that returns a boolean indicating if its
        input is zero, or None if it cannot make the determination.
        simpfunc is a callable that simplifies its input.
        The default is simpfunc=None, which indicate that the pivot search
        algorithm should not attempt to simplify any candidate pivots.
        If simpfunc fails to simplify its input, then it must return its input
        instead of a copy.r   N)rY   simpfuncr*   rE   )rN   r   rQ   LUdecomposition_SimplerJ   ri   r&   )r;   rY   rl   lu	row_swapsdetkr4   r4   r5   _eval_det_lu   s    
zMatrixDeterminant._eval_det_luc             C   s   |   S )zuAssumed to exist by matrix expressions; If we subclass
        MatrixDeterminant, we can fully evaluate determinants.)rp   )r;   r4   r4   r5   _eval_determinant  s    z#MatrixDeterminant._eval_determinant	berkowitzc             C   s   |  | S )zReturns the adjugate, or classical adjoint, of
        a matrix.  That is, the transpose of the matrix of cofactors.


        http://en.wikipedia.org/wiki/Adjugate

        See Also
        ========

        cofactor_matrix
        transpose
        )cofactor_matrix	transpose)r;   methodr4   r4   r5   adjugate  s    zMatrixDeterminant.adjugatelambdac                s<   | j | jkrt |  }t||}t fdd|D |S )a  Computes characteristic polynomial det(x*I - self) where I is
        the identity matrix.

        A PurePoly is returned, so using different variables for ``x`` does
        not affect the comparison or the polynomials:

        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy.abc import x, y
        >>> A = Matrix([[1, 3], [2, 0]])
        >>> A.charpoly(x) == A.charpoly(y)
        True

        Specifying ``x`` is optional; a symbol named ``lambda`` is used by
        default (which looks good when pretty-printed in unicode):

        >>> A.charpoly().as_expr()
        lambda**2 - lambda - 6

        And if ``x`` clashes with an existing symbol, underscores will
        be preppended to the name to make it unique:

        >>> A = Matrix([[1, 2], [x, 0]])
        >>> A.charpoly(x).as_expr()
        _x**2 - _x - 2*x

        Whether you pass a symbol or not, the generator can be obtained
        with the gen attribute since it may not be the same as the symbol
        that was passed:

        >>> A.charpoly(x).gen
        _x
        >>> A.charpoly(x).gen == x
        False

        Notes
        =====

        The Samuelson-Berkowitz algorithm is used to compute
        the characteristic polynomial efficiently and without any
        division operations.  Thus the characteristic polynomial over any
        commutative ring without zero divisors can be computed.

        See Also
        ========

        det
        c                s   g | ]} |qS r4   r4   )rF   rS   )r   r4   r5   rI   ^  s    z.MatrixDeterminant.charpoly.<locals>.<listcomp>)rN   rO   r.   rX   r   r   )r;   r3   r   rj   r4   )r   r5   charpoly%  s
    4
zMatrixDeterminant.charpolyc             C   s:   | j | jks| j dk rt d|| d  | ||| S )zCalculate the cofactor of an element.

        See Also
        ========

        cofactor_matrix
        minor
        minor_submatrix
        r*   rZ   rE   )rN   rO   r.   minor)r;   r<   rK   rw   r4   r4   r5   cofactor`  s    zMatrixDeterminant.cofactorc                s8   j jksj dk rt j j fddS )zReturn a matrix containing the cofactor of each element.

        See Also
        ========

        cofactor
        minor
        minor_submatrix
        adjugate
        r*   c                s    | | S )N)r|   )r<   rK   )rw   r;   r4   r5   <lambda>  s    z3MatrixDeterminant.cofactor_matrix.<locals>.<lambda>)rN   rO   r.   rP   )r;   rw   r4   )rw   r;   r5   ru   p  s    z!MatrixDeterminant.cofactor_matrixrg   c             C   sf  |  }|dkrd}|dkr d}|dkr4td| | j| jkrFt | j}|dkrZtjS |dkrj| d	 S |d
kr| d	 | d  | d | d   S |dkr,| d	 | d  | d  | d | d  | d   | d | d  | d   | d | d  | d   | d	 | d  | d   | d | d  | d   S |dkr>|  S |dkrP|  S |dkrb| 	 S dS )a  Computes the determinant of a matrix.  If the matrix
        is at most 3x3, a hard-coded formula is used.
        Otherwise, the determinant using the method `method`.


        Possible values for "method":
          bareis
          berkowitz
          lu
        Zbareisrg   Zdet_lurn   )rg   rt   rn   z$Determinant method '%s' unrecognizedr   r*   )r   r   rE   )r*   r*   )r   r*   )r*   r      )rE   rE   )r*   rE   )rE   r   )r   rE   )rE   r*   rt   N)
lower
ValueErrorrN   rO   r.   r   rQ   rh   rk   rr   )r;   rw   nr4   r4   r5   rp     s0     



zMatrixDeterminant.detc             C   s0   | j | jks| j dk rt | ||j|dS )a  Return the (i,j) minor of `self`.  That is,
        return the determinant of the matrix obtained by deleting
        the `i`th row and `j`th column from `self`.

        See Also
        ========

        minor_submatrix
        cofactor
        det
        r*   )rw   )rN   rO   r.   minor_submatrixrp   )r;   r<   rK   rw   r4   r4   r5   r{     s    zMatrixDeterminant.minorc                s    dk r | j 7  dk r$| j7 d   kr:| j k rVn nd  krT| jk snn td| j  d| j   fddt| j D }fddt| jD }| ||S )zReturn the submatrix obtained by removing the `i`th row
        and `j`th column from `self`.

        See Also
        ========

        minor
        cofactor
        r   z2`i` and `j` must satisfy 0 <= i < `self.rows` (%d)zand 0 <= j < `self.cols` (%d).c                s   g | ]}| kr|qS r4   r4   )rF   rS   )r<   r4   r5   rI     s    z5MatrixDeterminant.minor_submatrix.<locals>.<listcomp>c                s   g | ]}| kr|qS r4   r4   )rF   rS   )rK   r4   r5   rI     s    )rN   rO   r   r&   rd   )r;   r<   rK   rN   rO   r4   )r<   rK   r5   r     s    

2z!MatrixDeterminant.minor_submatrix)rt   )rt   )rt   )rg   )rt   )r@   rA   rB   rC   rW   rX   rh   rk   r6   rr   rs   rx   	_simplifyrz   r|   ru   rp   r{   r   r4   r4   r4   r5   rD   Q   s   ,,0/
;


1
rD   c               @   s   e Zd ZdZdd Z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d Zd-ddZeddfddZd.d!d"Zd/d#d$Zeefd%d&Zedfd'd(Zedddfd)d*Zd S )0MatrixReductionszUProvides basic matrix row/column operations.
    Should not be instantiated directly.c                s"    fdd} jj|S )Nc                s4   | kr| f S |kr(|  f S | |f S )Nr4   )r<   rK   )col1col2r;   r4   r5   rM     s
    z1MatrixReductions._eval_col_op_swap.<locals>.entry)rP   rN   rO   )r;   r   r   rM   r4   )r   r   r;   r5   _eval_col_op_swap  s    z"MatrixReductions._eval_col_op_swapc                s"    fdd} jj|S )Nc                s$   | kr| |f  S | |f S )Nr4   )r<   rK   )colrq   r;   r4   r5   rM     s    zBMatrixReductions._eval_col_op_multiply_col_by_const.<locals>.entry)rP   rN   rO   )r;   r   rq   rM   r4   )r   rq   r;   r5   "_eval_col_op_multiply_col_by_const  s    z3MatrixReductions._eval_col_op_multiply_col_by_constc                s$    fdd} jj|S )Nc                s0   | kr$| |f | f   S | |f S )Nr4   )r<   rK   )r   r   rq   r;   r4   r5   rM     s    zFMatrixReductions._eval_col_op_add_multiple_to_other_col.<locals>.entry)rP   rN   rO   )r;   r   rq   r   rM   r4   )r   r   rq   r;   r5   &_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 )Nr4   )r<   rK   )row1row2r;   r4   r5   rM     s
    z1MatrixReductions._eval_row_op_swap.<locals>.entry)rP   rN   rO   )r;   r   r   rM   r4   )r   r   r;   r5   _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 )Nr4   )r<   rK   )rq   rowr;   r4   r5   rM     s    zBMatrixReductions._eval_row_op_multiply_row_by_const.<locals>.entry)rP   rN   rO   )r;   r   rq   rM   r4   )rq   r   r;   r5   "_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 )Nr4   )r<   rK   )rq   r   r   r;   r4   r5   rM   
  s    zFMatrixReductions._eval_row_op_add_multiple_to_other_row.<locals>.entry)rP   rN   rO   )r;   r   rq   r   rM   r4   )rq   r   r   r;   r5   &_eval_row_op_add_multiple_to_other_row	  s    z7MatrixReductions._eval_row_op_add_multiple_to_other_rowc             C   s$   | j ||dddd\}}}|||fS )zReturns (mat, swaps) where `mat` is a row-equivalent matrix
        in echelon form and `swaps` is a list of row-swaps performed.TF)normalize_last	normalize
zero_above)_row_reduce)r;   rY   rl   reduced
pivot_colsswapsr4   r4   r5   _eval_echelon_form  s
    z#MatrixReductions._eval_echelon_formc                s   | j dks| jdkrdS t fdd| dd df D } | d rd|ob| d d dd f  S |o| dd dd f  S )Nr   Tc             3   s   | ]} |V  qd S )Nr4   )rF   t)rY   r4   r5   r\     s    z4MatrixReductions._eval_is_echelon.<locals>.<genexpr>r*   )r   r   )rN   rO   all_eval_is_echelon)r;   rY   Zzeros_belowr4   )rY   r5   r     s    "z!MatrixReductions._eval_is_echelonTc             C   s"   | j |||ddd\}}}||fS )NT)r   r   )r   )r;   rY   rl   r   r   r   r   r4   r4   r5   
_eval_rref!  s    zMatrixReductions._eval_rrefr   c             C   s
  |dkrt d|||dkrv|dk	r,|n|}|dks@|dkrNt d|d|  krd| jksvn t d|||dkr2t||||fdg}t|d	krt|||fdg}t|d	krt d
||\}}d|  kr| jksn t d||d|  kr | jks2n t d|||dkr|dkrJ|n|}|dkr\|n|}|dks~|dks~|dkrt d|||krt d|d|  kr| jksn t d||d|  kr| jksn t d|||||||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.)zn->knzn<->mzn->n+kmzOUnknown {} operation '{}'. Valid col operations are 'n->kn', 'n<->m', 'n->n+km'zn->knNzEFor a {0} operation 'n->kn' you must provide the kwargs `{0}` and `k`r   z"This matrix doesn't have a {} '{}'zn<->mrE   zIFor a {0} operation 'n<->m' you must provide the kwargs `{0}1` and `{0}2`zn->n+kmzPFor 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.)r   formatrO   set
differenceri   )r;   opr   rq   r   r   Z	error_strrO   r4   r4   r5   _normalize_op_args'  sH    



z#MatrixReductions._normalize_op_argsc                sJ   fdd  fddt jD }dd t|D }j|dd|fS )a~  Permute columns with complicated elements as
        far right as they can go.  Since the `sympy` row reduction
        algorithms start on the left, having complexity right-shifted
        speeds things up.

        Returns a tuple (mat, perm) where perm is a permutation
        of the columns to perform to shift the complex columns right, and mat
        is the permuted matrix.c                s"   t  fddd d | f D S )Nc             3   s"   | ]} |d krdndV  qd S )Nr*   r   r4   )rF   e)rY   r4   r5   r\   e  s    zQMatrixReductions._permute_complexity_right.<locals>.complexity.<locals>.<genexpr>)sum)r<   )rY   r;   r4   r5   
complexityb  s    z>MatrixReductions._permute_complexity_right.<locals>.complexityc                s   g | ]} ||fqS r4   r4   )rF   r<   )r   r4   r5   rI   f  s    z>MatrixReductions._permute_complexity_right.<locals>.<listcomp>c             S   s   g | ]\}}|qS r4   r4   )rF   r<   rK   r4   r4   r5   rI   g  s    rO   )Zorientation)r&   rO   sortedZpermute)r;   rY   complexpermr4   )r   rY   r;   r5   _permute_complexity_rightX  s    
z*MatrixReductions._permute_complexity_rightc                sv  | j | j } t|  fdd} fdd} fdd}	d\}
}g }g }xz| k r|
|k rt|||
d ||\}}}}x(|D ] \}}||
7 }||  | < qW |dkr|d	7 }qT|| |d
kr||
||
  ||
||
 f |dkr\|
| }}tj|  | < x8t|  | d	 |d	   D ]}| | |< q<W tj}xdt|D ]X}||
krxqf|dkr||
k rqf|  |  }||rqf|	||||
 qfW |
d	7 }
qTW |dkrV|dkrVxrt|D ]f\}}|  |  }tj|  | < x8t|  | d	 |d	   D ]}| | |< q6W qW | 	| j | jt
|t
|fS )a  Row reduce `self` and return a tuple (rref_matrix,
        pivot_cols, swaps) where pivot_cols are the pivot columns
        and swaps are any row swaps that were used in the process
        of row reduction.

        Parameters
        ==========

        iszerofunc : determines if an entry can be used as a pivot
        simpfunc : used to simplify elements and test if they are
            zero if `iszerofunc` returns `None`
        normalize_last : indicates where all row reduction should
            happen in a fraction-free manner and then the rows are
            normalized (so that the pivots are 1), or whether
            rows should be normalized along the way (like the naive
            row reduction algorithm)
        normalize : whether pivot rows should be normalized so that
            the pivot value is 1
        zero_above : whether entries above the pivot should be zeroed.
            If `zero_above=False`, an echelon matrix will be returned.
        c                s   | d   S )Nr4   )r<   )rO   r_   r4   r5   get_col  s    z-MatrixReductions._row_reduce.<locals>.get_colc                s^   |  |d    |   | d     |   | d   < |  |d   < d S )Nr*   r4   )r<   rK   )rO   r_   r4   r5   row_swap  s    z.MatrixReductions._row_reduce.<locals>.row_swapc                sP   ||   }x>t |  |d   D ]$}| |  |||    |< q$W dS )z,Does the row op row[i] = a*row[i] - b*row[j]r*   N)r&   )rS   r<   brK   qp)rO   r_   r4   r5   cross_cancel  s    z2MatrixReductions._row_reduce.<locals>.cross_cancel)r   r   Nr*   r   FT)rN   rO   rc   rb   rR   r   rQ   r&   	enumeraterP   tuple)r;   rY   rl   r   r   r   rN   r   r   r   piv_rowpiv_colr   r   Zpivot_offsetr`   Zassumed_nonzeronewly_determinedoffsetvalr<   rK   r   r   Zpiv_iZpiv_jr4   )rO   r_   r5   r   k  sX    


$

$zMatrixReductions._row_reduceFc             C   s4   t |tr|nt}| ||\}}}|r0||fS |S )zReturns a matrix row-equivalent to `self` that is
        in echelon form.  Note that echelon form of a matrix
        is *not* unique, however, properties like the row
        space and the null space are preserved.)
isinstancer)   r   r   )r;   rY   r   with_pivotsrl   r_   pivotsr   r4   r4   r5   echelon_form  s    zMatrixReductions.echelon_formn->knNc             C   s`   |  |||||d\}}}}}|dkr2| ||S |dkrF| ||S |dkr\| |||S dS )aW  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   zn->knzn<->mzn->n+kmN)r   r   r   r   )r;   r   r   rq   r   r   r4   r4   r5   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 )a(  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   zn->knzn<->mzn->n+kmN)r   r   r   r   )r;   r   r   rq   r   r   r4   r4   r5   elementary_row_op  s    z"MatrixReductions.elementary_row_opc             C   s
   |  |S )zReturns `True` if the matrix is in echelon form.
        That is, all rows of zeros are at the bottom, and below
        each leading non-zero in a row are exclusively zeros.)r   )r;   rY   r4   r4   r5   
is_echelon  s    zMatrixReductions.is_echelonc                s   t |tr|nt}| jdks&| jdkr*dS | jdks>| jdkr\ fdd| D }d|kr\dS | jdkr| jdkr fdd| D }d|krd|krdS |  } |rd|krdS  |dkrdS | j d	\}}|j |d
\}}	}
t|	S )a  
        Returns the rank of a matrix

        >>> from sympy import Matrix
        >>> from sympy.abc import x
        >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
        >>> m.rank()
        2
        >>> n = Matrix(3, 3, range(1, 10))
        >>> n.rank()
        2
        r   r*   c                s   g | ]} |qS r4   r4   )rF   r3   )rY   r4   r5   rI   4  s    z)MatrixReductions.rank.<locals>.<listcomp>FrE   c                s   g | ]} |qS r4   r4   )rF   r3   )rY   r4   r5   rI   8  s    N)rY   )rY   rl   )	r   r)   r   rN   rO   rp   r   r   ri   )r;   rY   r   rl   zerosrp   r_   re   r   r   r   r4   )rY   r5   rank  s(    zMatrixReductions.rankc             C   s6   t |tr|nt}| j|||d\}}|r2||f}|S )a  Return reduced row-echelon form of matrix and indices of pivot vars.

        Parameters
        ==========

        iszerofunc : Function
            A function used for detecting whether an element can
            act as a pivot.  `lambda x: x.is_zero` is used by default.
        simplify : Function
            A function used to simplify elements when looking for a pivot.
            By default SymPy's `simplify`is used.
        pivots : True or False
            If `True`, a tuple containing the row-reduced matrix and a tuple
            of pivot columns is returned.  If `False` just the row-reduced
            matrix is returned.
        normalize_last : True or False
            If `True`, no pivots are normalized to `1` until after all entries
            above and below each pivot are zeroed.  This means the row
            reduction algorithm is fraction free until the very last step.
            If `False`, the naive row reduction procedure is used where
            each pivot is normalized to be `1` before row operations are
            used to zero above and below the pivot.

        Notes
        =====

        The default value of `normalize_last=True` can provide significant
        speedup to row reduction, especially on matrices with symbols.  However,
        if you depend on the form row reduction algorithm leaves entries
        of the matrix, set `noramlize_last=False`


        Examples
        ========

        >>> from sympy import Matrix
        >>> from sympy.abc import x
        >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
        >>> m.rref()
        (Matrix([
        [1, 0],
        [0, 1]]), (0, 1))
        >>> rref_matrix, rref_pivots = m.rref()
        >>> rref_matrix
        Matrix([
        [1, 0],
        [0, 1]])
        >>> rref_pivots
        (0, 1)
        )rY   rl   r   )r   r)   r   r   )r;   rY   r   r   r   rl   r]   r   r4   r4   r5   rrefE  s    3zMatrixReductions.rref)T)r   )TTT)r   NNNN)r   NNNN)r@   rA   rB   rC   r   r   r   r   r   r   r   r   r   r   r   r   r6   r   r   r   propertyr   r   r   r4   r4   r4   r5   r     s*   			

1 
a

'r   c               @   s>   e Zd ZdZdddZdefddZdddZed	d
 Z	dS )MatrixSubspaceszmProvides methods relating to the fundamental subspaces
    of a matrix.  Should not be instantiated directly.Fc                s$    j |dd\}} fdd|D S )a  Returns a list of vectors (Matrix objects) that span columnspace of self

        Examples
        ========

        >>> from sympy.matrices import Matrix
        >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
        >>> m
        Matrix([
        [ 1,  3, 0],
        [-2, -6, 0],
        [ 3,  9, 6]])
        >>> m.columnspace()
        [Matrix([
        [ 1],
        [-2],
        [ 3]]), Matrix([
        [0],
        [0],
        [6]])]

        See Also
        ========

        nullspace
        rowspace
        T)r   r   c                s   g | ]}  |qS r4   )r   )rF   r<   )r;   r4   r5   rI     s    z/MatrixSubspaces.columnspace.<locals>.<listcomp>)r   )r;   r   r   r   r4   )r;   r5   columnspace  s    zMatrixSubspaces.columnspacec       
         s   j ||d\}  fddtjD }g }x\|D ]T}tjgj }tj||< x,t D ] \}}	||	  |||f 8  < qZW || q4W fdd|D S )a  Returns list of vectors (Matrix objects) that span nullspace of self

        Examples
        ========

        >>> from sympy.matrices import Matrix
        >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
        >>> m
        Matrix([
        [ 1,  3, 0],
        [-2, -6, 0],
        [ 3,  9, 6]])
        >>> m.nullspace()
        [Matrix([
        [-3],
        [ 1],
        [ 0]])]

        See Also
        ========

        columnspace
        rowspace
        )rY   r   c                s   g | ]}| kr|qS r4   r4   )rF   r<   )r   r4   r5   rI     s    z-MatrixSubspaces.nullspace.<locals>.<listcomp>c                s   g | ]}   jd |qS )r*   )rP   rO   )rF   r   )r;   r4   r5   rI     s    )r   r&   rO   r   rJ   rQ   r   rR   )
r;   r   rY   r   Z	free_varsbasisZfree_varvecr   r   r4   )r   r;   r5   	nullspace  s    

zMatrixSubspaces.nullspacec                s,   | j |dd\ } fddtt|D S )z:Returns a list of vectors that span the row space of self.T)r   r   c                s   g | ]}  |qS r4   )r   )rF   r<   )r   r4   r5   rI     s    z,MatrixSubspaces.rowspace.<locals>.<listcomp>)r   r&   ri   )r;   r   r   r4   )r   r5   rowspace  s    zMatrixSubspaces.rowspacec                s   | dd}dd   fdd}g }x t|dkrD|d jrD|d= q&W x&|D ]}|||}|jsL|| qLW |rdd	 |D }|S )
a+  Apply the Gram-Schmidt orthogonalization procedure
        to vectors supplied in `vecs`.

        Arguments
        =========

        vecs : vectors to be made orthogonal
        normalize : bool. Whether the returned vectors
                    should be renormalized to be unit vectors.
        r   Fc             S   s   ||  || |  S )N)dot)rS   r   r4   r4   r5   project  s    z.MatrixSubspaces.orthogonalize.<locals>.projectc                s6    fdd|D }t |dkr$ S  tdd | S )zPprojects vec onto the subspace given
            by the orthogonal basis `basis`c                s   g | ]} |qS r4   r4   )rF   r   )r   r   r4   r5   rI     s    zKMatrixSubspaces.orthogonalize.<locals>.perp_to_subspace.<locals>.<listcomp>r   c             S   s   | | S )Nr4   )rS   r   r4   r4   r5   r}     s    zIMatrixSubspaces.orthogonalize.<locals>.perp_to_subspace.<locals>.<lambda>)ri   r   )r   r   Z
components)r   )r   r5   perp_to_subspace  s    z7MatrixSubspaces.orthogonalize.<locals>.perp_to_subspacer   c             S   s   g | ]}||   qS r4   )norm)rF   r   r4   r4   r5   rI     s    z1MatrixSubspaces.orthogonalize.<locals>.<listcomp>)getri   r1   rR   )clsZvecskwargsr   r   r]   r   Zperpr4   )r   r5   orthogonalize  s    


zMatrixSubspaces.orthogonalizeN)F)F)
r@   rA   rB   rC   r   r6   r   r   classmethodr   r4   r4   r4   r5   r     s
   
 *
r   c               @   s^   e Zd ZdZdZdZdddZdddZdefd	d
Z	dddZ
dddZdd Zdd ZdS )MatrixEigenz\Provides basic matrix eigenvalue/vector operations.
    Should not be instantiated directly.NFc       
      C   s   | j st | j|dds"td| j}|dkr<| jdd}|rLt|td}g g  }}x(|D ] \}}}	||g| 7 }||	7 }q\W |rdd	 |D }| j| | j	| fS )
a>  
        Return (P, D), where D is diagonal and

            D = P^-1 * M * P

        where M is current matrix.

        Parameters
        ==========

        reals_only : bool. Whether to throw an error if complex numbers are need
                     to diagonalize. (Default: False)
        sort : bool. Sort the eigenvalues along the diagonal. (Default: False)
        normalize : bool. If True, normalize the columns of P. (Default: False)

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
        >>> m
        Matrix([
        [1,  2, 0],
        [0,  3, 0],
        [2, -4, 2]])
        >>> (P, D) = m.diagonalize()
        >>> D
        Matrix([
        [1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]])
        >>> P
        Matrix([
        [-1, 0, -1],
        [ 0, 0, -1],
        [ 2, 1,  2]])
        >>> P.inv() * m * P
        Matrix([
        [1, 0, 0],
        [0, 2, 0],
        [0, 0, 3]])

        See Also
        ========

        is_diagonal
        is_diagonalizable
        F)
reals_onlyclear_cachezMatrix is not diagonalizableNT)r   )keyc             S   s   g | ]}||   qS r4   )r   )rF   vr4   r4   r5   rI   N  s    z+MatrixEigen.diagonalize.<locals>.<listcomp>)
	is_squarer.   is_diagonalizabler,   _cache_eigenvects
eigenvectsr   r%   hstackdiag)
r;   r   sortr   Z	eigenvecsZp_colsr   r   multr   r4   r4   r5   diagonalize	  s     2
zMatrixEigen.diagonalizeTc                s  | dd| dd}|   s$i S |ddrPtdd  D rP dd	   js\ jr| jsht  fd
dt j	D }|r|}n2i }xx|D ]$}||krd||< ||  d7  < qW nJ|dd t
trt jtddf|}nt jtddf|}|rDt
|tr&t| nt|| jkrDtd| sN|S t
ts^t|szfdd| D S fdd|D S dS )a  Return eigenvalues using the Berkowitz agorithm to compute
        the characteristic polynomial.

        Parameters
        ==========

        error_when_incomplete : bool
            Raise an error when not all eigenvalues are computed. This is
            caused by ``roots`` not returning a full list of eigenvalues.

        simplify : bool or function
            If simplify is set to True, it attempts to return the most
            simplified form of expressions returned by applying default
            simplification method in every routine.
            If simplify is set to False, it will skip simplification in this
            particular routine to save computation resources.
            If you pass a function to simplify, it will attempt to apply
            the particular function as simplification method.

        Since the roots routine doesn't always work well with Floats,
        they will be replaced with Rationals before calling that
        routine. If this is not desired, set flag ``rational`` to False.
        r   FmultiplerationalTc             s   s   | ]}| tV  qd S )N)hasr   )rF   r   r4   r4   r5   r\   q  s    z(MatrixEigen.eigenvals.<locals>.<genexpr>c             S   s   t | ddS )NT)r   )r   )r3   r4   r4   r5   r}   r  s    z'MatrixEigen.eigenvals.<locals>.<lambda>c                s   g | ]} ||f qS r4   r4   )rF   r<   )r_   r4   r5   rI   x  s    z)MatrixEigen.eigenvals.<locals>.<listcomp>r   r*   Nr3   )r3   r   )r3   z$Could not compute eigenvalues for {}c                s   i | ]\}}| |qS r4   r4   )rF   r   value)r   r4   r5   
<dictcomp>  s    z)MatrixEigen.eigenvals.<locals>.<dictcomp>c                s   g | ]} |qS r4   r4   )rF   r   )r   r4   r5   rI     s    )r   popany	applyfuncis_upperis_lowerr   r.   r&   rN   r   r)   r   rz   r   dictr   valuesri   rO   r,   r   r   items)r;   error_when_incompleteflagsr   Zdiagonal_entrieseigsZdiagonal_entryr4   )r_   r   r5   	eigenvalsR  sB    

(zMatrixEigen.eigenvalsc       	         s   ddl m} |ddtts2r*tndd |dd}|dd |d	d
 tdd D }|r~dd fddj	f d|d|}fddt
| tdD }|rfddfdd|D }|r fdd|D }|S )a  Return list of triples (eigenval, multiplicity, basis).

        The flag ``simplify`` has two effects:
            1) if bool(simplify) is True, as_content_primitive()
            will be used to tidy up normalization artifacts;
            2) if nullspace needs simplification to compute the
            basis, the simplify flag will be passed on to the
            nullspace routine which will interpret it there.

        Parameters
        ==========

        error_when_incomplete : bool
            Raise an error when not all eigenvalues are computed. This is
            caused by ``roots`` not returning a full list of eigenvalues.

        If the matrix contains any Floats, they will be changed to Rationals
        for computation purposes, but the answers will be returned after being
        evaluated with evalf. If it is desired to removed small imaginary
        portions during the evalf step, pass a value for the ``chop`` flag.
        r   )eyer   Tc             S   s   | S )Nr4   )r3   r4   r4   r5   r}     s    z(MatrixEigen.eigenvects.<locals>.<lambda>Fchopr   Nc             s   s   | ]}| tV  qd S )N)r   r   )rF   r   r4   r4   r5   r\     s    z)MatrixEigen.eigenvects.<locals>.<genexpr>c             S   s   t | ddS )NT)r   )r   )r3   r4   r4   r5   r}     s    c                sZ    j|   }|j d}t|dkr>r>|j dd}t|dkrVtd|  |S )z:Get a basis for the eigenspace for a particular eigenvalue)rY   r   T)rY   r   z,Can't evaluate eigenvector for eigenvalue %s)r   rN   r   ri   NotImplementedError)eigenvalmr]   )rY   r_   r;   r   r4   r5   
eigenspace  s    
z*MatrixEigen.eigenvects.<locals>.eigenspace)r   r   c                s   g | ]\}}|| |fqS r4   r4   )rF   r   r   )r   r4   r5   rI     s    z*MatrixEigen.eigenvects.<locals>.<listcomp>)r   c                s    ddl m   fdd| D S )Nr   )gcdc                s"   g | ]}| t | qS r4   )rc   r   )rF   r   )r   rl   r4   r5   rI     s    z?MatrixEigen.eigenvects.<locals>.denom_clean.<locals>.<listcomp>)sympyr   )l)rl   )r   r5   denom_clean  s    z+MatrixEigen.eigenvects.<locals>.denom_cleanc                s    g | ]\}}}|| |fqS r4   r4   )rF   r   r   es)r   r4   r5   rI     s    c                s2   g | ]*\}}}|j  d | fdd|D fqS ))r   c                s   g | ]}|j  d qS ))r   )evalf)rF   r   )r   r4   r5   rI     s    z5MatrixEigen.eigenvects.<locals>.<listcomp>.<listcomp>)r   )rF   r   r   r   )r   r4   r5   rI     s    )sympy.matricesr   r   r   r)   r   r   r   r   r   r   r   r%   )	r;   r   rY   r   r   Z	primitive
has_floatsr   r]   r4   )r   r   r   rY   r_   r;   rl   r   r5   r     s.    

zMatrixEigen.eigenvectsc                s   | dd d|kr| d  fdd}js<|  dS jdk	rVj}|  |S tdd	 D r rd_|  dS jdd
_d}x2jD ](\}}}|r|jsd}|t|krd}qW |  |S )al  Returns true if a matrix is diagonalizable.

        Parameters
        ==========

        reals_only : bool. If reals_only=True, determine whether the matrix can be
                     diagonalized without complex numbers. (Default: False)

        kwargs
        ======

        clear_cache : bool. If True, clear the result of any computations when finished.
                      (Default: True)

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
        >>> m
        Matrix([
        [1,  2, 0],
        [0,  3, 0],
        [2, -4, 2]])
        >>> m.is_diagonalizable()
        True
        >>> m = Matrix(2, 2, [0, 1, 0, 0])
        >>> m
        Matrix([
        [0, 1],
        [0, 0]])
        >>> m.is_diagonalizable()
        False
        >>> m = Matrix(2, 2, [0, 1, -1, 0])
        >>> m
        Matrix([
        [ 0, 1],
        [-1, 0]])
        >>> m.is_diagonalizable()
        True
        >>> m.is_diagonalizable(reals_only=True)
        False

        See Also
        ========

        is_diagonal
        diagonalize
        r   TZclear_subproductsc                  s    rd_ d_dS )z%Clears any cached values if requestedN)r   _cache_is_diagonalizabler4   )r   r;   r4   r5   cleanup  s    z.MatrixEigen.is_diagonalizable.<locals>.cleanupFNc             s   s   | ]}|j V  qd S )N)is_real)rF   r   r4   r4   r5   r\   (  s    z0MatrixEigen.is_diagonalizable.<locals>.<genexpr>)r   )	r   r   r   r   is_symmetricr   r   r   ri   )r;   r   r   r   r]   r   r   r   r4   )r   r;   r5   r     s0    3


zMatrixEigen.is_diagonalizablec                s  j std|dd tdd D rtytdd jD }W n tk
rd   d}Y nX tt|d fd	d
}i fddfdd}dd }fdd}r̈dd 	 }t
dd | D jkrtdt| jkrdtt| td}	j|	 }
|s>||
S fdd|	D }j| }|||
S g }x\t| tdD ]H|}||}dd t|D }|  |fdd|D  qzW fdd|D }	j|	 }
|s||
S g }xt| tdD ]g }x|D ]x\}}|kr*q| }|d  }||| |fddt|D }|| |t| qW qW j| }|||
S )a{  Return `(P, J)` where `J` is a Jordan block
        matrix and `P` is a matrix such that

            `self == P*J*P**-1`


        Parameters
        ==========

        calc_transform : bool
            If ``False``, then only `J` is returned.
        chop : bool
            All matrices are convered to exact types when computing
            eigenvalues and eigenvectors.  As a result, there may be
            approximation errors.  If ``chop==True``, these errors
            will be truncated.

        Examples
        ========

        >>> from sympy import Matrix
        >>> m = Matrix([[ 6,  5, -2, -3], [-3, -1,  3,  3], [ 2,  1, -2, -3], [-1,  1,  5,  5]])
        >>> P, J = m.jordan_form()
        >>> J
        Matrix([
        [2, 1, 0, 0],
        [0, 2, 0, 0],
        [0, 0, 2, 1],
        [0, 0, 0, 2]])

        See Also
        ========

        jordan_block
        z&Only square matrices have Jordan formsr   Fc             s   s   | ]}| tV  qd S )N)r   r   )rF   r   r4   r4   r5   r\   c  s    z*MatrixEigen.jordan_form.<locals>.<genexpr>c             s   s   | ]}t |tr|jV  qd S )N)r   r   Z_prec)rF   Ztermr4   r4   r5   r\   g  s    5      c                 s0   r fdd| D } t | dkr,| d S | S )zMIf `has_floats` is `True`, cast all `args` as
            matrices of floats.c                s   g | ]}|j  d qS ))Zprecr   )r   )rF   r   )r   max_dpsr4   r5   rI   t  s    zCMatrixEigen.jordan_form.<locals>.restore_floats.<locals>.<listcomp>r*   r   )ri   )args)r   r   r  r4   r5   restore_floatsp  s
    z/MatrixEigen.jordan_form.<locals>.restore_floatsc                sz   | |fkr| |f S | |d fkrN| |d f | df  | |f< n  |  j  | | |f< | |f S )zICache computations of (self - val*I)**pow for quick
            retrievalr*   )r   rN   )r   pow)r_   	mat_cacher;   r4   r5   eig_mat{  s    & z(MatrixEigen.jordan_form.<locals>.eig_matc                s\   j }dg}| | d  }d}x4||d krV|| | | |  }|d7 }q$W |S )zuCalculate the sequence  [0, nullity(E), nullity(E**2), ...]
            until it is constant where `E = self - val*I`r   r*   rE   rZ   )rO   r   rR   )r   rO   r]   Znullityr<   )r	  r;   r4   r5   nullity_chain  s    
z.MatrixEigen.jordan_form.<locals>.nullity_chainc                sP    fddt dt d D }t dkr> d  d  gn d g}|| S )zReturn a list of the size of each Jordan block.
            If d_n is the nullity of E**n, then the number
            of Jordan blocks of size n is

                2*d_n - d_(n-1) - d_(n+1)c                s0   g | ](}d  |   |d    |d   qS )rE   r*   r4   )rF   r   )rG   r4   r5   rI     s    zNMatrixEigen.jordan_form.<locals>.blocks_from_nullity_chain.<locals>.<listcomp>r*   rZ   r   )r&   ri   )rG   Zmidendr4   )rG   r5   blocks_from_nullity_chain  s     (z:MatrixEigen.jordan_form.<locals>.blocks_from_nullity_chainc                sV   t | dkr|d S x<|D ]4} j| |g  jdd\}}|d t | kr|S qW dS )z[Picks a vector from big_basis that isn't in
            the subspace spanned by small_basisr   T)r   rZ   N)ri   r   r   )Zsmall_basisZ	big_basisr   re   r   )r;   r4   r5   pick_vec  s    
z)MatrixEigen.jordan_form.<locals>.pick_vecc             S   s   t | ddS )NT)r   )r   )r3   r4   r4   r5   r}     s    z)MatrixEigen.jordan_form.<locals>.<lambda>c             s   s   | ]
}|V  qd S )Nr4   )rF   r   r4   r4   r5   r\     s    z$Could not compute eigenvalues for {})r   c                s   g | ]} |d   d qS )r*   r   )r   )rF   eig)r	  r4   r5   rI     s    z+MatrixEigen.jordan_form.<locals>.<listcomp>c             S   s   g | ]\}}|d  |fqS )r*   r4   )rF   r<   numr4   r4   r5   rI     s    c             3   s(   | ] \}}t |D ]} |fV  qqd S )N)r&   )rF   sizer  re   )r  r4   r5   r\     s    c             3   s    | ]\}} j ||d V  qdS ))r  
eigenvalueN)jordan_block)rF   r  r  )r_   r4   r5   r\     s    r*   c                s   g | ]} | qS r4   r4   )rF   r<   )r  r	  r   r4   r5   rI     s    )r   r.   r   r   max_matr   r   r   r   r   r   rO   r,   r   ri   keysrc   r   r%   r   r   r   reverseextendr   r&   reversed)r;   Zcalc_transformr   Zmax_precr  r
  r  r  r   blocksZ
jordan_matZjordan_basisZ	basis_matZblock_structurechainZblock_sizesZ	size_numsZ	eig_basisZ	block_eigr  Znull_bigZ
null_smallZnew_vecsr4   )	r   r  r	  r   r_   r  r  r;   r   r5   jordan_form:  sp    $








zMatrixEigen.jordan_formc             K   s   |   jf |}dd |D S )a#  Returns left eigenvectors and eigenvalues.

        This function returns the list of triples (eigenval, multiplicity,
        basis) for the left eigenvectors. Options are the same as for
        eigenvects(), i.e. the ``**flags`` arguments gets passed directly to
        eigenvects().

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])
        >>> M.eigenvects()
        [(-1, 1, [Matrix([
        [-1],
        [ 1],
        [ 0]])]), (0, 1, [Matrix([
        [ 0],
        [-1],
        [ 1]])]), (2, 1, [Matrix([
        [2/3],
        [1/3],
        [  1]])])]
        >>> M.left_eigenvects()
        [(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2,
        1, [Matrix([[1, 1, 1]])])]

        c             S   s&   g | ]\}}}||d d |D fqS )c             S   s   g | ]}|  qS r4   )rv   )rF   r   r4   r4   r5   rI     s    z:MatrixEigen.left_eigenvects.<locals>.<listcomp>.<listcomp>r4   )rF   r   r   r   r4   r4   r5   rI     s    z/MatrixEigen.left_eigenvects.<locals>.<listcomp>)rv   r   )r;   r   r   r4   r4   r5   left_eigenvects  s    zMatrixEigen.left_eigenvectsc             C   sP   | }|j |  }g }x&| D ]\}}|t|g| 7 }q W |jdtd |S )a_  Compute the singular values of a Matrix

        Examples
        ========

        >>> from sympy import Matrix, Symbol
        >>> x = Symbol('x', real=True)
        >>> A = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]])
        >>> A.singular_values()
        [sqrt(x**2 + 1), 1, 0]

        See Also
        ========

        condition_number
        T)r  r   )Hr   r   r   r   r%   )r;   r_   Zvalmultpairsvalsrq   r   r4   r4   r5   singular_values  s    zMatrixEigen.singular_values)FFF)T)F)T)r@   rA   rB   rC   r   r   r   r   r6   r   r   r  r  r   r4   r4   r4   r5   r     s   
I
JE
Y
 A!r   c               @   sP   e Zd ZdZdd Zdd Zd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             G   s    ddl m} || f|ddiS )a  Calculate the derivative of each element in the matrix.
        ``args`` will be passed to the ``integrate`` function.

        Examples
        ========

        >>> from sympy.matrices 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   )
DerivativeZevaluateT)r   r"  )r;   r  r"  r4   r4   r5   diff>  s    zMatrixCalculus.diffc                s   |   fddS )Nc                s
   |   S )N)r#  )r3   )argr4   r5   r}   W  s    z1MatrixCalculus._eval_derivative.<locals>.<lambda>)r   )r;   r$  r4   )r$  r5   _eval_derivativeV  s    zMatrixCalculus._eval_derivativec             C   s
   | | S )N)_visit_eval_derivative_array)r;   sr4   r4   r5   _accept_eval_derivativeY  s    z&MatrixCalculus._accept_eval_derivativec                s   |   fddS )Nc                s
     | S )N)r#  )r3   )baser4   r5   r}   ^  s    z>MatrixCalculus._visit_eval_derivative_scalar.<locals>.<lambda>)r   )r;   r)  r4   )r)  r5   _visit_eval_derivative_scalar\  s    z,MatrixCalculus._visit_eval_derivative_scalarc             C   s   ddl m} ||| S )Nr   )derive_by_array)r   r+  )r;   r)  r+  r4   r4   r5   r&  `  s    z+MatrixCalculus._visit_eval_derivative_arrayc                s   |   fddS )a  Integrate each element of the matrix.  ``args`` will
        be passed to the ``integrate`` function.

        Examples
        ========

        >>> from sympy.matrices 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 )N)	integrate)r3   )r  r4   r5   r}   ~  s    z*MatrixCalculus.integrate.<locals>.<lambda>)r   )r;   r  r4   )r  r5   r,  e  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 )N)r#  )rK   r<   )Xr;   r4   r5   r}     s    z)MatrixCalculus.jacobian.<locals>.<lambda>)r   
MatrixBaserP   shape	TypeError)r;   r-  r   r   r4   )r-  r;   r5   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.matrices 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 )N)limit)r3   )r  r4   r5   r}     s    z&MatrixCalculus.limit.<locals>.<lambda>)r   )r;   r  r4   )r  r5   r2    s    zMatrixCalculus.limitN)r@   rA   rB   rC   r#  r%  r(  r*  r&  r,  r1  r2  r4   r4   r4   r5   r!  ;  s   9r!  c               @   s   e Zd ZdZd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 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.c             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| | }|j|jkr|jdkr|j}|j}t||  }|S |j|jkr|
|jS |j|jkr|j
|S td| j	|j	f dS )zQCompatibility function for deprecated behavior of ``matrix.dot(vector)``
        r*   )Matrixz,Dimensions incorrect for dot product: %s, %sz2`b` must be an ordered iterable or Matrix, not %s.N)denser4  r   r.  r$   ri   rO   rN   r-   r/  r   r0  typeTr"   tolist)r;   r   r4  r_   Zprodr4   r4   r5   _legacy_array_dot  s0    

z"MatrixDeprecated._legacy_array_dotry   c             C   s   | j |dS )N)r3   )rz   )r;   r3   r   r4   r4   r5   berkowitz_charpoly  s    z#MatrixDeprecated.berkowitz_charpolyc             C   s   | j ddS )zwComputes determinant using Berkowitz method.

        See Also
        ========

        det
        berkowitz
        rt   )rw   )rp   )r;   r4   r4   r5   berkowitz_det  s    	zMatrixDeprecated.berkowitz_detc             K   s   | j f |S )zwComputes eigenvalues of a Matrix using Berkowitz method.

        See Also
        ========

        berkowitz
        )r   )r;   r   r4   r4   r5   berkowitz_eigenvals  s    z$MatrixDeprecated.berkowitz_eigenvalsc             C   s>   t jg  }}x(|  D ]}|||d   | }qW t|S )zpComputes principal minors using Berkowitz method.

        See Also
        ========

        berkowitz
        rZ   )r   rQ   rt   rR   r   )r;   rf   ZminorsZpolyr4   r4   r5   berkowitz_minors  s
    
z!MatrixDeprecated.berkowitz_minorsc             C   s  ddl m} d}| s|S | js$t | | j }}dg|d  }xt|ddD ]}||d ||d  }}||d |f  |d ||f  }	}
|d |d |f |||f   }}|
g}x(td|d D ]}||||   qW x$t|D ]\}}|	| d ||< qW tj	|g| }x2t|D ]&}|d || d  ||d |f< q"W |||d < qNW | 
tj	|d  gg}x(t|D ]\}}||||   q~W |ttt| S )Nr   )r   ))r*   r*   rZ   rE   )r   r   )r   r   r   r.   rN   r&   rR   r   r   rQ   rP   r   map)r;   r   ZberkrU   NZ
transformsr   r7  rq   rH   rT   rS   r   r<   BZpolysr4   r4   r5   rt     s2    $$&zMatrixDeprecated.berkowitzrt   c             C   s   | j |dS )N)rw   )ru   )r;   rw   r4   r4   r5   cofactorMatrixE  s    zMatrixDeprecated.cofactorMatrixc             C   s   | j ddS )Nrg   )rw   )rp   )r;   r4   r4   r5   
det_bareisH  s    zMatrixDeprecated.det_bareisc             C   s   | j ddS )a;  Compute matrix determinant using Bareiss' fraction-free
        algorithm which is an extension of the well known Gaussian
        elimination method. This approach is best suited for dense
        symbolic matrices and will result in a determinant with
        minimal number of fractions. It means that less term
        rewriting is needed on resulting formulae.

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

        See Also
        ========

        det
        berkowitz_det
        rg   )rw   )rp   )r;   r4   r4   r5   det_bareissK  s    zMatrixDeprecated.det_bareissc             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
        rn   )rw   )rp   )r;   r4   r4   r5   det_LU_decomposition^  s    z%MatrixDeprecated.det_LU_decompositionc             C   s   | j ||dS )N)r  r  )r  )r;   r   r   r4   r4   r5   jordan_cells  s    zMatrixDeprecated.jordan_cellTc             C   s   |   \}}|| fS )N)r  get_diag_blocks)r;   Zcalc_transformationPJr4   r4   r5   jordan_cellsv  s    zMatrixDeprecated.jordan_cellsc             C   s   | j |||dS )N)rw   )r{   )r;   r<   rK   rw   r4   r4   r5   
minorEntryz  s    zMatrixDeprecated.minorEntryc             C   s   |  ||S )N)r   )r;   r<   rK   r4   r4   r5   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)permute_rows)r;   r   r4   r4   r5   permuteBkwd  s    zMatrixDeprecated.permuteBkwdc             C   s   | j |ddS )z:Permute the rows of the matrix with the given permutation.Zforward)rL  )rM  )r;   r   r4   r4   r5   
permuteFwd  s    zMatrixDeprecated.permuteFwdN)rt   )T)rt   )r@   rA   rB   rC   r9  r   r   r:  r;  r<  r=  rt   rA  rB  rC  rD  rE  rI  rJ  rK  rN  rO  r4   r4   r4   r5   r3    s"   !
(


r3  c               @   s  e Zd ZdZdZdZdZeeZ	dZ
efddZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd ZdyddZedd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zed*d+ Z d,d- Z!d.d/ Z"d0d1 Z#d2d3 Z$dzd5d6Z%d7d8 Z&e'fd9d:Z(e'fd;d<Z)e'fd=d>Z*d{d?d@Z+dAdB Z,dCdD Z-dEdF Z.dGdH Z/dIdJ Z0dKdL Z1e'dd4fdMdNZ2e'dd4fdOdPZ3dQdR Z4e'fdSdTZ5dUdV Z6dWdX Z7d|dYdZZ8d}d[d\Z9d]d^ Z:d~d`daZ;dbdc Z<ddde Z=dfdg Z>ddidjZ?ddldmZ@ddsdtZAdudv ZBddwdxZCdS )r.  zBase class for matrix objects.   Tr~   Nc             C   s   ddl m} || |dS )Nr*   )matrix2numpy)dtype)r5  rQ  )r;   rR  rQ  r4   r4   r5   	__array__  s    zMatrixBase.__array__c                s2    dkr fdd}|S t djj f d S )N)r#  r,  r2  c                 s    fdd} |S )Nc                s   t |   S )N)getattr)item)r  attrr4   r5   r}     s    z6MatrixBase.__getattr__.<locals>.doit.<locals>.<lambda>)r   )r  Z	item_doit)rV  r;   )r  r5   doit  s    z$MatrixBase.__getattr__.<locals>.doitz%s has no attribute %s.)r2   	__class__r@   )r;   rV  rW  r4   )rV  r;   r5   __getattr__  s
    zMatrixBase.__getattr__c             C   s   | j | j S )zgReturn the number of elements of self.

        Implemented mainly so bool(Matrix()) == False.
        )rN   rO   )r;   r4   r4   r5   __len__  s    zMatrixBase.__len__c             C   s\   d}xJt | jD ]<}|d7 }x&t | jD ]}|| ||f  7 }q(W |d7 }qW d| d S )N z<matrixrow>z</matrixrow>z<matrix>z	</matrix>)r&   rN   rO   
__mathml__)r;   Zmmlr<   rK   r4   r4   r5   r\    s    zMatrixBase.__mathml__c             C   s
   | |k S )Nr4   )r;   otherr4   r4   r5   __ne__  s    zMatrixBase.__ne__c                s   ddl m}m  ddlm fdd}|  \}}| } fdd|D }x|D ]}||| qTW | |||  |  S )Nr   )r   MutableMatrix)binomialc                s   | j d }| d }|dkr4||d k dkr4tdn$|dkrX|dkrX|d dkrXtdx^t|D ]R}xLt|| D ]<} ||}t| r| }|||  | | ||| f< qtW qbW d S )Nr   )r   r   r*   FzMatrix det == 0; not invertiblez%Non-integer power cannot be evaluated)r/  r   r&   r   Z_eval_expand_func)Zjcr   r?  r   r<   rK   Zbn)r`  r4   r5   jordan_cell_power  s    



zBMatrixBase._matrix_pow_by_jordan_blocks.<locals>.jordan_cell_powerc                s   g | ]} |qS r4   r4   )rF   rK   )r_  r4   r5   rI     s    z;MatrixBase._matrix_pow_by_jordan_blocks.<locals>.<listcomp>)	r   r   r_  r   r`  r  rF  rP   inv)r;   r  r   ra  rG  rH  rI  rK   r4   )r_  r`  r5   _matrix_pow_by_jordan_blocks  s    
z'MatrixBase._matrix_pow_by_jordan_blocksc             C   s   t | S )N)r   )r;   r4   r4   r5   r?     s    zMatrixBase.__repr__c             C   s4   | j dks| jdkr$d| j | jf S dt|   S )Nr   zMatrix(%s, %s, [])z
Matrix(%s))rN   rO   strr8  )r;   r4   r4   r5   r>     s    zMatrixBase.__str__c             C   s   | ` | `| `d S )N)Z_is_symbolicZ_is_symmetricZ_eigenvects)r;   r4   r4   r5   _diagonalize_clear_subproducts  s    z)MatrixBase._diagonalize_clear_subproductsc             C   sh   |sddl m} | }| jdks*| jdkr:d| j| jf S | jdkrVd| j|dd S d| j|dd S )	Nr   )
StrPrinterzMatrix(%s, %s, [])r*   zMatrix([%s])z,
)rowsepzMatrix([
%s]))Zsympy.printing.strrf  rN   rO   table)r;   printerrf  r4   r4   r5   _format_str  s    
zMatrixBase._format_strc          	      s$  ddl m} d}t|dkrt|d |rN|d j|d jt|d  fS t|d trx|d j|d j|d j	fS t|d t
r|d jr|d j|d j|d  j	fS t|d dr~|d  }t|jdkr|jd |jd  }} fdd| D }|||fS t|jdkrr|jd d }}tjg| }x(tt|D ] | |< qLW |||fS td	qt|d rt|d tsg }t }	x|d D ]|}
t|
tr||
  |
js|
jr*|	|
j n>||
 y|	t|
 W n  tk
r(   |	d Y nX qW t|	dkrRtd
tt|	 |	r`|	  nd}|rrt|nd}|rt|d sd} fdd|D }|||fS g }x>t|D ]2}x*t|D ]| ||   qW qW nt|dkrt!|d }t!|d }|dk s,|dk r<td"||t|dkrt|d t#r|d g }xt|D ]&| fddt|D  qpW nPt|dkrt|d r|d }t||| krtd fdd|D }nt|dkrd }}g }|dkr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]])

        r   )SparseMatrixNr*   rS  rE   c                s   g | ]}  |qS r4   )_sympify)rF   r<   )r   r4   r5   rI   0  s    z6MatrixBase._handle_creation_inputs.<locals>.<listcomp>z&SymPy supports just 1D and 2D matricesz Got rows of variable lengths: %sc                s   g | ]}  |qS r4   )rl  )rF   r<   )r   r4   r5   rI   T  s    r~   z@Cannot create a {} x {} matrix. Both dimensions must be positivec          	      s(   g | ] }      |qS r4   )rl  )rF   rK   )r   r<   r   r4   r5   rI   i  s   z+List length should be equal to rows*columnsc                s   g | ]}  |qS r4   )rl  )rF   r<   )r   r4   r5   rI   r  s    zData type not understood)$Zsympy.matrices.sparserk  ri   r   rN   rO   r"   r8  r.  r  r   	is_MatrixZas_explicithasattrrS  r/  Zravelr   rJ   r&   rl  r   r$   r8   r   r  addrR   r0  r   r   rc   r   r   r   r!   )r   r  r   rk  Z	flat_listZarrrN   rO   Zin_matZncolr   rK   r4   )r   r<   r   r5   _handle_creation_inputs  s    +" 




(

z"MatrixBase._handle_creation_inputsc             C   s"  ddl m} t|t}| | \}}}t|t}t|tksJt|tkr|r^| || dS t|tst	|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*   )r4  Nzunexpected value: %sT)r5  r4  r   slicekey2ijr.  r6  Zcopyin_matrixr   r$   Zcopyin_listr   r   divmodrO   rN   rl  )r;   r   r   r4  Zis_slicer<   rK   Zis_matr4   r4   r5   _setitem  s2    (

zMatrixBase._setitemc             C   s   | | S )zReturn self + b r4   )r;   r   r4   r4   r5   ro    s    zMatrixBase.addc             C   sT   | j r|  }n.| j| jkr6| j|   }| j| }ntd||}|j|S )a  Solves Ax = B using Cholesky decomposition,
        for a general square non-singular matrix.
        For a non-square matrix with rows > cols,
        the least squares solution is returned.

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        diagonal_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv_solve
        z6Under-determined System. Try M.gauss_jordan_solve(rhs))is_hermitian	_choleskyrN   rO   r  r   _lower_triangular_solve_upper_triangular_solve)r;   rhsLYr4   r4   r5   cholesky_solve  s    

zMatrixBase.cholesky_solvec             C   s$   | j std| jstd|  S )a  Returns the Cholesky decomposition L of a matrix A
        such that L * L.H = A

        A must be a Hermitian positive-definite matrix.

        Examples
        ========

        >>> from sympy.matrices import Matrix
        >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
        >>> A.cholesky()
        Matrix([
        [ 5, 0, 0],
        [ 3, 3, 0],
        [-1, 1, 3]])
        >>> A.cholesky() * A.cholesky().T
        Matrix([
        [25, 15, -5],
        [15, 18,  0],
        [-5,  0, 11]])

        The matrix can have complex entries:

        >>> from sympy import I
        >>> A = Matrix(((9, 3*I), (-3*I, 5)))
        >>> A.cholesky()
        Matrix([
        [ 3, 0],
        [-I, 2]])
        >>> A.cholesky() * A.cholesky().H
        Matrix([
        [   9, 3*I],
        [-3*I,   5]])

        See Also
        ========

        LDLdecomposition
        LUdecomposition
        QRdecomposition
        zMatrix must be square.zMatrix must be Hermitian.)r   r.   ru  r   rv  )r;   r4   r4   r5   cholesky  s
    +zMatrixBase.choleskyc             C   s"   | s
t 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
        )r   rJ   r   r   r   )r;   Zsingularvaluesr4   r4   r5   condition_number	  s    zMatrixBase.condition_numberc             C   s   |  | 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]])

        )rP   rN   rO   r  )r;   r4   r4   r5   copy/	  s    zMatrixBase.copyc          
   C   s   t |stdt| | j| j |j|j   kr<dks`n 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
        z2`b` must be an ordered iterable or Matrix, not %s.r~   z/Dimensions incorrect for cross product: %s x %sr*   rE   r   N)r$   r0  r6  rN   rO   r-   rP   )r;   r   r4   r4   r5   cross@	  s    &zMatrixBase.crossc             C   s(   ddl m} | jdkrt| j|d S )ak  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
        ========

        conjugate: By-element conjugation
        H: Hermite conjugation
        r   )mgamma   )Zsympy.physics.matricesr  rN   r2   r  )r;   r  r4   r4   r5   D`	  s    "
zMatrixBase.Dc             C   s,   | j std|j| jkr"td| |S )a  Solves Ax = B efficiently, where A is a diagonal Matrix,
        with non-zero diagonal entries.

        Examples
        ========

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

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv_solve
        zMatrix should be diagonalzSize mis-match)Zis_diagonalr0  rN   _diagonal_solve)r;   ry  r4   r4   r5   diagonal_solve	  s
    zMatrixBase.diagonal_solvec             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ddddd	  ||S t|t|krtd| j	|j	f t|}|j	d|fkr|d|}|j	|dfkr||d}|| d
 S )a  Return the dot product of two vectors of equal length. ``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.

        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

        See Also
        ========

        cross
        multiply
        multiply_elementwise
        r*   )r4  z,Dimensions incorrect for dot product: %s, %sz2`b` must be an ordered iterable or Matrix, not %s.z%Dot product of non row/column vectorsi5  z1.2z* to take matrix products)Zfeatureissuedeprecated_since_version
useinsteadr   )r5  r4  r   r.  r$   ri   rO   rN   r-   r/  r   r0  r6  r(   warnr9  reshape)r;   r   r4  r_   r   r4   r4   r5   r   	  s6    

zMatrixBase.dotc          	   C   sD  ddl m} ddlm} | ddddf | j }}||}|  rH|S xvtd|D ]h}xbtd|D ]T}d}x0td|D ]"}	||||d|	|d|	f  7 }qxW ||||f< | |||f< qdW qTW x~td|D ]p}
d}xDtd|D ]6}x0td|D ]"}||d|
|||||f  7 }qW qW |d }| |d|
f< |||
df< qW |S )a  Returns the dual of a matrix, which 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   )
LeviCivita)r   Nr*   rE   )r   r  r   r   rN   r  r&   )r;   r  r   Mr   Zworkr<   rK   Zacumrq   r   rS   r   r4   r4   r5   dual	  s,    "&zMatrixBase.dualc       
      C   s   | j stdy|  \}}| }W n tk
rB   tdY nX dd }tt||}ddlm	} ddl
m} || }|| |  }	tdd	 |  D rt| ||	S t| |	S d
S )z-Return the exponentiation of a square matrix.z0Exponentiation is valid only for square matricesz`Exponentiation is implemented only for matrices for which the Jordan normal form can be computedc       	      S   s   | j }| d }|dkr t|}ndddlm} | d || }| | }||}x&td|D ]}||| t|  }qXW t| d | }|S )N)r   r   r*   r   )r   )rN   r   r   r   r&   r   )	r   Znrr   resr   rG   r   Znexr<   r4   r4   r5   _jblock_exponential
  s    
z+MatrixBase.exp.<locals>._jblock_exponentialr   )r   )rec             s   s   | ]}|j V  qd S )N)r   )rF   r   r4   r4   r5   r\   1
  s    z!MatrixBase.exp.<locals>.<genexpr>N)r   r.   r  rF  r,   r   rc   r>  r   r   r   r  rb  r   r   r6  )
r;   rG  rH  Zcellsr  r  r   r  ZeJr]   r4   r4   r5   r   
  s$    zMatrixBase.expFc                s  ddl m}m} | |  | }|ddddf j\} |jdd\}}|ddddf |dddf  }}	tt fdd|}t	|}
|t
 j}|||}x t|D ]\}}||| qW |ddddf |dddf  }}|	|
ddf jstd	|t	|d }td
|dd dj}t||fddt
 |
 D  |
 d}|d|
|
df }|	d|
df }||||  |}| d}x&t|D ]\}}	|	||| df< qW |r|||fS ||fS dS )a:	  
        Solves Ax = b using Gauss Jordan elimination.

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

        Parameters
        ==========

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

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

        Returns
        =======

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

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

        Examples
        ========

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

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

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv

        References
        ==========

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

        r   )r4  r   NrZ   T)r   c                s   |  k S )Nr4   )r   )r   r4   r5   r}   
  s    z/MatrixBase.gauss_jordan_solve.<locals>.<lambda>zLinear system has no solutiontauc             S   s   t | dS )NZ
1234567890)rd  rstrip)r<   r4   r4   r5   r}   
  s    )Zcomparec                s   g | ]}t  qS r4   )next)rF   rq   )genr4   r5   rI   
  s    z1MatrixBase.gauss_jordan_solve.<locals>.<listcomp>r*   )r   r4  r   r   r  r/  r   rc   filterri   r&   r7  Zvstackr   Zcol_swapr1   r   r   r:   r#   r  )r;   r   Zfreevarr4  r   Zaugr   rU   r   r   r   Zpermutationr<   cZfree_var_indexr:   r  VZvtZfree_solZsolrq   r4   )r   r  r5   gauss_jordan_solve6
  s:    S&&*

zMatrixBase.gauss_jordan_solvec                s   | j st | j|  }dyt|W n  tk
rL   td Y nX |   |  fddtD }|S )at  
        Returns the inverse of the matrix `K` (mod `m`), if it exists.

        Method to find the matrix inverse of `K` (mod `m`) implemented in this function:

        * Compute `\mathrm{adj}(K) = \mathrm{cof}(K)^t`, the adjoint matrix of `K`.

        * Compute `r = 1/\mathrm{det}(K) \pmod m`.

        * `K^{-1} = r\cdot \mathrm{adj}(K) \pmod m`.

        Examples
        ========

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

        Nz!Matrix is not invertible (mod %d)c                s.   g | ]&}t D ]} ||f   qqS r4   )r&   )rF   r<   rK   )K_adjr?  det_invr   r4   r5   rI   
  s    z&MatrixBase.inv_mod.<locals>.<listcomp>)	r   r.   rO   rp   r   r   rx   rX  r&   )r;   r   Zdet_KZK_invr4   )r  r?  r  r   r5   inv_mod
  s    zMatrixBase.inv_modc                sr   | j std| jdd}|d}|dkrZ| jddd t fdd	tjD }|rftd
| 	 | S )zCalculates the inverse using the adjugate matrix and a determinant.

        See Also
        ========

        inv
        inverse_LU
        inverse_GE
        z"A Matrix must be square to invert.rt   )rw   r   NT)r   c             3   s   | ]} ||f V  qd S )Nr4   )rF   rK   )rY   okr4   r5   r\   
  s    z)MatrixBase.inverse_ADJ.<locals>.<genexpr>z Matrix det == 0; not invertible.)
r   r.   rp   equalsr   r   r&   rN   r   rx   )r;   rY   rG   Zzeror4   )rY   r  r5   inverse_ADJ
  s    

zMatrixBase.inverse_ADJc                s   ddl m} | jstd||  || j}|j ddd t	 fddt
jD rjtd	| d
d
|jd
f S )zCalculates the inverse using Gaussian elimination.

        See Also
        ========

        inv
        inverse_LU
        inverse_ADJ
        r*   )r4  z"A Matrix must be square to invert.T)rY   r   r   c             3   s   | ]} ||f V  qd S )Nr4   )rF   rK   )rY   redr4   r5   r\     s    z(MatrixBase.inverse_GE.<locals>.<genexpr>z Matrix det == 0; not invertible.N)r5  r4  r   r.   r   
as_mutabler   rN   r   r   r&   r   rP   )r;   rY   r4  Zbigr4   )rY   r  r5   
inverse_GE   s    
zMatrixBase.inverse_GEc                sX   | j st | jddd t fddtjD rBtd| j| | jt	dS )zCalculates the inverse using LU decomposition.

        See Also
        ========

        inv
        inverse_GE
        inverse_ADJ
        T)r   r   c             3   s   | ]} ||f V  qd S )Nr4   )rF   rK   )rY   r  r4   r5   r\   #  s    z(MatrixBase.inverse_LU.<locals>.<genexpr>z Matrix det == 0; not invertible.)rY   )
r   r.   r   r   r&   rN   r   LUsolver   r6   )r;   rY   r4   )rY   r  r5   
inverse_LU  s    
zMatrixBase.inverse_LUc             K   s(   | j st |dk	r||d< | jf |S )a  
        Return the inverse of a matrix.

        CASE 1: If the matrix is a dense matrix.

        Return the matrix inverse using the method indicated (default
        is Gauss elimination).

        Parameters
        ==========

        method : ('GE', 'LU', or 'ADJ')

        Notes
        =====

        According to the ``method`` keyword, it calls the appropriate method:

          GE .... inverse_GE(); default
          LU .... inverse_LU()
          ADJ ... inverse_ADJ()

        See Also
        ========

        inverse_LU
        inverse_GE
        inverse_ADJ

        Raises
        ------
        ValueError
            If the determinant of the matrix is zero.

        CASE 2: If the matrix is a sparse matrix.

        Return the matrix inverse using Cholesky or LDL (default).

        kwargs
        ======

        method : ('CH', 'LDL')

        Notes
        =====

        According to the ``method`` keyword, it calls the appropriate method:

          LDL ... inverse_LDL(); default
          CH .... inverse_CH()

        Raises
        ------
        ValueError
            If the determinant of the matrix is zero.

        Nrw   )r   r.   Z_eval_inverse)r;   rw   r   r4   r4   r5   rb  (  s
    :zMatrixBase.invc             C   sF   | sdS | j stdtd| }| |}|jd || j krBd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 matricesr3   r   F)r   r.   r   rz   r  rN   )r;   r3   r   r4   r4   r5   is_nilpotenth  s    

zMatrixBase.is_nilpotentc       	      C   s   ddl m} dd |D \}}|rP| js2d }}qh|d | jdd \}}n||d | j}|d }|r| js|d }}q|d | jdd \}}n||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
        r   )r+   c             S   s   g | ]}t |tqS r4   )r   rq  )rF   rq   r4   r4   r5   rI     s    z)MatrixBase.key2bounds.<locals>.<listcomp>NrE   r*   )sympy.matrices.commonr+   rN   indicesrO   )	r;   r  a2idx_isliceZjsliceZrloZrhiZcloZchir4   r4   r5   
key2bounds  s    


zMatrixBase.key2boundsc                s|   ddl m  t|rBt|dks(td fddt|| jD S t|trb|	t| dd S 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   )r+   rE   z"key must be a sequence of length 2c                s(   g | ] \}}t |ts  ||n|qS r4   )r   rq  )rF   r<   r   )r  r4   r5   rI     s   z%MatrixBase.key2ij.<locals>.<listcomp>N)r  r+   r$   ri   r0  zipr/  r   rq  r  rs  rO   )r;   r   r4   )r  r5   rr    s    


zMatrixBase.key2ijc             C   s$   | j std| jstd|  S )a  Returns the LDL Decomposition (L, D) of matrix A,
        such that L * D * L.H == A
        This method eliminates the use of square root.
        Further this ensures that all the diagonal entries of L are 1.
        A must be a Hermitian positive-definite matrix.

        Examples
        ========

        >>> from sympy.matrices import Matrix, eye
        >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
        >>> L, D = A.LDLdecomposition()
        >>> L
        Matrix([
        [   1,   0, 0],
        [ 3/5,   1, 0],
        [-1/5, 1/3, 1]])
        >>> D
        Matrix([
        [25, 0, 0],
        [ 0, 9, 0],
        [ 0, 0, 9]])
        >>> L * D * L.T * A.inv() == eye(A.rows)
        True

        The matrix can have complex entries:

        >>> from sympy import I
        >>> A = Matrix(((9, 3*I), (-3*I, 5)))
        >>> L, D = A.LDLdecomposition()
        >>> L
        Matrix([
        [   1, 0],
        [-I/3, 1]])
        >>> D
        Matrix([
        [9, 0],
        [0, 4]])
        >>> L*D*L.H == A
        True

        See Also
        ========

        cholesky
        LUdecomposition
        QRdecomposition
        zMatrix must be square.zMatrix must be Hermitian.)r   r.   ru  r   Z_LDLdecomposition)r;   r4   r4   r5   LDLdecomposition  s
    1zMatrixBase.LDLdecompositionc             C   sf   | j r|  \}}n2| j| jkr>| j|   \}}| j| }ntd||}||}|j|S )a  Solves Ax = B using LDL decomposition,
        for a general square and non-singular matrix.

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

        Examples
        ========

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

        See Also
        ========

        LDLdecomposition
        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LUsolve
        QRsolve
        pinv_solve
        z6Under-determined System. Try M.gauss_jordan_solve(rhs))	ru  r  rN   rO   r  r   rw  r  rx  )r;   ry  rz  r  r{  Zr4   r4   r5   LDLsolve  s    

zMatrixBase.LDLsolvec             C   s:   | j std|j| jkr"td| js0td| |S )a  Solves Ax = B, where A is a lower triangular matrix.

        See Also
        ========

        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv_solve
        zMatrix must be square.zMatrices size mismatch.z Matrix must be lower triangular.)r   r.   rN   r-   r   r   rw  )r;   ry  r4   r4   r5   lower_triangular_solve  s    z!MatrixBase.lower_triangular_solvec       	         sZ   | j |||d\ } fdd} fdd}|  j j|}|  j j|}|||fS )a  Returns (L, U, perm) where L is a lower triangular matrix with unit
        diagonal, U is an upper triangular matrix, and perm is a list of row
        swap index pairs. If A is the original matrix, then
        A = (L*U).permuteBkwd(perm), and the row permutation matrix P such
        that P*A = L*U can be computed by P=eye(A.row).permuteFwd(perm).

        See documentation for LUCombined for details about the keyword argument
        rankcheck, iszerofunc, and simpfunc.

        Examples
        ========

        >>> from sympy import Matrix
        >>> a = Matrix([[4, 3], [6, 3]])
        >>> L, U, _ = a.LUdecomposition()
        >>> L
        Matrix([
        [  1, 0],
        [3/2, 1]])
        >>> U
        Matrix([
        [4,    3],
        [0, -3/2]])

        See Also
        ========

        cholesky
        LDLdecomposition
        QRdecomposition
        LUdecomposition_Simple
        LUdecompositionFF
        LUsolve
        )rY   rl   	rankcheckc                s8   | |k rt jS | |krt jS | jk r2 | |f S t jS )N)r   rJ   rQ   rO   )r<   rK   )combinedr4   r5   entry_Ld  s    
z+MatrixBase.LUdecomposition.<locals>.entry_Lc                s   | |krt jS  | |f S )N)r   rJ   )r<   rK   )r  r4   r5   entry_Up  s    z+MatrixBase.LUdecomposition.<locals>.entry_U)rm   rP   rN   rO   )	r;   rY   rl   r  r   r  r  rz  Ur4   )r  r5   LUdecomposition2  s    '	zMatrixBase.LUdecompositionc                s  |r| j dks| jdkr,| | j | jg fS |   g }dx>td j d D ](}d}xV| jkr|r fddt|| j D }t|||\}}	}
}|	dk}|r\d7 q\W |rƈ|krtd|dkrdn|| }|dkr|r |fS x |D ]\}}| || f< qW ||kr|||g  |d|f  |d|f   |d|f<  |d|f<  | jf  | jf   | jf<  | jf< d }x~t|d  j D ]j} |f  |f   ||f< xBt| jD ]2} ||f  ||f  ||f    ||f< qW qW |kr`x(t|d  j D ]}tj	 |f< qHW d7  jkrP |fS qPW  |fS )a"  Compute an lu decomposition of m x n matrix A, where P*A = L*U

        * L is m x m lower triangular with unit diagonal
        * U is m x n upper triangular
        * P is an m x m permutation matrix

        Returns an m x n matrix lu, and an m element list perm where each
        element of perm is a pair of row exchange indices.

        The factors L and U are stored in lu as follows:
        The subdiagonal elements of L are stored in the subdiagonal elements
        of lu, that is lu[i, j] = L[i, j] whenever i > j.
        The elements on the diagonal of L are all 1, and are not explicitly
        stored.
        U is stored in the upper triangular portion of lu, that is
        lu[i ,j] = U[i, j] whenever i <= j.
        The output matrix can be visualized as:

            Matrix([
                [u, u, u, u],
                [l, u, u, u],
                [l, l, u, u],
                [l, l, l, u]])

        where l represents a subdiagonal entry of the L factor, and u
        represents an entry from the upper triangular entry of the U
        factor.

        perm is a list row swap index pairs such that if A is the original
        matrix, then A = (L*U).permuteBkwd(perm), and the row permutation
        matrix P such that ``P*A = L*U`` can be computed by
        ``P=eye(A.row).permuteFwd(perm)``.

        The keyword argument rankcheck determines if this function raises a
        ValueError when passed a matrix whose rank is strictly less than
        min(num rows, num cols). The default behavior is to decompose a rank
        deficient matrix. Pass rankcheck=True to raise a
        ValueError instead. (This mimics the previous behavior of this function).

        The keyword arguments iszerofunc and simpfunc are used by the pivot
        search algorithm.
        iszerofunc is a callable that returns a boolean indicating if its
        input is zero, or None if it cannot make the determination.
        simpfunc is a callable that simplifies its input.
        The default is simpfunc=None, which indicate that the pivot search
        algorithm should not attempt to simplify any candidate pivots.
        If simpfunc fails to simplify its input, then it must return its input
        instead of a copy.

        When a matrix contains symbolic entries, the pivot search algorithm
        differs from the case where every entry can be categorized as zero or
        nonzero.
        The algorithm searches column by column through the submatrix whose
        top left entry coincides with the pivot position.
        If it exists, the pivot is the first entry in the current search
        column that iszerofunc guarantees is nonzero.
        If no such candidate exists, then each candidate pivot is simplified
        if simpfunc is not None.
        The search is repeated, with the difference that a candidate may be
        the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero.
        In the second search the pivot is the first candidate that
        iszerofunc can guarantee is nonzero.
        If no such candidate exists, then the pivot is the first candidate
        for which iszerofunc returns None.
        If no such candidate exists, then the search is repeated in the next
        column to the right.
        The pivot search algorithm differs from the one in `rref()`, which
        relies on ``_find_reasonable_pivot()``.
        Future versions of ``LUdecomposition_simple()`` may use
        ``_find_reasonable_pivot()``.

        See Also
        ========

        LUdecomposition
        LUdecompositionFF
        LUsolve
        r   r*   Tc             3   s   | ]} |f V  qd S )Nr4   )rF   r)rn   	pivot_colr4   r5   r\     s    z4MatrixBase.LUdecomposition_Simple.<locals>.<genexpr>NzRank of matrix is strictly less than number of rows or columns. Pass keyword argument rankcheck=False to compute the LU decomposition of this matrix.)
rN   rO   r   r  r&   _find_reasonable_pivot_naiver   rR   r   rJ   )r;   rY   rl   r  ro   Z	pivot_rowZiszeropivotZsub_colZpivot_row_offsetZpivot_valueZis_assumed_non_zeroZind_simplified_pairsZcandidate_pivot_rowr   r   Z	start_colr   r  r4   )rn   r  r5   rm   y  sJ    S
:B 8

z!MatrixBase.LUdecomposition_Simplec             C   s(  ddl m} |j}|j}| j| j }}|  ||||  }}}|||}	d}
xt|d D ]}|||f dkrTx,t|d |D ]}|||f rP qW td|||df |||df  |||df< |||df< ||d|f ||d|f  ||d|f< ||d|f< ||ddf ||ddf  ||ddf< ||ddf< |||f  |||f< }|
| |	||f< xt|d |D ]p}|||f  |||f< }xDt|d |D ]2}||||f  |||f |  |
 |||f< qW d|||f< qW |}
q`W |
|	|d |d f< |||	|fS )aN  Compute a fraction-free LU decomposition.

        Returns 4 matrices P, L, D, U such that PA = L D**-1 U.
        If the elements of the matrix belong to some integral domain I, then all
        elements of L, D and U are guaranteed to belong to I.

        **Reference**
            - W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms
              for LU and QR factors". Frontiers in Computer Science in China,
              Vol 2, no. 1, pp. 67-80, 2008.

        See Also
        ========

        LUdecomposition
        LUdecomposition_Simple
        LUsolve
        r   )rk  r*   zMatrix is not full rankN)	r   rk  r   r   rN   rO   r  r&   r   )r;   rk  r   r   r   r   r  rz  rG  ZDDZoldpivotrq   ZkpivotZUkkr<   ZUikrK   r4   r4   r5   LUdecompositionFF>  s4    
:::2zMatrixBase.LUdecompositionFFc       	   	      s   |j | j krtd| jtd\}}| j }|| }xDt|D ]8}x2t|D ]&}|||f  ||| fdd qPW qBW xrt|d ddD ]^}x8t|d |D ]&}|||f  ||| fdd qW |||f  || fdd qW |	|S )	a  Solve the linear system Ax = rhs for x where A = self.

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

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        QRsolve
        pinv_solve
        LUdecomposition
        z3`self` and `rhs` must have the same number of rows.)rY   c                s   | |   S )Nr4   )r3   y)scaler4   r5   r}     s    z$MatrixBase.LUsolve.<locals>.<lambda>r*   rZ   c                s   | |   S )Nr4   )r3   r  )r  r4   r5   r}     s    c                s   |   S )Nr4   )r3   re   )r  r4   r5   r}     s    )
rN   r-   rm   r6   rM  r  r&   Z
zip_row_opZrow_oprX  )	r;   ry  rY   rU   r   r   r   r<   rK   r4   )r  r5   r  o  s"    zMatrixBase.LUsolvec             C   s   | | S )zrReturns self*b

        See Also
        ========

        dot
        cross
        multiply_elementwise
        r4   )r;   r   r4   r4   r5   multiply  s    
zMatrixBase.multiplyc                s:   | j dkr| jdkrtd|   |  fdd}|S )zdReturn the normalized version of ``self``.

        See Also
        ========

        norm
        r*   z'A Matrix must be a vector to normalize.c                s   |   S )Nr4   )r<   )r   r4   r5   r}     s    z'MatrixBase.normalized.<locals>.<lambda>)rN   rO   r-   r   r   )r;   outr4   )r   r5   
normalized  s
    zMatrixBase.normalizedc          	      s  t |  pdg}| jdks&| jdkrdks6dkrLttdd |D  S dkrftdd |D  S tjkrtdd	 |D  S tj	krt
d
d	 |D  S y$ttfdd|D  td 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rBt
|   S tjkrt| 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*   rE   Nc             s   s   | ]}t |d  V  qdS )rE   N)abs)rF   r<   r4   r4   r5   r\     s    z"MatrixBase.norm.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)r  )rF   r<   r4   r4   r5   r\     s    c             S   s   g | ]}t |qS r4   )r  )rF   r<   r4   r4   r5   rI     s    z#MatrixBase.norm.<locals>.<listcomp>c             S   s   g | ]}t |qS r4   )r  )rF   r<   r4   r4   r5   rI     s    c             3   s   | ]}t |  V  qd S )N)r  )rF   r<   )ordr4   r5   r\     s    z'Expected order to be Number, Symbol, ooc                s   g | ]}t  |qS r4   )r   r   )rF   r<   )r   r4   r5   rI     s    r  c                s   g | ]}t  |qS r4   )r   r   )rF   r<   )r   r4   r5   rI   
  s    )fZfroZ	frobeniusZvector)r  zMatrix Norms under development)rc   r   rN   rO   r   r   r   ZInfinityr   ZNegativeInfinityr   r	   r   r0  r   r   r  r&   r   r   r    r   r   r   )r;   r  r  r4   )r   r  r5   r     s:    4

$




zMatrixBase.normc       	      C   sp   ddl m} | }|  }|dkrR|j|j }}td||td}| |||j}|| ||j||  |  S )a;
  Solve Ax = B using the Moore-Penrose pseudoinverse.

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

        Parameters
        ==========

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

        Returns
        =======

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

        Examples
        ========

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

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv

        Notes
        =====

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

        References
        ==========

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

        r   )r   Nz
w:{0}_:{1})r   )	r   r   pinvrO   r   r   r   rX  r7  )	r;   r@  Zarbitrary_matrixr   rU   ZA_pinvrN   rO   wr4   r4   r5   
pinv_solve  s    MzMatrixBase.pinv_solvec             C   sf   | }| j }|jr|S y0| j| jkr2||  | S |||   S W n tk
r`   tdY nX dS )at  Calculate the Moore-Penrose pseudoinverse of the matrix.

        The Moore-Penrose pseudoinverse exists and is unique for any matrix.
        If the matrix is invertible, the pseudoinverse is the same as the
        inverse.

        Examples
        ========

        >>> from sympy import Matrix
        >>> Matrix([[1, 2, 3], [4, 5, 6]]).pinv()
        Matrix([
        [-17/18,  4/9],
        [  -1/9,  1/9],
        [ 13/18, -2/9]])

        See Also
        ========

        inv
        pinv_solve

        References
        ==========

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

        z.Rank-deficient matrices are not yet supported.N)r  r1   rN   rO   rb  r   r   )r;   rU   ZAHr4   r4   r5   r  k  s    zMatrixBase.pinvr-  c             C   s   g }xht | jD ]Z}g }x<t | jD ].}| ||f dkrD|d q$|t| q$W |dd|  qW td| dS )a  Shows location of non-zero entries for fast shape lookup.

        Examples
        ========

        >>> from sympy.matrices 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]r[  
N)r&   rN   rO   rR   rd  joinprint)r;   Zsymbr'  r<   linerK   r4   r4   r5   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   )r;   r   r4   r4   r5   r     s    zMatrixBase.projectc          	   C   s  | j }|  }|j|jks"td|j}|j}|}| d }x,t|jD ]}|| dkrJ|d8 }qJW ||jks~td|	|||	| }}	x t|D ]}
|dd|
f }xNt|
D ]B}||dd|f |dd|
f 
|dd|f  8 }|  qW | |	|
|
f< ||	|
|
f  |dd|
f< |dd|
f  dkrXtd|
 x<t|
D ]0}|dd|f 
|dd|
f |	||
f< qbW qW ||||	fS )a  Return Q, R where A = Q*R, Q is orthogonal and R is upper triangular.

        Examples
        ========

        This is the example from wikipedia:

        >>> from sympy import Matrix
        >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]])
        >>> Q, R = A.QRdecomposition()
        >>> Q
        Matrix([
        [ 6/7, -69/175, -58/175],
        [ 3/7, 158/175,   6/175],
        [-2/7,    6/35,  -33/35]])
        >>> R
        Matrix([
        [14,  21, -14],
        [ 0, 175, -70],
        [ 0,   0,  35]])
        >>> A == Q*R
        True

        QR factorization of an identity matrix:

        >>> A = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
        >>> Q, R = A.QRdecomposition()
        >>> Q
        Matrix([
        [1, 0, 0],
        [0, 1, 0],
        [0, 0, 1]])
        >>> R
        Matrix([
        [1, 0, 0],
        [0, 1, 0],
        [0, 0, 1]])

        See Also
        ========

        cholesky
        LDLdecomposition
        LUdecomposition
        QRsolve
        z/The number of rows must be greater than columnsr   r*   z-The rank of the matrix must match the columnsNz"Could not normalize the vector %d.)rX  r  rN   rO   r,   r   r&   r   r   r   r   expandr   )r;   r   r_   r   r   r   Zrow_reducedr<   QrH   rK   tmpr4   r4   r5   QRdecomposition  s8    /
6
4zMatrixBase.QRdecompositionc       
      C   s   |    \}}|j| }g }|j}xvt|d ddD ]b}||ddf }x6t|d |D ]$}	||||	f ||d |	   8 }qZW |||||f   q6W | dd t|D S )a  Solve the linear system 'Ax = b'.

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

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

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

        See Also
        ========

        lower_triangular_solve
        upper_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        LUsolve
        pinv_solve
        QRdecomposition
        r*   rZ   Nc             S   s   g | ]
}|j qS r4   )r  )rF   r   r4   r4   r5   rI   C  s    z&MatrixBase.QRsolve.<locals>.<listcomp>)r  r  r7  rN   r&   rR   rP   r  )
r;   r   r  rH   r  r3   r   rK   r  rq   r4   r4   r5   QRsolve  s    
$zMatrixBase.QRsolveCHc             C   s0   |dkr|  |S | j}||  j|d| | S )a  Return the least-square fit to the data.

        By default the cholesky_solve routine is used (method='CH'); other
        methods of matrix inversion can be used. To find out which are
        available, see the docstring of the .inv() method.

        Examples
        ========

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

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

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

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

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

        The error is given by S*xy - r:

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

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

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

        r  )rw   )r|  r  rb  )r;   ry  rw   r   r4   r4   r5   solve_least_squaresE  s    6
zMatrixBase.solve_least_squaresGEc             C   sF   | j s2| j| jk rtdqB| j| jkrBtdn| j|d| S dS )zReturn solution to self*soln = rhs using given inversion method.

        For a list of possible inversion methods, see the .inv() docstring.
        z6Under-determined system. Try M.gauss_jordan_solve(rhs)z]For over-determined system, M, having more rows than columns, try M.solve_least_squares(rhs).)rw   N)r   rN   rO   r   rb  )r;   ry  rw   r4   r4   r5   solve  s    

zMatrixBase.solve[]r  , rightc             C   s  | j dks| jdkrdS g }dg| j }xft| j D ]X}	|g  xHt| jD ]:}
|| |	|
f }|d | tt|||
 ||
< qNW q4W ddddddd| }xVt|D ]J\}	}x*t|D ]\}
}t||||
 ||
< qW ||	| | ||	< qW |	|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
        >>> from sympy.printing.str import 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}
        r   z[]rZ   ljustrjustcenter)leftr  r  <>^)
rN   rO   r&   rR   Z_printr  ri   r   rT  r  )r;   ri  ZrowstartZrowendrg  ZcolsepZalignr  maxlenr<   rK   r'  r   elemr4   r4   r5   rh    s,    3
zMatrixBase.tablec             C   s:   | j std|j| jkr"td| js0td| |S )a  Solves Ax = B, where A is an upper triangular matrix.

        See Also
        ========

        lower_triangular_solve
        gauss_jordan_solve
        cholesky_solve
        diagonal_solve
        LDLsolve
        LUsolve
        QRsolve
        pinv_solve
        zMatrix must be square.zMatrix size mismatch.zMatrix is not upper triangular.)r   r.   rN   r0  r   rx  )r;   ry  r4   r4   r5   upper_triangular_solve  s    z!MatrixBase.upper_triangular_solvec       	      C   s   ddl m} | j}|| jkr$td|rD|   | |  krDtdd}|r|||d  d d}xt|D ]0}x*t||D ]}| ||f ||< |d7 }q|W qlW nX|||d  d d}x@t|D ]4}x.t|d |D ]}| ||f ||< |d7 }qW qW |S )a  Return the unique elements of a symmetric Matrix as a one column matrix
        by stacking the elements in the lower triangle.

        Arguments:
        diagonal -- include the diagonal cells of self or not
        check_symmetry -- checks symmetry of self but not completely reliably

        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]])

        See Also
        ========

        vec
        r   )r   zMatrix must be squarez>Matrix appears to be asymmetric; consider check_symmetry=Falser*   rE   )	r   r   rO   rN   r-   r   rv   r   r&   )	r;   ZdiagonalZcheck_symmetryr   r  countr   rK   r<   r4   r4   r5   vech  s,    
zMatrixBase.vech)N)F)N)N)N)r-  )r  )r  )r  r  r  r  r  )TT)Dr@   rA   rB   rC   Z__array_priority__rm  Z_class_prioritystaticmethodr   rl  __hash__objectrS  rY  rZ  r\  r^  rc  r?   r>   re  rj  r   rp  rt  ro  r|  r}  r~  r  r  r   r  r  r   r  r   r  r  r6   r  r  r  rb  r  r  rr  r  r  r  r  rm   r  r  r  r  r   r  r  r  r   r  r  r  r  rh  r  r  r4   r4   r4   r5   r.    s   

 F1 +:'+
 ,
@7)E C1(
d
V,
"O-
;
 
Mr.  i;  z)from sympy.matrices.common import classofz1.3)r  r  r  c             C   s   ddl m} || |S )Nr   )classof)r  r  )rU   r@  Zclassof_r4   r4   r5   r  ,  s    r  z'from sympy.matrices.common import a2idx)r  r  r  Nc             C   s   ddl m} || |S )Nr   )r+   )r  r+   )rK   r   r  r4   r4   r5   r+   4  s    r+   c             C   s  g }t | } tdd | D rtdd | D rdd | D }t|}||rt|dkrhdd t| D }ddd	|fS ||}|| | d	|fS g }x:t| D ].\}}	||	}
|
d	kr||	d	|fS ||
 qW t|rddd	|fS xtt| D ]h\}}	|| dk	rq||	}||}
|
d
ks(|
d	kr6|||f |
d	krL||d	|fS |
||< qW t|rnddd	|fS xNt| D ]B\}}	|| dk	rqx|	tj	rxd
||< ||tj	f qxW t|rddd	|fS |d}|| | d
|fS )a   Find the lowest index of an item in `col` that is
    suitable for a pivot.  If `col` consists only of
    Floats, the pivot with the largest norm is returned.
    Otherwise, the first element where `iszerofunc` returns
    False is used.  If `iszerofunc` doesn't return false,
    items are simplified and retested until a suitable
    pivot is found.

    Returns a 4-tuple
        (pivot_offset, pivot_val, assumed_nonzero, newly_determined)
    where pivot_offset is the index of the pivot, pivot_val is
    the (possibly simplified) value of the pivot, assumed_nonzero
    is True if an assumption that the pivot was non-zero
    was made without being proved, and newly_determined are
    elements that were simplified during the process of pivot
    finding.c             s   s   | ]}t |ttfV  qd S )N)r   r   r   )rF   r3   r4   r4   r5   r\   T  s    z)_find_reasonable_pivot.<locals>.<genexpr>c             s   s   | ]}t |tV  qd S )N)r   r   )rF   r3   r4   r4   r5   r\   U  s    c             S   s   g | ]}t |qS r4   )r  )rF   r3   r4   r4   r5   rI   V  s    z*_find_reasonable_pivot.<locals>.<listcomp>r   c             S   s    g | ]\}}|d kr|d fqS )r   r4   )rF   r<   r3   r4   r4   r5   rI   ]  s    NFT)
rc   r   r   r  r   indexrR   r  r   rJ   )r   rY   rl   r   Zcol_absZ	max_valuer  Zpossible_zerosr<   r3   r1   Zsimpedr4   r4   r5   rb   =  sT    




rb   c       	      C   s   g }xFt | D ]:\}}||}|dkr2||dg fS |dkr|||f qW t|dkrddddg fS |dkr|d d |d d dg fS g }xN|D ]F\}}||}t|t|kr|||f ||dkr||d|fS qW |d d |d d d|fS )a  
    Helper that computes the pivot value and location from a
    sequence of contiguous matrix column elements. As a side effect
    of the pivot search, this function may simplify some of the elements
    of the input column. A list of these simplified entries and their
    indices are also returned.
    This function mimics the behavior of _find_reasonable_pivot(),
    but does less work trying to determine if an indeterminate candidate
    pivot simplifies to zero. This more naive approach can be much faster,
    with the trade-off that it may erroneously return a pivot that is zero.

    `col` is a sequence of contiguous column entries to be searched for
    a suitable pivot.
    `iszerofunc` is a callable that returns a Boolean that indicates
    if its input is zero, or None if no such determination can be made.
    `simpfunc` is a callable that simplifies its input. It must return
    its input if it does not simplify its input. Passing in
    `simpfunc=None` indicates that the pivot search should not attempt
    to simplify any candidate pivots.

    Returns a 4-tuple:
    (pivot_offset, pivot_val, assumed_nonzero, newly_determined)
    `pivot_offset` is the sequence index of the pivot.
    `pivot_val` is the value of the pivot.
    pivot_val and col[pivot_index] are equivalent, but will be different
    when col[pivot_index] was simplified during the pivot search.
    `assumed_nonzero` is a boolean indicating if the pivot cannot be
    guaranteed to be zero. If assumed_nonzero is true, then the pivot
    may or may not be non-zero. If assumed_nonzero is false, then
    the pivot is non-zero.
    `newly_determined` is a list of index-value pairs of pivot candidates
    that were simplified during the pivot search.
    FNr   r*   T)r   rR   ri   id)	r   rY   rl   Zindeterminatesr<   Zcol_valZcol_val_is_zeror   Ztmp_col_valr4   r4   r5   r    s&    +r  )N)RZ
__future__r   r   Zmpmath.libmp.libmpfr   Zsympy.core.addr   Zsympy.core.basicr   Zsympy.core.exprr   Zsympy.core.functionr   Zsympy.core.powerr	   Zsympy.core.symbolr
   r   r   r   Zsympy.core.numbersr   r   r   Zsympy.core.singletonr   Zsympy.core.sympifyr   Z(sympy.functions.elementary.miscellaneousr   r   r   Zsympy.functionsr   r   Zsympy.polysr   r   r   Zsympy.printingr   Zsympy.simplifyr   r   r   Zsympy.core.compatibilityr   r   r    r!   Zsympy.utilities.iterablesr"   r#   r$   r%   r&   r'   Zsympy.utilities.exceptionsr(   typesr)   commonr+   r,   r-   r.   r/   Zsympy.core.decoratorsr0   r6   r7   r8   rD   r   r   r   r!  r3  r.  r  rb   r  r4   r4   r4   r5   <module>   s         (    =  8                 1g