U
    9%ej                     @   sF  d dl mZ d dlmZ d dlmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZ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mZ d dlmZ d dlm Z m!Z! d dl"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ dd Z,dVddZ-dd Z.dWddddddZ/dZ0dXdd Z1dYd!d"Z2e*dfd#d$Z3d%d& Z4dZd'd(Z5de*fdd)d*d+Z6d[d,d-Z7d\d.d/Z8d0d1 Z9d2d3 Z:d4d5 Z;d]d6d7Z<d^d8d9Z=d_d:d;Z>d<d= Z?d>d? Z@d@dA ZAdBdC ZBdDdE ZCdFdG ZDdHdI ZEdJdK ZFdLdM ZGdNZHeHeA_IeHeB_IeHeC_IeHeD_IeHeE_Id`dd)dOdPZJdQdR ZKdSdT ZLdUS )a    )FunctionType)Counter)mpworkprec)prec_to_dpsdefault_sort_key)DEFAULT_MAXPRECPrecisionExhausted)	fuzzy_andfuzzy_or)Float_sympify)sqrt)rootsCRootOfZZQQEX)DomainMatrix)dom_eigenvectsdom_eigenvects_to_sympy)gcd   )MatrixErrorNonSquareMatrixError)_find_reasonable_pivot)_iszero	_simplifyc           	   
   C   s   dd }d }t dd | tD }d|  }|tk rt|n t| jt|d}t	|\}}|dd |D }|d k	rt
|| |k r||fW  5 Q R  S |}W 5 Q R X |d9 }q.td S )Nc                 S   s   t tdd | D S )Nc                 s   s   | ]}|d  V  qdS )   N .0ir!   r!   S/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/sympy/matrices/eigen.py	<genexpr>   s     zA_eigenvals_eigenvects_mpmath.<locals>.<lambda>.<locals>.<genexpr>)r   r   sum)vr!   r!   r%   <lambda>       z._eigenvals_eigenvects_mpmath.<locals>.<lambda>c                 S   s   g | ]
}|j qS r!   )_precr#   xr!   r!   r%   
<listcomp>   s     z0_eigenvals_eigenvects_mpmath.<locals>.<listcomp>r    )nc                 S   s*   g | ]"}t |t |fD ]}|qqS r!   )r   reZim)r#   er$   r!   r!   r%   r.   #   s       )maxZatomsr   r	   r   r   matrixevalfr   eigfabsr
   )	MZnorm2Zv1precZepsAEERZv2r!   r!   r%   _eigenvals_eigenvects_mpmath   s    


r<   Fc                 C   s.   t | \}}dd |D }|r"|S tt|S )z Compute eigenvalues using mpmathc                 S   s   g | ]}t |qS r!   r   r,   r!   r!   r%   r.   5   s     z%_eigenvals_mpmath.<locals>.<listcomp>)r<   dictr   )r7   multipler:   _resultr!   r!   r%   _eigenvals_mpmath2   s
    rA   c                 C   sV   t | \}}g }t| jD ]6}t|| }t|d d |f }||d|gf q|S )Nr   )r<   rangerowsr   append)r7   r:   r;   r@   r$   eigenvalZ	eigenvectr!   r!   r%   _eigenvects_mpmath;   s    rF   T)simplifyr>   rationalc                   s   | s|rg S i S | j s$td| | jjttfkr\tdd | D r\| t	r\t
| |dS |r~ddlm  |  fdd} |rt| f||d	|S t| f||d	|S )
a  Compute eigenvalues of the matrix.

    Parameters
    ==========

    error_when_incomplete : bool, optional
        If it is set to ``True``, it will raise an error if not all
        eigenvalues are computed. This is caused by ``roots`` not returning
        a full list of eigenvalues.

    simplify : bool or function, optional
        If it is set to ``True``, it attempts to return the most
        simplified form of expressions returned by applying default
        simplification method in every routine.

        If it is set to ``False``, it will skip simplification in this
        particular routine to save computation resources.

        If a function is passed to, it will attempt to apply
        the particular function as simplification method.

    rational : bool, optional
        If it is set to ``True``, every floating point numbers would be
        replaced with rationals before computation. It can solve some
        issues of ``roots`` routine not working well with floats.

    multiple : bool, optional
        If it is set to ``True``, the result will be in the form of a
        list.

        If it is set to ``False``, the result will be in the form of a
        dictionary.

    Returns
    =======

    eigs : list or dict
        Eigenvalues of a matrix. The return format would be specified by
        the key ``multiple``.

    Raises
    ======

    MatrixError
        If not enough roots had got computed.

    NonSquareMatrixError
        If attempted to compute eigenvalues from a non-square matrix.

    Examples
    ========

    >>> from sympy import Matrix
    >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1])
    >>> M.eigenvals()
    {-1: 1, 0: 1, 2: 1}

    See Also
    ========

    MatrixDeterminant.charpoly
    eigenvects

    Notes
    =====

    Eigenvalues of a matrix $A$ can be computed by solving a matrix
    equation $\det(A - \lambda I) = 0$

    It's not always possible to return radical solutions for
    eigenvalues for matrices larger than $4, 4$ shape due to
    Abel-Ruffini theorem.

    If there is no radical solution is found for the eigenvalue,
    it may return eigenvalues in the form of
    :class:`sympy.polys.rootoftools.ComplexRootOf`.
    z{} must be a square matrix.c                 s   s   | ]}|j V  qd S NZ	is_numberr,   r!   r!   r%   r&      s     z_eigenvals.<locals>.<genexpr>)r>   r   	nsimplifyc                    s   |  tr | ddS | S NT)rH   )hasr   r-   rK   r!   r%   r)      r*   z_eigenvals.<locals>.<lambda>)error_when_incompleterG   )	is_squarer   format_repdomainr   r   allrN   r   rA   sympy.simplifyrL   	applyfunc_eigenvals_list_eigenvals_dict)r7   rP   rG   r>   rH   flagsr!   rK   r%   
_eigenvalsG   s>    P
  r[   ad  It is not always possible to express the eigenvalues of a matrix of size 5x5 or higher in radicals. We have CRootOf, but domains other than the rationals are not currently supported. If there are no symbols in the matrix, it should still be possible to compute numeric approximations of the eigenvalues using M.evalf().eigenvals() or M.charpoly().nroots().c              	      s:  |   }g }| jjttfk}|D ]}|rTt|dkrT|d }| ||f }	||	 q | ||f }
ttrx|
j	d}n|
	 }t
|fddi|}t||
jkrt| }|  |jz fddt|D }W n( tk
r   |rttng }Y nX ||7 }q s|S tts(tfdd|D S )	Nr   r   rG   r>   Tc                    s   g | ]}t  |qS r!   r   r#   idxfr-   r!   r%   r.      s     z#_eigenvals_list.<locals>.<listcomp>c                    s   g | ]} |qS r!   r!   )r#   valuer\   r!   r%   r.      s     )strongly_connected_componentsrS   rT   r   r   lenrD   
isinstancer   charpolyr   rC   intdegreeas_exprgenrB   NotImplementedErrorr   eigenvals_error_messager   )r7   rP   rG   rZ   iblocksall_eigsis_dombindexvalblockrf   eigsrh   r!   ra   rG   r-   r%   rX      s<    




rX   c              	      s  |   }i }| jjttfk}|D ],}|r`t|dkr`|d }| ||f }	||	dd ||	< q | ||f }
ttr|
j	d}n|
	 }t
|fddi|}t| |
jkrt| }|  |jz fddt|D }W n* tk
r   |rttni }Y nX | D ].\}}||krB||  |7  < n|||< qq sZ|S ttsjtfdd| D S )	Nr   r   r\   r>   Fc                    s   i | ]}t  |d qS r   r]   r^   r`   r!   r%   
<dictcomp>  s     
 z#_eigenvals_dict.<locals>.<dictcomp>c                    s   i | ]\}} ||qS r!   r!   )r#   keyrb   r\   r!   r%   rw     s      )rc   rS   rT   r   r   rd   getre   r   rf   r   r'   valuesrC   rg   rh   ri   rj   rB   rk   r   rl   itemsr   )r7   rP   rG   rZ   rm   rn   ro   rp   rq   rr   rs   rf   rt   rh   kr(   r!   ru   r%   rY      sB    




rY   c                 C   s\   | |  | j|  }|j|d}t|dkr>|r>|j|dd}t|dkrXtd||S )z:Get a basis for the eigenspace for a particular eigenvalue)
iszerofuncr   Tr}   rG   z,Can't evaluate eigenvector for eigenvalue {})eyerC   	nullspacerd   rk   rR   )r7   rE   r}   rG   mretr!   r!   r%   _eigenspace  s    r   c                 K   sX   t j| ddd}| }|jtkrTt|\}}t||| jf|}t|dd d}|S d S )NT)field	extensionc                 S   s   t | d S )Nr   r   rO   r!   r!   r%   r)   0  r*   z!_eigenvects_DOM.<locals>.<lambda>rx   )	r   Zfrom_MatrixZto_denserT   r   r   r   	__class__sorted)r7   kwargsZDOMrH   Z	algebraic
eigenvectsr!   r!   r%   _eigenvects_DOM(  s    
  r   c           
      K   sv   | j f ddi|}|D ]}|trtdqt| td}g }|D ](\}}t| |||d}	||||	f qH|S )NrH   FzYEigenvector computation is not implemented if the matrix have eigenvalues in CRootOf formr   r~   )		eigenvalsrN   r   r   r   r{   r   r   rD   )
r7   r}   rG   rZ   r   r-   r   rr   multZvectsr!   r!   r%   _eigenvects_sympy6  s    
r   chopc          	         s   | dd}| dd}|dd |dd t|tsJ|rBtndd | t}|rtdd	 | D rrt| S d
dl	m
 | fdd} t| }|dkrt| |fd|i|}|r؇fddfdd|D }|r fdd|D }|S )a  Compute eigenvectors of the matrix.

    Parameters
    ==========

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

    iszerofunc : function, optional
        Specifies a zero testing function to be used in ``rref``.

        Default value is ``_iszero``, which uses SymPy's naive and fast
        default assumption handler.

        It can also accept any user-specified zero testing function, if it
        is formatted as a function which accepts a single symbolic argument
        and returns ``True`` if it is tested as zero and ``False`` if it
        is tested as non-zero, and ``None`` if it is undecidable.

    simplify : bool or function, optional
        If ``True``, ``as_content_primitive()`` will be used to tidy up
        normalization artifacts.

        It will also be used by the ``nullspace`` routine.

    chop : bool or positive number, optional
        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. The ``chop`` flag is passed to ``evalf``.
        When ``chop=True`` a default precision will be used; a number will
        be interpreted as the desired level of precision.

    Returns
    =======

    ret : [(eigenval, multiplicity, eigenspace), ...]
        A ragged list containing tuples of data obtained by ``eigenvals``
        and ``nullspace``.

        ``eigenspace`` is a list containing the ``eigenvector`` for each
        eigenvalue.

        ``eigenvector`` is a vector in the form of a ``Matrix``. e.g.
        a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``.

    Raises
    ======

    NotImplementedError
        If failed to compute nullspace.

    Examples
    ========

    >>> from sympy import Matrix
    >>> M = Matrix(3, 3, [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]])])]

    See Also
    ========

    eigenvals
    MatrixSubspaces.nullspace
    rG   TFNr>   c                 S   s   | S rI   r!   rO   r!   r!   r%   r)     r*   z_eigenvects.<locals>.<lambda>c                 s   s   | ]}|j V  qd S rI   rJ   r,   r!   r!   r%   r&     s     z_eigenvects.<locals>.<genexpr>r   rK   c                    s    | ddS rM   r!   rO   rK   r!   r%   r)     r*   c                    s    fdd| D S )Nc                    s"   g | ]}|t t|  qS r!   )r   listrW   r#   r(   simpfuncr!   r%   r.     s     z4_eigenvects.<locals>.denom_clean.<locals>.<listcomp>r!   )lr   r!   r%   denom_clean  s    z _eigenvects.<locals>.denom_cleanc                    s    g | ]\}}}|| |fqS r!   r!   r#   rr   r   es)r   r!   r%   r.     s     z_eigenvects.<locals>.<listcomp>c                    s2   g | ]*\}}}|j  d | fdd|D fqS )r   c                    s   g | ]}|j  d qS )r   r4   r   r   r!   r%   r.     s     z*_eigenvects.<locals>.<listcomp>.<listcomp>r   r   r   r!   r%   r.     s   )ry   popre   r   r   rN   r   rU   rF   rV   rL   rW   r   r   )	r7   rP   r}   r   rZ   rG   Z	primitive
has_floatsr   r!   )r   r   rL   r   r%   _eigenvectsI  s.    L


r   c                 C   s`   | j sdg fS | jdd}|D ]8\}}}|r>|js>d|f  S |t|krd|f  S qd|fS )zSee _is_diagonalizable. This function returns the bool along with the
    eigenvectors to avoid calculating them again in functions like
    ``diagonalize``.FTr\   )rQ   r   is_realrd   )r7   
reals_only	eigenvecsrr   r   basisr!   r!   r%   _is_diagonalizable_with_eigen  s    
r   c                 K   sT   | j s
dS tdd | D r(|  r(dS tdd | D rD| jrDdS t| |dd S )a  Returns ``True`` if a matrix is diagonalizable.

    Parameters
    ==========

    reals_only : bool, optional
        If ``True``, it tests whether the matrix can be diagonalized
        to contain only real numbers on the diagonal.


        If ``False``, it tests whether the matrix can be diagonalized
        at all, even with numbers that may not be real.

    Examples
    ========

    Example of a diagonalizable matrix:

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

    Example of a non-diagonalizable matrix:

    >>> M = Matrix([[0, 1], [0, 0]])
    >>> M.is_diagonalizable()
    False

    Example of a matrix that is diagonalized in terms of non-real entries:

    >>> M = Matrix([[0, 1], [-1, 0]])
    >>> M.is_diagonalizable(reals_only=False)
    True
    >>> M.is_diagonalizable(reals_only=True)
    False

    See Also
    ========

    is_diagonal
    diagonalize
    Fc                 s   s   | ]}|j V  qd S rI   )r   r#   r1   r!   r!   r%   r&     s     z%_is_diagonalizable.<locals>.<genexpr>Tc                 s   s   | ]}|j V  qd S rI   )Z
is_complexr   r!   r!   r%   r&     s     r   r   )rQ   rU   Zis_symmetricis_hermitianr   )r7   r   r   r!   r!   r%   _is_diagonalizable  s    ,r   c                 C   s   | j dkstd|  }|  }|  }| d t| d  }|  }| d ||  |d< | d ||  |d< | dd df  dkrd}d|d< n6| | kr|}n|}||d  }d| d  }||fS )Nr   zInput must be a column matrix)r   r   r   r    )cols
ValueErrorcopyabsnorm)r-   r(   Zv_plusZv_minusqZnorm_xbetr!   r!   r%   _householder_vector  s$    

r   c                 C   sx  | j }| j}|  }|||| }}tt||D ]2}t||d |f \}}||| || |j  }	|	||d |d f  ||d |d f< ||}
|	|
|d |d f< ||
 }|d |d kr8t|||d d f j\}}||| d || |j  }	||d |d d f |	 ||d |d d f< ||}
|	|
|d d |d d f< |
| }q8|||fS Nr   r    )	rC   r   
as_mutabler   rB   minr   HT)r7   r   r/   r9   UVr$   r(   r   hh_mattempr!   r!   r%   _bidiagonal_decmp_hholder  s&    (
 0

r   c                 C   s  | j }| j}|  }tt||D ]}t||d |f \}}||| || |j  }|||d |d f  ||d |d f< |d |d kr"t|||d d f j\}}||| d || |j  }||d |d d f | ||d |d d f< q"|S r   )	rC   r   r   rB   r   r   r   r   r   )r7   r   r/   r9   r$   r(   r   r   r!   r!   r%   _eval_bidiag_hholder1  s    ( 2r   c                 C   sD   t |tstd|rt| S t| j}|d j|d j|d jfS )a/  
    Returns $(U,B,V.H)$ for

    $$A = UBV^{H}$$

    where $A$ is the input matrix, and $B$ is its Bidiagonalized form

    Note: Bidiagonal Computation can hang for symbolic matrices.

    Parameters
    ==========

    upper : bool. Whether to do upper bidiagnalization or lower.
                True for upper and False for lower.

    References
    ==========

    .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
    .. [2] Complex Matrix Bidiagonalization, https://github.com/vslobody/Householder-Bidiagonalization

    upper must be a booleanr    r   r   )re   boolr   r   r   )r7   upperXr!   r!   r%   _bidiagonal_decomposition@  s    

r   c                 C   s*   t |tstd|rt| S t| jjS )a  
    Returns $B$, the Bidiagonalized form of the input matrix.

    Note: Bidiagonal Computation can hang for symbolic matrices.

    Parameters
    ==========

    upper : bool. Whether to do upper bidiagnalization or lower.
                True for upper and False for lower.

    References
    ==========

    .. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
    .. [2] Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization

    r   )re   r   r   r   r   )r7   r   r!   r!   r%   _bidiagonalizeb  s
    
r   c                 C   s   | j st t| |d\}}|s(td|r8t|td}g g  }}|D ] \}}	}
||g|	 7 }||
7 }qF|rzd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
    r   zMatrix is not diagonalizabler   c                 S   s   g | ]}||   qS r!   )r   r   r!   r!   r%   r.     s     z _diagonalize.<locals>.<listcomp>)rQ   r   r   r   r   r   hstackdiag)r7   r   sort	normalizeZis_diagonalizabler   Zp_colsr   rr   r   r   r!   r!   r%   _diagonalize~  s     4


r   c                 C   s&   |   }|dkrdS |r"| jr"dS d S NFT)Z_has_positive_diagonalsZis_strongly_diagonally_dominant)r7   Zpositive_diagonalsr!   r!   r%   _fuzzy_positive_definite  s    
r   c                 C   s&   |   }|dkrdS |r"| jr"dS d S r   )Z_has_nonnegative_diagonalsZis_weakly_diagonally_dominant)r7   Znonnegative_diagonalsr!   r!   r%   _fuzzy_positive_semidefinite  s    
r   c                 C   s6   | j s| jsdS | | j } t| }|d k	r.|S t| S NF)r   rQ   r   r   _is_positive_definite_GEr7   Zfuzzyr!   r!   r%   _is_positive_definite  s    
r   c                 C   s6   | j s| jsdS | | j } t| }|d k	r.|S t| S r   )r   rQ   r   r   "_is_positive_semidefinite_choleskyr   r!   r!   r%   _is_positive_semidefinite  s    
r   c                 C   s
   t |  S rI   )r   r7   r!   r!   r%   _is_negative_definite  s    r   c                 C   s
   t |  S rI   )r   r   r!   r!   r%   _is_negative_semidefinite  s    r   c                 C   sd   | j rN|  }dd | D }t|}dd | D }t|}t||gS | jr`| | j jS dS )Nc                 S   s   g | ]
}|j qS r!   )is_positiver,   r!   r!   r%   r.     s     z"_is_indefinite.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r!   )is_negativer,   r!   r!   r%   r.     s     F)r   r   keysr   r   rQ   r   Zis_indefinite)r7   ZeigenZargs1Zany_positiveZargs2Zany_negativer!   r!   r%   _is_indefinite  s    r   c                 C   s   |   } | j}t|D ]}| ||f j}|dk	r8|  S t|d |D ]T}| ||f | ||d df  | ||f | ||d df   | ||d df< qFqdS )zRA division-free gaussian elimination method for testing
    positive-definiteness.Tr   N)r   rC   rB   r   )r7   sizer$   r   jr!   r!   r%   r     s    Tr   c           
   	      s      t jD ]} fddt| jD }t|\}}}}|rL dS |dkrt|d  jD ]H}t| jD ]6} ||f j}	|	dkr   dS |	dkrt   dS qtqd dS  ||f js|jr dS  ||f jr|js dS |dkr |||   	|||  t
 ||f  ||f<  ||d df   ||f   <  |d d|d df   ||d df j ||d df  8  < q d jS )	zUses Cholesky factorization with complete pivoting

    References
    ==========

    .. [1] http://eprints.ma.man.ac.uk/1199/1/covered/MIMS_ep2008_116.pdf

    .. [2] https://www.value-at-risk.net/cholesky-factorization/
    c                    s   g | ]} ||f qS r!   r!   r"   r   r!   r%   r.   -  s     z6_is_positive_semidefinite_cholesky.<locals>.<listcomp>Nr   FTr   )r   )r   rB   rC   r   r   is_zeror   Zis_nonnegativeZcol_swapZrow_swapr   r   )
r7   r|   ZdiagsZpivotZ	pivot_valZnonzeror?   r$   r   Ziszeror!   r   r%   r   !  s4    


$Lr   aP  Finds out the definiteness of a matrix.

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

    A square real matrix $A$ is:

    - A positive definite matrix if $x^T A x > 0$
      for all non-zero real vectors $x$.
    - A positive semidefinite matrix if $x^T A x \geq 0$
      for all non-zero real vectors $x$.
    - A negative definite matrix if $x^T A x < 0$
      for all non-zero real vectors $x$.
    - A negative semidefinite matrix if $x^T A x \leq 0$
      for all non-zero real vectors $x$.
    - An indefinite matrix if there exists non-zero real vectors
      $x, y$ with $x^T A x > 0 > y^T A y$.

    A square complex matrix $A$ is:

    - A positive definite matrix if $\text{re}(x^H A x) > 0$
      for all non-zero complex vectors $x$.
    - A positive semidefinite matrix if $\text{re}(x^H A x) \geq 0$
      for all non-zero complex vectors $x$.
    - A negative definite matrix if $\text{re}(x^H A x) < 0$
      for all non-zero complex vectors $x$.
    - A negative semidefinite matrix if $\text{re}(x^H A x) \leq 0$
      for all non-zero complex vectors $x$.
    - An indefinite matrix if there exists non-zero complex vectors
      $x, y$ with $\text{re}(x^H A x) > 0 > \text{re}(y^H A y)$.

    A matrix need not be symmetric or hermitian to be positive definite.

    - A real non-symmetric matrix is positive definite if and only if
      $\frac{A + A^T}{2}$ is positive definite.
    - A complex non-hermitian matrix is positive definite if and only if
      $\frac{A + A^H}{2}$ is positive definite.

    And this extension can apply for all the definitions above.

    However, for complex cases, you can restrict the definition of
    $\text{re}(x^H A x) > 0$ to $x^H A x > 0$ and require the matrix
    to be hermitian.
    But we do not present this restriction for computation because you
    can check ``M.is_hermitian`` independently with this and use
    the same procedure.

    Examples
    ========

    An example of symmetric positive definite matrix:

    .. plot::
        :context: reset
        :format: doctest
        :include-source: True

        >>> from sympy import Matrix, symbols
        >>> from sympy.plotting import plot3d
        >>> a, b = symbols('a b')
        >>> x = Matrix([a, b])

        >>> A = Matrix([[1, 0], [0, 1]])
        >>> A.is_positive_definite
        True
        >>> A.is_positive_semidefinite
        True

        >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))

    An example of symmetric positive semidefinite matrix:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> A = Matrix([[1, -1], [-1, 1]])
        >>> A.is_positive_definite
        False
        >>> A.is_positive_semidefinite
        True

        >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))

    An example of symmetric negative definite matrix:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> A = Matrix([[-1, 0], [0, -1]])
        >>> A.is_negative_definite
        True
        >>> A.is_negative_semidefinite
        True
        >>> A.is_indefinite
        False

        >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))

    An example of symmetric indefinite matrix:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> A = Matrix([[1, 2], [2, -1]])
        >>> A.is_indefinite
        True

        >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))

    An example of non-symmetric positive definite matrix.

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> A = Matrix([[1, 2], [-2, 1]])
        >>> A.is_positive_definite
        True
        >>> A.is_positive_semidefinite
        True

        >>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))

    Notes
    =====

    Although some people trivialize the definition of positive definite
    matrices only for symmetric or hermitian matrices, this restriction
    is not correct because it does not classify all instances of
    positive definite matrices from the definition $x^T A x > 0$ or
    $\text{re}(x^H A x) > 0$.

    For instance, ``Matrix([[1, 2], [-2, 1]])`` presented in
    the example above is an example of real positive definite matrix
    that is not symmetric.

    However, since the following formula holds true;

    .. math::
        \text{re}(x^H A x) > 0 \iff
        \text{re}(x^H \frac{A + A^H}{2} x) > 0

    We can classify all positive definite matrices that may or may not
    be symmetric or hermitian by transforming the matrix to
    $\frac{A + A^T}{2}$ or $\frac{A + A^H}{2}$
    (which is guaranteed to be always real symmetric or complex
    hermitian) and we can defer most of the studies to symmetric or
    hermitian positive definite matrices.

    But it is a different problem for the existance of Cholesky
    decomposition. Because even though a non symmetric or a non
    hermitian matrix can be positive definite, Cholesky or LDL
    decomposition does not exist because the decompositions require the
    matrix to be symmetric or hermitian.

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Definiteness_of_a_matrix#Eigenvalues

    .. [2] https://mathworld.wolfram.com/PositiveDefiniteMatrix.html

    .. [3] Johnson, C. R. "Positive Definite Matrices." Amer.
        Math. Monthly 77, 259-264 1970.
    c                   s   j std  trbztdd   D }W n tk
rR   d}Y nX tt|dfdd}i  fdd	 fd
d}dd } fdd}rddlm	 
fdd }|D ]}	|	trtdqt| jkrPt| td}
j|
 }|s*||S fdd|
D }j| }|||S g }t| tdD ]R| }||}||}dd t|D }|  |fdd|D  qdtdd |D }| jkrtd fdd|D }
j|
 }|s||S g }t| tdD ]g }|D ]x\}}|krDq.| }|d  }||| |		fddt|D }|| |t| q.q"j| }|||S )a  Return $(P, J)$ where $J$ is a Jordan block
    matrix and $P$ is a matrix such that $M = P J P^{-1}$

    Parameters
    ==========

    calc_transform : bool
        If ``False``, then only $J$ is returned.

    chop : bool
        All matrices are converted 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 formsc                 s   s   | ]}t |tr|jV  qd S rI   )re   r   r+   )r#   termr!   r!   r%   r&   -  s     
 z_jordan_form.<locals>.<genexpr>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 ))r/   r   r   )r#   r   )r   max_dpsr!   r%   r.   <  s     z8_jordan_form.<locals>.restore_floats.<locals>.<listcomp>r   r   )rd   )args)r   r   r   r!   r%   restore_floats7  s
    z$_jordan_form.<locals>.restore_floatsc                    s   | |fkr| |f S | |d fkrT| |d f j | df dd| |f< n"|   j  || |f< | |f S )zFCache computations of ``(M - val*I)**pow`` for quick
        retrievalr   NZdotprodsimp)multiplyr   rC   pow)rr   r   )r7   mat	mat_cacher!   r%   eig_matE  s    
 "z_jordan_form.<locals>.eig_matc                    s    j }dg}|| d  }d}||d kr|| ||krBq|| |  }|d7 }||d k sp||kr"td q"|S )zpCalculate the sequence  [0, nullity(E), nullity(E**2), ...]
        until it is constant where ``E = M - val*I``r   r   r    r   zMSymPy had encountered an inconsistent result while computing Jordan block: {})r   ZrankrD   r   rR   )rr   algebraic_multiplicityr   r   Znullityr$   )r7   r   r!   r%   nullity_chainU  s"    
z#_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 )r    r   r!   )r#   r/   dr!   r%   r.   |  s     zC_jordan_form.<locals>.blocks_from_nullity_chain.<locals>.<listcomp>r   r   r   )rB   rd   )r   midendr!   r   r%   blocks_from_nullity_chaint  s     (z/_jordan_form.<locals>.blocks_from_nullity_chainc                    sV   t | dkr|d S |D ]8} j| |g  jdd\}}|d t | kr|  S qdS )zWPicks a vector from big_basis that isn't in
        the subspace spanned by small_basisr   T)Zwith_pivotsr   N)rd   r   Zechelon_form)Zsmall_basisZ	big_basisr(   r?   Zpivotsr   r!   r%   pick_vec  s    
z_jordan_form.<locals>.pick_vecr   rK   c                    s    | ddS rM   r!   rO   rK   r!   r%   r)     r*   z_jordan_form.<locals>.<lambda>zTJordan normal form is not implemented if the matrix have eigenvalues in CRootOf formr   c                    s   g | ]} |d   d qS )r   r   )r   )r#   r5   )r   r!   r%   r.     s   z _jordan_form.<locals>.<listcomp>c                 S   s   g | ]\}}|d  |fqS rv   r!   )r#   r$   numr!   r!   r%   r.     s     c                    s&   g | ]\}}t |D ]} |fqqS r!   )rB   )r#   r   r   r?   )r5   r!   r%   r.     s     
  c                 s   s   | ]\}}|V  qd S rI   r!   r#   r5   r   r!   r!   r%   r&     s     zOSymPy had encountered an inconsistent result while computing Jordan block. : {}c                 3   s    | ]\}} j ||d V  qdS ))r   Z
eigenvalueN)Zjordan_blockr   )r   r!   r%   r&     s     r   c                    s    g | ]} |j d dqS )Nr   )r   r"   )r5   r   vecr!   r%   r.     s   )rQ   r   rN   r   r2   rz   r   r   rV   rL   rW   r   r   r   rd   r   r   r   r   r   r   	enumeratereverseextendr'   rC   rR   r   rB   reversed)r7   Zcalc_transformr   Zmax_precr   r   r   r   rt   r-   blocksZ
jordan_matZjordan_basisZ	basis_matZblock_structurer   chainZblock_sizesZ	size_numsZjordan_form_sizeZ	eig_basisZ	block_eigr   Znull_bigZ
null_smallZnew_vecsr!   )
r7   r   r5   r   r   r   r   r   rL   r   r%   _jordan_form  s    #











r   c                 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 r!   )	transpose)r#   r   r!   r!   r%   r.     s     z/_left_eigenvects.<locals>.<listcomp>.<listcomp>r!   )r#   rr   r   r   r!   r!   r%   r.     s     z$_left_eigenvects.<locals>.<listcomp>)r   r   )r7   rZ   rt   r!   r!   r%   _left_eigenvects  s    r   c                 C   s   | j | jkr| j|  }n| | j }g }| D ]\}}|t|g| 7 }q:t|| jk r~|| jg| jt|  7 }|j	dt
d |S )a3  Compute the singular values of a Matrix

    Examples
    ========

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

    See Also
    ========

    condition_number
    T)r   rx   )rC   r   r   r   r   r{   r   rd   zeror   r   )r7   Zvalmultpairsvalsr|   r(   r!   r!   r%   _singular_values  s    r   N)F)T)TF)TF)T)F)F)T)T)FFF)T)Mtypesr   collectionsr   Zmpmathr   r   Zmpmath.libmp.libmpfr   Zsympy.core.sortingr   Zsympy.core.evalfr	   r
   Zsympy.core.logicr   r   Zsympy.core.numbersr   Zsympy.core.sympifyr   Z(sympy.functions.elementary.miscellaneousr   Zsympy.polysr   r   r   r   r   Zsympy.polys.matricesr   Zsympy.polys.matrices.eigenr   r   Zsympy.polys.polytoolsr   commonr   r   Zdeterminantr   Z	utilitiesr   r   r<   rA   rF   r[   rl   rX   rY   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z_doc_positive_definite__doc__r   r   r   r!   r!   r!   r%   <module>   s   
	  l   
-   
0
o

9
"

L- / v#