L i NgdZddlZddlmZmZmZmZmZmZm Z m Z m Z m Z m Z mZmZmZmZddlmZmZddlmZmZmZddlmZmZejdd Zd Zd Zd Zedd d%dZ eddd&dddddddddd dZ!dddddddddd Z"dZ#ed d'dZ$edd d(dZ%eddd&ddddddddddZ&ed d)dZ'edd d*d Z(edd d+d!Z)d,d"Z*edd-d#Z+d$Z,y).) eigeigvalseigheigvalsh eig_bandedeigvals_bandedeigh_tridiagonaleigvalsh_tridiagonal hessenbergcdf2rdfN)arrayisfiniteinexactnonzero iscomplexobj flatnonzeroconjasarrayargsortempty iscomplexzeroseinsumeyeinf)_asarray_validated_apply_over_batch) LinAlgError _datacopiednorm)get_lapack_funcs_compute_lworky?Fdtypec"tj||}|jdkD}|ddxxx|jdddkzccct|D]<}|dd|dzf|jdd|f<t |dd|f|dd|dzf>|S)zR Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output r%r Nr)npr imagrr)wvinr&vmis Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/linalg/_decomp.py_make_complex_eigvecsr1 s E"A !AcrFqvvabzA~F ^!1ac6{q!t  Qq!tWa1Q3i ! Hc|rC|*tj|tj|fStj||fS||Stj|}|dk(}|dk(}|}||||z ||<tj|||z<tj |j dk(rtj|||z<|Sttjtj|||z<|S)Nr ) r)vstack ones_like empty_likerallr*nancomplex)alphabetahomogeneous_eigvalsr+ alpha_zero beta_zero beta_nonzeros r0 _make_eigvalsr@.s <99eR\\%%89: :99eT]+ + <L e$A1*JI%:L#L1$|2DDAlO*,AzkI% &vvejjAo&,.FF*y()H-4BFFBFF,C*y()Hr2c 8td||f\}||} }|||d} | ddjjtj} |j dvr#||||| | ||\} } }}}}t | | |}n/||||| | ||\}}} }}}}|t|zz} t | | |}t|dtj|jdk(}|j dvs6|s4|jj}|r t|||}|r t|||}t|jdD]I}|r!|dd|fxxt!|dd|fzcc<|s)|dd|fxxt!|dd|fzcc<K|s|s|S|r |r|||fS||fS||fS) N)ggevr()lworkr czz generalized eig algorithm (ggev))r"realastyper)int_typecoder@_I _check_infor7r*r&charr1rangeshaper!)a1b1leftright overwrite_a overwrite_br<rBcvlcvrresrCr:r;vlvrworkinfor+alpharalphai only_realtr/s r0_geneigraHs YR 1EDUC r2R C GAJOO " "277 +E }}*.r2sC/:K+I'tRT4 %': ;37BS8={8C4E0b"dDf$ %': ;89qvv}%I MMT !Y GGLL &q"a0B &q"a0B288A; '  q!tHR1X &H  q!tHR1X &H ' E b"9 "u b5Lr2)a)brcFTc t||}t|jdk7s|jd|jdk7r td|jdk(rt t jd|j\} } t j|d| j} t| d |} t j|d | j} t j|d | j} |s|s| S|r |r| | | fS| | fS| | fS|xs t||}|t||}|xs t||}t|jdk7s|jd|jdk7r td|j|jk7r td t|||||||Std |f\}}||}}t||jd|| }|jdvr ||||||\} } } }t| d |} n,||||||\}}} } }|t |zz} t| d |} t#|ddt j$| j&dk(}|jdvs6|s4| jj(}|r t+| | |} |r t+| | |} |s|s| S|r |r| | | fS| | fS| | fS)a8 Solve an ordinary or generalized eigenvalue problem of a square matrix. Find eigenvalues w and right or left eigenvectors of a general matrix:: a vr[:,i] = w[i] b vr[:,i] a.H vl[:,i] = w[i].conj() b.H vl[:,i] where ``.H`` is the Hermitian conjugation. Parameters ---------- a : (M, M) array_like A complex or real matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional Right-hand side matrix in a generalized eigenvalue problem. Default is None, identity matrix is assumed. left : bool, optional Whether to calculate and return left eigenvectors. Default is False. right : bool, optional Whether to calculate and return right eigenvectors. Default is True. overwrite_a : bool, optional Whether to overwrite `a`; may improve performance. Default is False. overwrite_b : bool, optional Whether to overwrite `b`; may improve performance. Default is False. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. homogeneous_eigvals : bool, optional If True, return the eigenvalues in homogeneous coordinates. In this case ``w`` is a (2, M) array so that:: w[1,i] a vr[:,i] = w[0,i] b vr[:,i] Default is False. Returns ------- w : (M,) or (2, M) double or complex ndarray The eigenvalues, each repeated according to its multiplicity. The shape is (M,) unless ``homogeneous_eigvals=True``. vl : (M, M) double or complex ndarray The left eigenvector corresponding to the eigenvalue ``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``. The left eigenvector is not normalized. vr : (M, M) double or complex ndarray The normalized right eigenvector corresponding to the eigenvalue ``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``. Raises ------ LinAlgError If eigenvalue computation does not converge. See Also -------- eigvals : eigenvalues of general arrays eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays. eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian band matrices eigh_tridiagonal : eigenvalues and right eiegenvectors for symmetric/Hermitian tridiagonal matrices Examples -------- >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[0., -1.], [1., 0.]]) >>> linalg.eigvals(a) array([0.+1.j, 0.-1.j]) >>> b = np.array([[0., 1.], [1., 1.]]) >>> linalg.eigvals(a, b) array([ 1.+0.j, -1.+0.j]) >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]]) >>> linalg.eigvals(a, homogeneous_eigvals=True) array([[3.+0.j, 8.+0.j, 7.+0.j], [1.+0.j, 1.+0.j, 1.+0.j]]) >>> a = np.array([[0., -1.], [1., 0.]]) >>> linalg.eigvals(a) == linalg.eig(a)[0] array([ True, True]) >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector array([[-0.70710678+0.j , -0.70710678-0.j ], [-0. +0.70710678j, -0. -0.70710678j]]) >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector array([[0.70710678+0.j , 0.70710678-0.j ], [0. -0.70710678j, 0. +0.70710678j]])  check_finitercr rexpected square matrixr%r rOr&Nr r z a and b must have the same shape)geev geev_lwork) compute_vl compute_vrrE)rCrnrorTzeig algorithm (geev)zCdid not converge (only eigenvalues with order >= %d have converged)positiverF)rlenrO ValueErrorsizerr)rr&r6r@r rar"r#rJrKrLr7r*rMr1)rbrdrRrSrTrUrgr<rPw_nvr_nr+rYrZrQrlrmrnrorCr\wrwir_r`s r0rrrsF AL 9B 288}RXXa[BHHQK7122 ww!|q12 T MM"D : !T#6 7 ]]2V4:: > ]]2V4:: >H "by b5L"u 5+b!"4K}  =!7[Q%7 rxx=A ! !;56 6 88rxx ?@ @r2tUK*, ,((>FD*!5 J :rxx{&0&0 2E }}r*4*4+682r4 !T#6 7#Be/9/90; =BB bL !T#6 7,<=qvv}%I MMT !Y GGLL &q"a0B &q"a0B E b"9 "u b5Lr2) lower eigvals_onlyrTrUtypergsubset_by_indexsubset_by_valuedriverc  |rdnd} |rdnd} gd} | | vr-tdj| dj| dd t|| }t |j d k7s|j d |j dk7r td |j d k(ryttjd |j\}}tj|d|j}tj|d|j}|r|S||fS|xs t||}t|rdnd}|j d }d|i}|t|| }|xs t||}t |j d k7s|j d |j dk7r td|j |j k7r%td|j d|j |dvr tdt|rdn|xsd}|j||d|d uxs| d u}|r | r td|rRd|D\}}d |cxkr |cxkr|ksntd|dz d|d|d |jd!|dz|dzd"| rH| \}}t |cxkr|cxkr tksntd#|d$|d |jd||d%|rd&nd'}| r>|| d(vrt| d)|| d*vrtd+| d,|r| d-vrtd+| d.|d/n|rd0nd1} d2d3gd2d3ggd4gd5d6}|t!|| z|| zd7zf|g\}}||d8}| d9k(r|jd:| dk(rd ndit#|fi|}t%|t&rt)t+||| z|} nd2|i} |j|| dk(rd ndd;|dOd<|i|| ^}}}!}"nm| d1k(rt!|d1z|g}i} n.t!|| z|| zd7zf|g\}}t#||| =}d2|i} |j| | d>|dO||d?|| ^}}}!}"|r|d |!d n|}|r|s|d d d |!d fn|}|"d k(r|r|S||fS|"d@kr"t-dA|" dB|j.|z| z|"|kDrt-dC|"|z dDdEdFdGdHdI}#| dJvr|#dKj|"}$t-|$| dLvr|#dMj|"}$t-|$| dNvrD|r|#dKj|"}$t-|$|#d9j|"|dz}$t-|$|#d/}$t-|$)Pu. Solve a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix. Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of array ``a``, where ``b`` is positive definite such that for every eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of ``v``) satisfies:: a @ vi = λ * b @ vi vi.conj().T @ a @ vi = λ vi.conj().T @ b @ vi = 1 In the standard problem, ``b`` is assumed to be the identity matrix. Parameters ---------- a : (M, M) array_like A complex Hermitian or real symmetric matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional A complex Hermitian or real symmetric definite positive matrix in. If omitted, identity matrix is assumed. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of ``a`` and, if applicable, ``b``. (Default: lower) eigvals_only : bool, optional Whether to calculate only eigenvalues and no eigenvectors. (Default: both are calculated) subset_by_index : iterable, optional If provided, this two-element iterable defines the start and the end indices of the desired eigenvalues (ascending order and 0-indexed). To return only the second smallest to fifth smallest eigenvalues, ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only available with "evr", "evx", and "gvx" drivers. The entries are directly converted to integers via ``int()``. subset_by_value : iterable, optional If provided, this two-element iterable defines the half-open interval ``(a, b]`` that, if any, only the eigenvalues between these values are returned. Only available with "evr", "evx", and "gvx" drivers. Use ``np.inf`` for the unconstrained ends. driver : str, optional Defines which LAPACK driver should be used. Valid options are "ev", "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for generalized (where b is not None) problems. See the Notes section. The default for standard problems is "evr". For generalized problems, "gvd" is used for full set, and "gvx" for subset requested cases. type : int, optional For the generalized problems, this keyword specifies the problem type to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible inputs):: 1 => a @ v = w @ b @ v 2 => a @ b @ v = w @ v 3 => b @ a @ v = w @ v This keyword is ignored for standard problems. overwrite_a : bool, optional Whether to overwrite data in ``a`` (may improve performance). Default is False. overwrite_b : bool, optional Whether to overwrite data in ``b`` (may improve performance). Default is False. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- w : (N,) ndarray The N (N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity. v : (M, N) ndarray The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is the column ``v[:,i]``. Only returned if ``eigvals_only=False``. Raises ------ LinAlgError If eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or Hermitian, no error will be reported but results will be wrong. See Also -------- eigvalsh : eigenvalues of symmetric or Hermitian arrays eig : eigenvalues and right eigenvectors for non-symmetric arrays eigh_tridiagonal : eigenvalues and right eiegenvectors for symmetric/Hermitian tridiagonal matrices Notes ----- This function does not check the input array for being Hermitian/symmetric in order to allow for representing arrays with only their upper/lower triangular parts. Also, note that even though not taken into account, finiteness check applies to the whole array and unaffected by "lower" keyword. This function uses LAPACK drivers for computations in all possible keyword combinations, prefixed with ``sy`` if arrays are real and ``he`` if complex, e.g., a float array with "evr" driver is solved via "syevr", complex arrays with "gvx" driver problem is solved via "hegvx" etc. As a brief summary, the slowest and the most robust driver is the classical ``ev`` which uses symmetric QR. ``evr`` is seen as the optimal choice for the most general cases. However, there are certain occasions that ``evd`` computes faster at the expense of more memory usage. ``evx``, while still being faster than ``ev``, often performs worse than the rest except when very few eigenvalues are requested for large arrays though there is still no performance guarantee. Note that the underlying LAPACK algorithms are different depending on whether `eigvals_only` is True or False --- thus the eigenvalues may differ depending on whether eigenvectors are requested or not. The difference is generally of the order of machine epsilon times the largest eigenvalue, so is likely only visible for zero or nearly zero eigenvalues. For the generalized problem, normalization with respect to the given type argument:: type 1 and 3 : v.conj().T @ a @ v = w type 2 : inv(v).conj().T @ a @ inv(v) = w type 1 or 2 : v.conj().T @ b @ v = I type 3 : v.conj().T @ inv(b) @ v = I Examples -------- >>> import numpy as np >>> from scipy.linalg import eigh >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]]) >>> w, v = eigh(A) >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) True Request only the eigenvalues >>> w = eigh(A, eigvals_only=True) Request eigenvalues that are less than 10. >>> A = np.array([[34, -4, -10, -7, 2], ... [-4, 7, 2, 12, 0], ... [-10, 2, 44, 2, -19], ... [-7, 12, 2, 79, -34], ... [2, 0, -19, -34, 29]]) >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10]) array([6.69199443e-07, 9.11938152e+00]) Request the second smallest eigenvalue and its eigenvector >>> w, v = eigh(A, subset_by_index=[1, 1]) >>> w array([9.11938152]) >>> v.shape # only a single column is returned (5, 1) LUNV)Nevevdevrevxgvgvdgvxz2"{}" is unknown. Possible values are "None", "{}".z", "rNrfrcr zexpected square "a" matrixr%rirjrkTFrTzexpected square "b" matrixzwrong b dimensions z , should be )rrcz("type" keyword only accepts 1, 2, and 3.)rUitypez.Either index or value subset can be requested.c32K|]}t|ywN)int).0xs r0 zeigh..s2Q#a&2sz?Requested eigenvalue indices are not valid. Valid range is [0, z] and start <= end, but start=z, end=z is givenI)rNiliuz^Requested eigenvalue bounds are not valid. Valid range is (-inf, inf) and low < high, but low=z, high=)rNrYvuhesy)rrrzK requires input b array to be supplied for generalized eigenvalue problems.)rrrr"zA" does not accept input b array for standard eigenvalue problems.)rrrrz'" cannot compute subsets of eigenvaluesrrrrCliwork)rCrlrwork)rCrr)syevdsyevrheevdheevr_lwork)nryr compute_v)ryrrb)uplo)rjobz)rbrdr(zIllegal value in argument of internal zThe leading minor of order z of B is not positive definite. The factorization of B could not be completed and no eigenvalues or eigenvectors were computed.zxThe algorithm failed to converge; {} off-diagonal elements of an intermediate tridiagonal form did not converge to zero.z#{} eigenvectors failed to converge.zThe algorithm failed to compute an eigenvalue while working on the submatrix lying in rows and columns {0}/{1} through mod({0},{1}).zInternal Error.)rrrr)rrr)rrr)rr)rsformatjoinrrrrOrtrr)rr&r6r rupdaterr"r# isinstancetupledictziprrJ)%rbrdryrzrTrUr{rgr|r}r~r_jobdrv_strrPruv_nr+r-cplxrdrv_argsrQsubsetlohipfx lwork_specdrvdrvlwclw_argslw lwork_args other_argsr\drv_errmsgs% r0rrsN3SD3CDCG W"F66;;wqr{+CDF F AL 9B 288}RXXa[BHHQK7566 ww!|q12S MM"D : MM"F#)) < Ha4K5+b!"4K#4D  A{+H}  =!7[Q%7 rxx=A ! !;9: : 88rxx 2288*L ST T y GH H#B'tdme dCDT) Kd/JF?IJJ2/2BR!2!!334Q3%8&&(Tt9>? ? #R!V26BC B&R&3&$$&4wrd)=> > #Rr:;$DC 9&$88x(DDE E M*E Eq)AAB B v!;;q(OPQ Q)6%u$X.#X.88 J y%sV|SZ5H&I')d, UU+ U? OO[ts{!B C E .X . b% c*SZ"8"=>J!2J%43;aANO"%"E"Eh"E*"E1z4 U?"3;R9CJ)3<VH9L*M+-r(4JC qt4B!2Jt45"%"Kb"KH"K "K1z4$.:a=A!' !^jm^ 1A qy Ha4K "9 :D5'!$!3f!< =?@ @ AX ;DF8D??@ @ JDJ0G%dm**40c" ">)en++D1c" ">)!$-..t4C c" " "%.//ac:Cc" "enc" "r2rc) r rrcr7valueindexrbr-r/c|t|tr|j} t|}d\}}dx}}|dk7rt |} | jdk7s| jdk7s | d| dkr t d|dk(r | \}}|dk(r|}n| jjjdvr0t d | jd | jjd | dz\}}t||dkst|||kDr t d ||z dz}||||||fS#t$r}t d|d}~wwxYw) z5Check that select is valid, convert to Fortran style.zinvalid argument for selectN)rF?rr rczBselect_range must be a 2-element array-like in nondecreasing orderhilqpzEwhen using select="i", select_range must contain integers, got dtype z ()zselect_range out of bounds) rstrry _conv_dictKeyErrorrsrndimrtr&rMminmax) select select_rangemax_evmax_lenerYrrrsrs r0 _check_selectrts[&#?F#FBKB { \ " 77a<277a<2a52a5=67 7 Q;FB{ xx}}""$G3 33588*Brxx}}oQP !VFB2r{Q#b"+"7 !=>>"Wq[F 2r2r6 ))1 ?67Q>?s D!! D;* D66D;)a_bandrcc |s|rt||}|xs t||}nUt|}t|jj t r$t|js tdd}t|jdk7r td|jdk(rttjddgddgg|j\} } tj|d| j } tj|d | j } |r| S| | fSt!||||jd\}} }}}}~|dk(r?|jj"d vrd }nd }t%|f|f\}||| ||\} } }n|rd}|jj"dvrt%dtddf\}nt%dtddf\}d|dz}|jj"d vrd}nd}t%|f|f\}||| |||| ||||| \} } }}}| d|} |s | ddd|f} t'|||r| S| | fS)aH Solve real symmetric or complex Hermitian band matrix eigenvalue problem. Find eigenvalues w and optionally right eigenvectors v of a:: a v[:,i] = w[i] v[:,i] v.H v = identity The matrix a is stored in a_band either in lower diagonal or upper diagonal ordered form: a_band[u + i - j, j] == a[i,j] (if upper form; i <= j) a_band[ i - j, j] == a[i,j] (if lower form; i >= j) where u is the number of bands above the diagonal. Example of a_band (shape of a is (6,6), u=2):: upper form: * * a02 a13 a24 a35 * a01 a12 a23 a34 a45 a00 a11 a22 a33 a44 a55 lower form: a00 a11 a22 a33 a44 a55 a10 a21 a32 a43 a54 * a20 a31 a42 a53 * * Cells marked with * are not used. Parameters ---------- a_band : (u+1, M) array_like The bands of the M by M matrix a. lower : bool, optional Is the matrix in the lower form. (Default is upper form) eigvals_only : bool, optional Compute only the eigenvalues and no eigenvectors. (Default: calculate also eigenvectors) overwrite_a_band : bool, optional Discard data in a_band (may enhance performance) select : {'a', 'v', 'i'}, optional Which eigenvalues to calculate ====== ======================================== select calculated ====== ======================================== 'a' All eigenvalues 'v' Eigenvalues in the interval (min, max] 'i' Eigenvalues with indices min <= i <= max ====== ======================================== select_range : (min, max), optional Range of selected eigenvalues max_ev : int, optional For select=='v', maximum number of eigenvalues expected. For other values of select, has no meaning. In doubt, leave this parameter untouched. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- w : (M,) ndarray The eigenvalues, in ascending order, each repeated according to its multiplicity. v : (M, M) float or complex ndarray The normalized eigenvector corresponding to the eigenvalue w[i] is the column v[:,i]. Only returned if ``eigvals_only=False``. Raises ------ LinAlgError If eigenvalue computation does not converge. See Also -------- eigvals_banded : eigenvalues for symmetric/Hermitian band matrices eig : eigenvalues and right eigenvectors of general arrays. eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eigh_tridiagonal : eigenvalues and right eigenvectors for symmetric/Hermitian tridiagonal matrices Examples -------- >>> import numpy as np >>> from scipy.linalg import eig_banded >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]]) >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]]) >>> w, v = eig_banded(Ab, lower=True) >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) True >>> w = eig_banded(Ab, lower=True, eigvals_only=True) >>> w array([-4.26200532, -2.22987175, 3.95222349, 12.53965359]) Request only the eigenvalues between ``[-3, 4]`` >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4]) >>> w array([-2.22987175, 3.95222349]) rfz#array must not contain infs or NaNsrrczexpected a 2-D arrayr r%rirjrkGFDhbevdsbevd)rry overwrite_abfF)lamchfdshbevxsbevx)rmmaxrNryrabstolN)rr r issubclassr&r{rrr7rsrrrOrtrr)r6rrMr"rL)rryrzoverwrite_a_bandrrrrgrPrurr+r-rYrrr internal_namebevdr\rrbevxr.ifails r0rrsjZ' \ B+H B0G 6] bhhmmW -hrl6F6F6HBC C 288}/00 ww!|bhhAA'7rxxHIS MM"D : MM"F#)) < Ha4K%2 fbhhqk&3"FBBF  { 88==E ! $M $M -!1B59"L(8 %4DF 1d F 88==D %j5#3F2HIFE%j5#3F2HIFEU3Z 88==E !#M#M -!1B59# BBl*:4D 1a bqE!RaR%Am$ a4Kr2c &t||dd|||S)a Compute eigenvalues from an ordinary or generalized eigenvalue problem. Find eigenvalues of a general matrix:: a vr[:,i] = w[i] b vr[:,i] Parameters ---------- a : (M, M) array_like A complex or real matrix whose eigenvalues and eigenvectors will be computed. b : (M, M) array_like, optional Right-hand side matrix in a generalized eigenvalue problem. If omitted, identity matrix is assumed. overwrite_a : bool, optional Whether to overwrite data in a (may improve performance) check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. homogeneous_eigvals : bool, optional If True, return the eigenvalues in homogeneous coordinates. In this case ``w`` is a (2, M) array so that:: w[1,i] a vr[:,i] = w[0,i] b vr[:,i] Default is False. Returns ------- w : (M,) or (2, M) double or complex ndarray The eigenvalues, each repeated according to its multiplicity but not in any specific order. The shape is (M,) unless ``homogeneous_eigvals=True``. Raises ------ LinAlgError If eigenvalue computation does not converge See Also -------- eig : eigenvalues and right eigenvectors of general arrays. eigvalsh : eigenvalues of symmetric or Hermitian arrays eigvals_banded : eigenvalues for symmetric/Hermitian band matrices eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices Examples -------- >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[0., -1.], [1., 0.]]) >>> linalg.eigvals(a) array([0.+1.j, 0.-1.j]) >>> b = np.array([[0., 1.], [1., 1.]]) >>> linalg.eigvals(a, b) array([ 1.+0.j, -1.+0.j]) >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]]) >>> linalg.eigvals(a, homogeneous_eigvals=True) array([[3.+0.j, 8.+0.j, 7.+0.j], [1.+0.j, 1.+0.j, 1.+0.j]]) r )rdrRrSrTrgr<)r)rbrdrTrgr<s r0rrIs"N qAAQK(#6 88r2)ryrTrUr{rgr|r}r~c .t|||d|||||||  S)u Solves a standard or generalized eigenvalue problem for a complex Hermitian or real symmetric matrix. Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive definite such that for every eigenvalue λ (i-th entry of w) and its eigenvector vi (i-th column of v) satisfies:: a @ vi = λ * b @ vi vi.conj().T @ a @ vi = λ vi.conj().T @ b @ vi = 1 In the standard problem, b is assumed to be the identity matrix. Parameters ---------- a : (M, M) array_like A complex Hermitian or real symmetric matrix whose eigenvalues will be computed. b : (M, M) array_like, optional A complex Hermitian or real symmetric definite positive matrix in. If omitted, identity matrix is assumed. lower : bool, optional Whether the pertinent array data is taken from the lower or upper triangle of ``a`` and, if applicable, ``b``. (Default: lower) overwrite_a : bool, optional Whether to overwrite data in ``a`` (may improve performance). Default is False. overwrite_b : bool, optional Whether to overwrite data in ``b`` (may improve performance). Default is False. type : int, optional For the generalized problems, this keyword specifies the problem type to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible inputs):: 1 => a @ v = w @ b @ v 2 => a @ b @ v = w @ v 3 => b @ a @ v = w @ v This keyword is ignored for standard problems. check_finite : bool, optional Whether to check that the input matrices contain only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. subset_by_index : iterable, optional If provided, this two-element iterable defines the start and the end indices of the desired eigenvalues (ascending order and 0-indexed). To return only the second smallest to fifth smallest eigenvalues, ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only available with "evr", "evx", and "gvx" drivers. The entries are directly converted to integers via ``int()``. subset_by_value : iterable, optional If provided, this two-element iterable defines the half-open interval ``(a, b]`` that, if any, only the eigenvalues between these values are returned. Only available with "evr", "evx", and "gvx" drivers. Use ``np.inf`` for the unconstrained ends. driver : str, optional Defines which LAPACK driver should be used. Valid options are "ev", "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for generalized (where b is not None) problems. See the Notes section of `scipy.linalg.eigh`. Returns ------- w : (N,) ndarray The N (N<=M) selected eigenvalues, in ascending order, each repeated according to its multiplicity. Raises ------ LinAlgError If eigenvalue computation does not converge, an error occurred, or b matrix is not definite positive. Note that if input matrices are not symmetric or Hermitian, no error will be reported but results will be wrong. See Also -------- eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eigvals : eigenvalues of general arrays eigvals_banded : eigenvalues for symmetric/Hermitian band matrices eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices Notes ----- This function does not check the input array for being Hermitian/symmetric in order to allow for representing arrays with only their upper/lower triangular parts. This function serves as a one-liner shorthand for `scipy.linalg.eigh` with the option ``eigvals_only=True`` to get the eigenvalues and not the eigenvectors. Here it is kept as a legacy convenience. It might be beneficial to use the main function to have full control and to be a bit more pythonic. Examples -------- For more examples see `scipy.linalg.eigh`. >>> import numpy as np >>> from scipy.linalg import eigvalsh >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]]) >>> w = eigvalsh(A) >>> w array([-3.74637491, -0.76263923, 6.08502336, 12.42399079]) T) rdryrzrTrUr{rgr|r}r~)r) rbrdryrTrUr{rgr|r}r~s r0rrs+b Qe$K'd / r2c &t||d||||S)a' Solve real symmetric or complex Hermitian band matrix eigenvalue problem. Find eigenvalues w of a:: a v[:,i] = w[i] v[:,i] v.H v = identity The matrix a is stored in a_band either in lower diagonal or upper diagonal ordered form: a_band[u + i - j, j] == a[i,j] (if upper form; i <= j) a_band[ i - j, j] == a[i,j] (if lower form; i >= j) where u is the number of bands above the diagonal. Example of a_band (shape of a is (6,6), u=2):: upper form: * * a02 a13 a24 a35 * a01 a12 a23 a34 a45 a00 a11 a22 a33 a44 a55 lower form: a00 a11 a22 a33 a44 a55 a10 a21 a32 a43 a54 * a20 a31 a42 a53 * * Cells marked with * are not used. Parameters ---------- a_band : (u+1, M) array_like The bands of the M by M matrix a. lower : bool, optional Is the matrix in the lower form. (Default is upper form) overwrite_a_band : bool, optional Discard data in a_band (may enhance performance) select : {'a', 'v', 'i'}, optional Which eigenvalues to calculate ====== ======================================== select calculated ====== ======================================== 'a' All eigenvalues 'v' Eigenvalues in the interval (min, max] 'i' Eigenvalues with indices min <= i <= max ====== ======================================== select_range : (min, max), optional Range of selected eigenvalues check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- w : (M,) ndarray The eigenvalues, in ascending order, each repeated according to its multiplicity. Raises ------ LinAlgError If eigenvalue computation does not converge. See Also -------- eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian band matrices eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices eigvals : eigenvalues of general arrays eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eig : eigenvalues and right eigenvectors for non-symmetric arrays Examples -------- >>> import numpy as np >>> from scipy.linalg import eigvals_banded >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]]) >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]]) >>> w = eigvals_banded(Ab, lower=True) >>> w array([-4.26200532, -2.22987175, 3.95222349, 12.53965359]) r)ryrzrrrrg)r)rryrrrrgs r0rr s$r fE'7#/l LLr2)rr)rrc (t||d|||||S)al Solve eigenvalue problem for a real symmetric tridiagonal matrix. Find eigenvalues `w` of ``a``:: a v[:,i] = w[i] v[:,i] v.H v = identity For a real symmetric matrix ``a`` with diagonal elements `d` and off-diagonal elements `e`. Parameters ---------- d : ndarray, shape (ndim,) The diagonal elements of the array. e : ndarray, shape (ndim-1,) The off-diagonal elements of the array. select : {'a', 'v', 'i'}, optional Which eigenvalues to calculate ====== ======================================== select calculated ====== ======================================== 'a' All eigenvalues 'v' Eigenvalues in the interval (min, max] 'i' Eigenvalues with indices min <= i <= max ====== ======================================== select_range : (min, max), optional Range of selected eigenvalues check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. tol : float The absolute tolerance to which each eigenvalue is required (only used when ``lapack_driver='stebz'``). An eigenvalue (or cluster) is considered to have converged if it lies in an interval of this width. If <= 0. (default), the value ``eps*|a|`` is used where eps is the machine precision, and ``|a|`` is the 1-norm of the matrix ``a``. lapack_driver : str LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf', 'stev', or 'stevd'. When 'auto' (default), it will use 'stevd' if ``select='a'`` and 'stebz' otherwise. 'sterf' and 'stev' can only be used when ``select='a'``. Returns ------- w : (M,) ndarray The eigenvalues, in ascending order, each repeated according to its multiplicity. Raises ------ LinAlgError If eigenvalue computation does not converge. See Also -------- eigh_tridiagonal : eigenvalues and right eiegenvectors for symmetric/Hermitian tridiagonal matrices Examples -------- >>> import numpy as np >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh >>> d = 3*np.ones(4) >>> e = -1*np.ones(3) >>> w = eigvalsh_tridiagonal(d, e) >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1) >>> w2 = eigvalsh(A) # Verify with other eigenvalue routines >>> np.allclose(w - w2, np.zeros(4)) True T)rzrrrgtol lapack_driver)r)rrrrrgrrs r0r r js&Z  14\!s- IIr2c t||}t||}||fD]?}|jdk7r td|jjdvs6t d|j |j dzk7r&td|j d|j dt||d |j \}} } } } } t|ts t d d }||vrtd |d ||dk(r |d k(rdnd}t|dk(rv|dk(r5| |d cxkr| ks'ntg}tdd g|j}n4t|d g|j}tdgg|j}|r|S||fSt|f||f\}| }|dk(r6|d k7r td|s td|||\}}t|}n|dk(r+|d k7r td||||\}}}t|}n|dk(r+|d k7r td||||\}}}t|}n|dk(r;t|}d}t|f||f\}|rdnd}||||| | | | || \}}}}}not|j dz|j}||ddtd||f\}||||| | | | |\}}}t|d||||| | | | ||| \}}}}t||d!z|d|}|r|S|dk(rJtd"||f\}||||\}}t|d#d$%t!|}|||dd|f}}||fSddd|f}||fS)&a Solve eigenvalue problem for a real symmetric tridiagonal matrix. Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``:: a v[:,i] = w[i] v[:,i] v.H v = identity For a real symmetric matrix ``a`` with diagonal elements `d` and off-diagonal elements `e`. Parameters ---------- d : ndarray, shape (ndim,) The diagonal elements of the array. e : ndarray, shape (ndim-1,) The off-diagonal elements of the array. eigvals_only : bool, optional Compute only the eigenvalues and no eigenvectors. (Default: calculate also eigenvectors) select : {'a', 'v', 'i'}, optional Which eigenvalues to calculate ====== ======================================== select calculated ====== ======================================== 'a' All eigenvalues 'v' Eigenvalues in the interval (min, max] 'i' Eigenvalues with indices min <= i <= max ====== ======================================== select_range : (min, max), optional Range of selected eigenvalues check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. tol : float The absolute tolerance to which each eigenvalue is required (only used when 'stebz' is the `lapack_driver`). An eigenvalue (or cluster) is considered to have converged if it lies in an interval of this width. If <= 0. (default), the value ``eps*|a|`` is used where eps is the machine precision, and ``|a|`` is the 1-norm of the matrix ``a``. lapack_driver : str LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf', 'stev', or 'stevd'. When 'auto' (default), it will use 'stevd' if ``select='a'`` and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is used to find the corresponding eigenvectors. 'sterf' can only be used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only be used when ``select='a'``. Returns ------- w : (M,) ndarray The eigenvalues, in ascending order, each repeated according to its multiplicity. v : (M, M) ndarray The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is the column ``v[:,i]``. Only returned if ``eigvals_only=False``. Raises ------ LinAlgError If eigenvalue computation does not converge. See Also -------- eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal matrices eig : eigenvalues and right eigenvectors for non-symmetric arrays eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian band matrices Notes ----- This function makes use of LAPACK ``S/DSTEMR`` routines. Examples -------- >>> import numpy as np >>> from scipy.linalg import eigh_tridiagonal >>> d = 3*np.ones(4) >>> e = -1*np.ones(3) >>> w, v = eigh_tridiagonal(d, e) >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1) >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4))) True rfrzexpected a 1-D arrayrz$Only real arrays currently supportedzd (z%) must have one more element than e (rr zlapack_driver must be str)autostemrsterfstebzstevstevdzlapack_driver must be one of z, got rrrr%rrz)sterf can only be used when select == "a"z0sterf can only be used when eigvals_only is Truerz(stev can only be used when select == "a")rz)stevd can only be used when select == "a"EBNr() stemr_lworkr)rrCrz (eigh_tridiagonal))steinzstein (eigh_tridiagonal)z"%d eigenvectors failed to convergerp)rrrsr&rM TypeErrorrtrrrrrr rr"floatrLr)rrrzrrrgrrcheckrYrrr_driversr+r-funcrr\r.rrorderiblockisplite_rrCrs r0rrsz 1<8A1<8AQD ::?34 4 ;;  u $BC C D  vv!3qvvh&KAFF8STUVV - a!)FBBA mS )344BGG#8 B -01 1#)Q;G  1v{ Q;adbb Aq!fAGG,AqtfAGG,AtfAGG,A Ha4K m-1v 6ED  I Q;HI I$% %q!*4 F & Q;GH H!Q)4 1d F ' ! Q;HI I!Q)4 1d F ' !Cj !="2QF;$%*1aRR+0&2"1ffd166!8QWW %3B'(81a&A )!RRR4=?vtD-(QFBB'0fN 1am&;;< "1A G #$Z!Q8ED1aFF3GAt 8!E GAJEU8Qq%x[qA!t !RaR%A!t r2ch|dkrtd| d||dkDr|rtd|z||fzyy)zCheck info return value.r zillegal value in argument rz%s N)rsr)r\r~rqs r0rLrLusM ax5teWM&RSS axH58+>??xr2ct||}t|jdk7s|jd|jdk7r td|xs t ||}|j dk(rt tjd|j}tj|j|j}|s|St tjd|jd \}}tj|j|j}tj|j|j}||fS|jddkr|r|t|jdfS|Std |f\} } } | |d| \} } }}}t|d d t|}t| | jd| |}| | | ||d\}}}t|dd tj|d}|s|Std|f\}}t||| |}|||| ||d\}}t|dd ||fS)a: Compute Hessenberg form of a matrix. The Hessenberg decomposition is:: A = Q H Q^H where `Q` is unitary/orthogonal and `H` has only zero elements below the first sub-diagonal. Parameters ---------- a : (M, M) array_like Matrix to bring into Hessenberg form. calc_q : bool, optional Whether to compute the transformation matrix. Default is False. overwrite_a : bool, optional Whether to overwrite `a`; may improve performance. Default is False. check_finite : bool, optional Whether to check that the input matrix contains only finite numbers. Disabling may give a performance gain, but may result in problems (crashes, non-termination) if the inputs do contain infinities or NaNs. Returns ------- H : (M, M) ndarray Hessenberg form of `a`. Q : (M, M) ndarray Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``. Only returned if ``calc_q=True``. Examples -------- >>> import numpy as np >>> from scipy.linalg import hessenberg >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]]) >>> H, Q = hessenberg(A, calc_q=True) >>> H array([[ 2. , -11.65843866, 1.42005301, 0.25349066], [ -9.94987437, 14.53535354, -5.31022304, 2.43081618], [ 0. , -1.83299243, 0.38969961, -0.51527034], [ 0. , 0. , -3.83189513, 1.07494686]]) >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4))) True rfrcr rrhrr%T)calc_q)gehrdgebal gehrd_lwork)permuterTzgebal (hessenberg)Frp)rr)rrrCrTzgehrd (hessenberg)r()orghr orghr_lwork)rbtaurrrCrTzorghr (hessenberg))rrrrOrsr rtr r)rr&rr"rLr#triu)rbrrTrgrPh3hq3qrrrbarrpivscaler\rrChqr r r s r0r r }s` AL 9B 288}bhhqkRXXa[81225+b!"4K ww!| q1 2 HHRXXRXX .Hq 9$GFB2A2Aa4K xx{a s288A;'' ' 02ACE%!IE5+!&r1+!NBB$*U; BA ; r BE"%QGMBT*U; BA **BREJE; ;bR 8EbcbRu!LGAt*U; a4Kr2ct|t|}}|jdkr td|jdkr td|j|jdzk7r td|jd}|jdd}|jd|jdk7r td |jd|k7r td t |}|j d }|dzd k(j s td t|}|dd}|d}|d dd} |ddd} d} |D]4} | d dd| dddk(j sJd| | d ddfz } 6t|||fz|jj} t|}|j| d||f<|| | fzj| | | | fz<|| | fzj| | | | fz<t|||fztj}d|d||f<d|| | | fz<d|| | | fz<d|| | | fz<d|| | | fz<td||j}| |fS)a Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real eigenvalues in a block diagonal form ``wr`` and the associated real eigenvectors ``vr``, such that:: vr @ wr = X @ vr continues to hold, where ``X`` is the original array for which ``w`` and ``v`` are the eigenvalues and eigenvectors. .. versionadded:: 1.1.0 Parameters ---------- w : (..., M) array_like Complex or real eigenvalues, an array or stack of arrays Conjugate pairs must not be interleaved, else the wrong result will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result, but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not. v : (..., M, M) array_like Complex or real eigenvectors, a square array or stack of square arrays. Returns ------- wr : (..., M, M) ndarray Real diagonal block form of eigenvalues vr : (..., M, M) ndarray Real eigenvectors associated with ``wr`` See Also -------- eig : Eigenvalues and right eigenvectors for non-symmetric arrays rsf2csf : Convert real Schur form to complex Schur form Notes ----- ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``. For example, obtained by ``w, v = scipy.linalg.eig(X)`` or ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent stacked arrays. .. versionadded:: 1.1.0 Examples -------- >>> import numpy as np >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]]) >>> X array([[ 1, 2, 3], [ 0, 4, 5], [ 0, -5, 4]]) >>> from scipy import linalg >>> w, v = linalg.eig(X) >>> w array([ 1.+0.j, 4.+5.j, 4.-5.j]) >>> v array([[ 1.00000+0.j , -0.01906-0.40016j, -0.01906+0.40016j], [ 0.00000+0.j , 0.00000-0.64788j, 0.00000+0.64788j], [ 0.00000+0.j , 0.64788+0.j , 0.64788-0.j ]]) >>> wr, vr = linalg.cdf2rdf(w, v) >>> wr array([[ 1., 0., 0.], [ 0., 4., 5.], [ 0., -5., 4.]]) >>> vr array([[ 1. , 0.40016, -0.01906], [ 0. , 0.64788, 0. ], [ 0. , 0. , 0.64788]]) >>> vr @ wr array([[ 1. , 1.69593, 1.9246 ], [ 0. , 2.59153, 3.23942], [ 0. , -3.23942, 2.59153]]) >>> X @ vr array([[ 1. , 1.69593, 1.9246 ], [ 0. , 2.59153, 3.23942], [ 0. , -3.23942, 2.59153]]) rzexpected w to be at least 1Drczexpected v to be at least 2DzUexpected eigenvectors array to have exactly one dimension more than eigenvalues arrayr(NrDzVexpected v to be a square matrix or stacked square matrices: v.shape[-2] = v.shape[-1]z7expected the same number of eigenvalues as eigenvectors)axisr z/expected complex-conjugate pairs of eigenvaluesrz(Conjugate pair spanned different arrays!r%.ry?g?yz...ij,...jk->...ik)rrrsrOrsumr7rrrGr&rNr*r)cdoubler)r+r-rM complex_mask n_complexidx idx_stackidx_elemjk stack_indr/rwdiurZs r0r r sf a "4Q"7qA vvz788vvz788vv!AB B  A  Awwr{aggbk!?@ @wwr{a() )Qr)s P77777C114RXXb  4'T8X&7?CZL"ZLz8X&8Du'up@8YYxSr2