K iBddlmZddlmZddlmZmZddlmZddl m Z ddl m Z m Z ddlmZmZddlmZdd lmZdd lmZdd lmZmZmZmZmZdd lmZdd lm Z m!Z!ddl"m#Z#ddl$m%Z%m&Z&ddl'm(Z(ddl)m*Z*m+Z+ddgiZ,dZ-d:dZ.dZ/ d;dddddZ0dZ1 dd=d+Z?d,Z@d-ZAd.ZBd/ZCd0ZDd1ZEd2ZFd3ZGd4ZHd5ZIeIeB_JeIeC_JeIeD_JeIeE_JeIeF_Jd;dd"d6ZKd7ZLd8ZMy9)>) FunctionType)Counter)mpworkprec) prec_to_dpsdefault_sort_key)DEFAULT_MAXPRECPrecisionExhausted) fuzzy_andfuzzy_or)Float)_sympify)sqrt)rootsCRootOfZZQQEX) DomainMatrix)dom_eigenvectsdom_eigenvects_to_sympy)gcd) MatrixErrorNonSquareMatrixError)_find_reasonable_pivot)_iszero _simplify)_is_indefinite_is_negative_definite_is_negative_semidefinite_is_positive_definite_is_positive_semidefinite matplotlibc \d}d}td|jtD}d| z}|tkrt |5t j |jt|}t j|\}}||D cgc]3}t j|t j|fD]} | 5c} }} |(t j|| z |kr ||fcdddS| }ddd|dz}|tkrtcc} }w#1swY$xYw)NcLtjtd|DS)Nc3&K|] }|dz yw)N).0is Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/matrices/eigen.py zA_eigenvals_eigenvects_mpmath...."s!21!Q$!2)rrsum)vs r-z._eigenvals_eigenvects_mpmath.."sbggc!2!223c34K|]}|jywN)_precr+xs r-r.z/_eigenvals_eigenvects_mpmath..%s/1qww/r))n)maxatomsrr rrmatrixevalfreigreimfabsr ) Mnorm2v1precepsAEERer,v2s r-_eigenvals_eigenvects_mpmathrM!s  3E B // /D dU(C  d^  !''K$5'67AFF1IEAr1CaruuQxq.BCCCDB~"''"r'"2S"8"u    B      D  s%AD"8D (D"=D"D""D+Fct|\}}|Dcgc] }t|}}|r|Stt|Scc}w)z Compute eigenvalues using mpmath)rMrdictr)rCmultiplerI_r8results r-_eigenvals_mpmathrS;sC ' *DAq#$ %ahqk %F %   &s?ct|\}}g}t|jD]7}t||}t|dd|f}|j |d|gf9|S)Nr)rMrangerowsrappend)rCrIrJrRr,eigenval eigenvects r-_eigenvects_mpmathrZDsg ( +EAr F 166]2AaD>R1X&  xYK012 Mr3T)simplifyrPrationalc |s|rgSiS|jstdj||jjt t fvr4td|Dr"|jtr t||S|rddl m |jfd}|rt|f||d|St|f||d|S)aCompute 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 ======== MatrixBase.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.c34K|]}|jywr5 is_numberr7s r-r.z_eigenvals..&qq{{&r9rPr nsimplifycF|jtr |dS|SNT)r\)hasrr8rds r-r2z_eigenvals..sQUU5\iD1qr3)error_when_incompleter[) is_squarerformat_repdomainrrallrgrrSsympy.simplifyrd applyfunc_eigenvals_list_eigenvals_dict)rCrir[rPr\flagsrds @r- _eigenvalsrtPs` I ;;"#@#G#G#JKKvv}}RH$ &A& &155<$Q: :, KK H J %:X    !6   r3adIt 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 r|j}g}|jjttfv}|D]}|r,t |dk(r|d}|||f} |j | 1|||f} t|tr| j|} n| j} t| fddi|} t | | jk7r | jd} || z }|s|St|tst }|D cgc] } ||  c} S#t$r|rttg} YUwxYwcc} w)Nrrr[rPTrb)strongly_connected_componentsrlrmrrlenrW isinstancercharpolyrrV all_rootsNotImplementedErrorreigenvals_error_messager)rCrir[rsiblocksall_eigsis_dombindexvalblockrzeigsvalues r-rqrqs@--/GH VV]]r2h &F  c!fkaDEE5L/C OOC !Q$ h -~~x~8H~~'HX666 t9 " ))4)8 D7:  h -)1 2HUO 22' (%&=>>D   3s DD4D10D1c ,|j}i}|jjttfv}|D]}|r3t |dk(r%|d}|||f} |j | ddz|| <8|||f} t|tr| j|} n| j} t| fddi|} t| j| jk7r t| jd} | j'D]\} }| |vr|| xx|z cc<||| <|s|St|tst(}|j'Dcic]\}}|||c}}S#t $r|rt#t$i} YwxYwcc}}w)NrrrvrPFrb)rwrlrmrrrxgetryrrzrr0valuesrVrOr{r|rr}itemsr)rCrir[rsr~rrrrrrrzrkr1keyrs r-rrrrs--/GH VV]]r2h &F   c!fkaDEE5L/C$LLa014HSM !Q$ h -~~x~8H~~'HX777 t{{}  + H...>?JJL DAqH} q   7 B  h -3;>>3C DZS%HSM5 DD!' (%&=>>D   EsE.F.F  F c||j|j|zz }|j|}t|dk(r|r|j|d}t|dk(rt dj ||S)z:Get a basis for the eigenspace for a particular eigenvalue) iszerofuncrTrr[z,Can't evaluate eigenvector for eigenvalue {})eyerV nullspacerxr|rk)rCrXrr[mrets r- _eigenspacers{ aeeAFFmh& &A +++ ,C 3x1}kkZ$k? 3x1}! : A A( KM M Jr3c tj|dd}|j}|jtk7r6t |\}}t |||jfi|}t|d}|Sy)NT)field extensionct|dS)Nrrr8s r-r2z!_eigenvects_DOM..3s6Fqt6Lr3r) r from_Matrixto_densermrrr __class__sorted)rCkwargsDOMr\ algebraic eigenvectss r-_eigenvects_DOMr+so  " "1DD AC ,,.C zzR,S1), i8068 J,LM  r3c |jdddi|}|D]"}|jtstdt |j t }g}|D](\}}t||||} |j||| f*|S)Nr\FzYEigenvector computation is not implemented if the matrix have eigenvalues in CRootOf formrrr*) eigenvalsrgrrrrr rrW) rCrr[rsrr8rrmultvectss r-_eigenvects_sympyr9s 4U4e4I/ 55>./ // y(.>?I C' TAszHM Cu%&' Jr3chopc |jdd}|jdd}|jdd|jddt|ts |rtnd|j t }|r7td|Dr t|Sdd l m |jfd }t|}|t||fd|i|}|r%fd } |D cgc]\} } } | | | | f}} } } |rJ|D cgc]9\} } } | j| | | D cgc]} | j| c} f;}} } } } |Scc} } } wcc} wcc} } } } w) aCompute 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 MatrixBase.nullspace r[TFNrPc|Sr5r*rs r-r2z_eigenvects..sr3c34K|]}|jywr5r_r7s r-r.z_eigenvects..rar9rrcc|dSrfr*rhs r-r2z_eigenvects..s)A"=r3c v|Dcgc](}|tt|z j*c}Scc}wr5)rlistrp)lr1simpfuncs r- denom_cleanz _eigenvects..denom_cleans/DEFqQT!W%00:F FFs-6r)rpopryrrrgrrnrZrordrprrr>)rCrirrrsr[ primitive has_floatsrrrresr1rdrs @@r- _eigenvectsrLsVXyyT*H *e,I IIj$ IIj$ h - (9kuJ &A& &%a( (, KK= > ! C {:JJEJ GBEEE T2T;r?+EE&)**!Cr t $d,LAQWW$W-?,LM** JF-M*sEE E 8E E c|jsdgfS|jd}|D].\}}}|r|jsd|fcS|t|k7s*d|fcSd|fS)zSee _is_diagonalizable. This function returns the bool along with the eigenvectors to avoid calculating them again in functions like ``diagonalize``.FTrv)rjris_realrx)rC reals_only eigenvecsrrbasiss r-_is_diagonalizable_with_eigenrsr ;;by d +I%$T5 ckk)# # 3u: )# # $ ?r3c |jsytd|Dr|jrytd|Dr |jryt ||dS)aReturns ``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 ======== sympy.matrices.matrixbase.MatrixBase.is_diagonal diagonalize Fc34K|]}|jywr5)rr+rKs r-r.z%_is_diagonalizable..s 199 r9Tc34K|]}|jywr5) is_complexrs r-r.z%_is_diagonalizable..s #A1<< #r9rr)rjrn is_symmetric is_hermitianr)rCrrs r-_is_diagonalizablersRX ;; a  Q^^%5 # ## (z B1 EEr3c|jdk(s td|j}|j}|j}|dt|dz }|j }|d||zz|d<|d||zz |d<|dddfj dk(r d}d|d<||fS|j |j kr|}n|}||dz }d|j dzz }||fS)NrzInput must be a column matrix)rrrr))cols ValueErrorcopyabsnorm)r8r1v_plusv_minusqnorm_xbets r-_householder_vectorrs 66Q;899 A VVXFffhG $#ag,A VVXFT7QZ'F4LdGa&j(GDMQx}}!$ c6M ;;=GLLN *AA !H1668q=! c6Mr3c|j}|j}|j}|j||j|}}t t ||D]}t ||d|f\}}|j||z ||z|jzz } | ||d|dfz||d|df<|j|} | | |d|df<|| z}|dz|dz kst |||dzdfj\}}|j||z dz ||z|jzz } ||d|dzdf| z||d|dzdf<|j|} | | |dzd|dzdf<| |z}|||fSNrr)) rVr as_mutablerrUminrHT) rCrr:rHUVr,r1rhh_mattemps r-_bidiagonal_decmp_hholderrs A A A 558QUU1XqA 3q!9  $Qqr1uX.3q1ua!## -Qqr12vY&!"ab& uuQxQRV H q5AE>(1acd76FAsUU1q519%a!## 5FAB!H+.Aab!A#$hK558D%D1qst qA  a7Nr3c|j}|j}|j}tt ||D]}t ||d|f\}}|j ||z ||z|jzz }|||d|dfz||d|df<|dz|dz ksbt |||dzdfj\}}|j ||z dz ||z|jzz }||d|dzdf|z||d|dzdf<|Sr) rVrrrUrrrrr)rCrr:rHr,r1rrs r-_eval_bidiag_hholderr4s A A A 3q!9 /$Qqr1uX.3qscAgm+Qqr12vY&!"ab& q5AE>(1acd76FAsUU1q519%a!## 5FAB!H+.Aab!A#$hK/ Hr3ct|ts td|r t|St|j}|dj|dj|djfS)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)rr)ryboolrrr)rCupperXs r-_bidiagonal_decompositionrCs[0 eT "233 (++!!##&A Q4661Q4661Q466 !!r3ct|ts td|r t|St|jjS)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)ryrrrr)rCrs r-_bidiagonalizeres=( eT "233 #A&&  $ & &&r3cR|js tt||\}}|s td|rt |t }gg}}|D]\}} } ||g| zz }|| z }|r |D cgc]} | | j z }} |j||j|fScc} w)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 ======== sympy.matrices.matrixbase.MatrixBase.is_diagonal is_diagonalizable rzMatrix is not diagonalizabler) rjrrrrr rhstackdiag) rCrsort normalizeis_diagonalizablerp_colsrrrrr1s r- _diagonalizersh ;;"$$#@%$' y 899 9*:; rDF%T5 3%$,%(./1!affh,// 188V faffdm ++0s*B$cL|j}|dury|r |jryyNFT)_has_positive_diagonalsis_strongly_diagonally_dominant)rCpositive_diagonalss r-_fuzzy_positive_definiters-224U"a?? r3cL|j}|dury|r |jryyr)_has_nonnegative_diagonalsis_weakly_diagonally_dominant)rCnonnegative_diagonalss r-_fuzzy_positive_semidefiniters-88:%!@!@ r3c|js|jsy||jz}t|}||St |SNF)rrjrr_is_positive_definite_GErCfuzzys r-r#r#s@ >>{{ G $Q 'E  #A &&r3c|js|jsy||jz}t|}||St |Sr)rrjrr"_is_positive_semidefinite_choleskyrs r-r$r$s@ >>{{ G ( +E  -a 00r3ct| Sr5)r#rCs r-r!r!s ! $$r3ct| Sr5)r$rs r-r"r"s $aR ((r3c||jr|j}|jDcgc]}|j}}t |}|jDcgc]}|j }}t |}t ||gS|jr||jzjSycc}wcc}wr) rrkeys is_positiver is_negativer rjr is_indefinite)rCeigenr8args1 any_positiveargs2 any_negatives r-r r s~~ /4zz|y|||fj s |j ry|||fjr |jsy|dkDr*|j|||z|j|||zt|||f|||f<|||dzdfxx|||fzcc<||dzd|dzdfxx|||dzdfj|||dzdfzzcc<s|djScc}w)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/ NrFTr)r) rrUrVrris_zeror is_nonnegativecol_swaprow_swaprr) rCrr,diagspivot pivot_valnonzerorQriszeros r-rr$s A 166]3"'166"23Q1a433'=e'D$y'1  =1Q3' %q!&&)%Aq!tW__F~#5$ % % QT7  )"7"7AqD'((Y-E-E 19 JJq!E' " JJq!E' "qAw-!Q$ !QqST' a1g  !A#$!* 1acd7!QqST' 22 93< V9 # ##;4sF)aPFinds 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 existence 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 & !"#$js td!jt r6 t dj D}t t|d# #fd}i"!"fdfd}d}fd } rd d lm $!j$fd !!j}|D]"} | jtstd t|j!j k(rwt#|jt$} !j&| } |s|| S| D cgc]} | dj)d } } !j*| }||| Sg}t#|jt$D]} || }|| |}||}t-|Dcgc] \}}|dz|f}}}|j/|j1|Dcgc]\}}t3|D]}| |fc}}}t5d|D}|j6k7rtdj9!fd|D} !j&| } |s|| Sg} t#|jt$D]} g}|D]\}}|| k7r | |j)}| |dz j)}|||z|}t3|Dcgc]}| |j;|d}}|j1|| j1t=|!j*| }||| S#t $rd}YwxYwcc} wcc}}wcc}}}wcc}w)aReturn $(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 formsc3VK|]!}t|ts|j#ywr5)ryrr6)r+terms r-r.z_jordan_form..0sX$ 4QV@W4::Xs))5c|r |Dcgc]}|j}}t|dk(r|dS|Scc}w)zMIf ``has_floats`` is `True`, cast all ``args`` as matrices of floats.)r:rrr)r>rx)argsrrrmax_dpss r-restore_floatsz$_jordan_form..restore_floats:sG ;?@aAGGgDG1@D@ t9>7N As9c||fvr||fS||dz fvr&||dz fj|dfd||f<n5|jjzz j|||f<||fS)zFCache computations of ``(M - val*I)**pow`` for quick retrievalrN dotprodsimp)multiplyrrVpow)rr+rCmat mat_caches r-eig_matz_jordan_form..eig_matHs : "c3Z( ( q>Y &$-sC!Gn$=$F$FsAh'T%G%;IsCj !&)3quuQVV}+<%<$A$A#$FIsCj !#s$$r3c>j}dg}||djz }d}||dk7rh|j|||k(r |S|||jz }|dz }||dks||kDrtdj ||dk7rh|S)zpCalculate the sequence [0, nullity(E), nullity(E**2), ...] until it is constant where ``E = M - val*I``rrr)rzMSymPy had encountered an inconsistent result while computing Jordan block: {})rrankrWrrk)ralgebraic_multiplicityrrnullityr,rCr.s r- nullity_chainz#_jordan_form..nullity_chainXs &&#a--//R JJw 00 gc1o2244G qLA R G.D$D!$$R $ r3ctdt|dz Dcgc]}d||z||dz z ||dzz }}t|dkDr |d|dz gn|dg}||zScc}w)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)rr)rr)rUrx)dr:midends r-blocks_from_nullity_chainz/_jordan_form..blocks_from_nullity_chainws6;1c!fqj5IJq1v!a% 1QU8+JJ"%Q!ququ}o!A$Sy Ks!A#ct|dk(r|dS|D]=}j||gzjd\}}|dt|k(s;|cSy)zWPicks a vector from big_basis that isn't in the subspace spanned by small_basisrT) with_pivotsrN)rxr echelon_form) small_basis big_basisr1rQpivotsrCs r-pick_vecz_jordan_form..pick_vecsr { q Q<  A ;!#46CC $D&IAvbzS--  r3rrcc|dSrfr*rhs r-r2z_jordan_form..siD&Ar3zTJordan normal form is not implemented if the matrix have eigenvalues in CRootOf formrrc3&K|] \}}| ywr5r*)r+r?rs r-r.z_jordan_form..sAIC4Ar/zOSymPy had encountered an inconsistent result while computing Jordan block. : {}c3JK|]\}}j||yw))r eigenvalueN) jordan_block)r+r?rr,s r-r.z_jordan_form..s%_)#t#"""=_s #Nr()rjrrgrr;rrrrordrprrrrxrrrr rrr enumeratereverseextendrUr0rVrkr*reversed)%rCcalc_transformrmax_precr&r3r9r@rr8blocks jordan_matr? jordan_basis basis_matblock_structurer1chain block_sizesr,num size_numsrrQjordan_form_size eig_basis block_eignull_big null_smallvecnew_vecsr.rr,r-r%rds%` ` @@@@@@r- _jordan_formr\sF ;;"#KLLCuJ X!((*XXHk(+R0 I % >  ,mmAB ==?D/ 55>./ // 499;388#DIIK-=>SXXv& !*- -"# Q113A6# #!szz<0 i44Odiik'78J!%cc#9:/6 /8 .DEFAsac3ZE E *3 H HYT3U3Z Hc4[ H[ H JJ"AAA166! ++16!96 6`_F6"J j))Ldiik'784 . 4OItC!#t,779H!#tax0;;=J  Y 6AC"4[* Q00$0G*H*   X &    2 3! 44* L)I )Z 00M H x#"F IV*s) M*!M<N:N!N* M98M9c |jjdi|}|Dcgc]'\}}}|||Dcgc]}|jc}f)c}}}}Scc}wcc}}}}w)aReturns 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]])])] r*) transposer)rCrsrrrrrs r-_left_eigenvectsr_sX< $1;;= # # ,e ,DPT U U>> 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)rGr) rVrrr*rrrrxzerorr )rC valmultpairsvalsrr1s r-_singular_valuesrds$ vvss||A002 zz!##002  D""$1 a A   4y166 AFFSY.// IId 0I1 Kr3N)F)T)TF)FFF)Ntypesr collectionsrmpmathrrmpmath.libmp.libmpfrsympy.core.sortingr sympy.core.evalfr r sympy.core.logicr r sympy.core.numbersrsympy.core.sympifyr(sympy.functions.elementary.miscellaneousr sympy.polysrrrrrsympy.polys.matricesrsympy.polys.matrices.eigenrrsympy.polys.polytoolsr exceptionsrr determinantr utilitiesrr__doctest_requires__rMrSrZrtr}rqrrrrrrrrrrrrrrrrr#r$r!r"r rr_doc_positive_definite__doc__r\r_rdr*r3r-rysu+/@0$'922-N%9/)"%1> 4!"h/4u hX2-2&3T-2*EZ)0%  &*.'l5l^&5Fr.,  "D'8I,X ' 1%)  )$Zk\%;$:!$:$:!$:r1r1j VF%r3