
    5[g                     x   g d Z ddlZddlmZmZmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZmZ  ej                  dd	
      Zd Zd Zd Z	 	 d dZd!dddddddddd	dZ dddddddddd	Z!d Z"	 	 d"dZ#	 	 d#dZ$d!ddddddddddZ%	 	 d$dZ&	 	 d%dZ'	 	 d&dZ(d'dZ)d(dZ*d Z+y)))
eigeigvalseigheigvalsh
eig_bandedeigvals_bandedeigh_tridiagonaleigvalsh_tridiagonal
hessenbergcdf2rdf    N)arrayisfiniteinexactnonzeroiscomplexobjflatnonzeroconjasarrayargsortempty	iscomplexzeroseinsumeyeinf)_asarray_validated   )LinAlgError_datacopiednorm)get_lapack_funcs_compute_lworky              ?Fdtypec                 "   t        j                  ||      }| j                  dkD  }|ddxxx | j                  dd dk  z  ccc t        |      D ]<  }|dd|dz   f   |j                  dd|f<   t	        |dd|f   |dd|dz   f          > |S )zR
    Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
    r$   r   Nr   )npr   imagr   r   )wvinr%   vmis         O/var/www/html/bid-api/venv/lib/python3.12/site-packages/scipy/linalg/_decomp.py_make_complex_eigvecsr0       s    
 	E"A	
!AcrFqvvabzA~F^1ac6{q!tQq!tWa1Q3i   H    c                    |rC|*t        j                  | t        j                  |       f      S t        j                  | |f      S || S t        j                  |       }| dk(  }|dk(  }| }| |   ||   z  ||<   t         j                  || |z  <   t        j
                  | j                  dk(        rt         j                  |||z  <   |S t        t         j                  t         j                        |||z  <   |S )Nr   )	r(   vstack	ones_like
empty_liker   allr)   nancomplex)alphabetahomogeneous_eigvalsr*   
alpha_zero	beta_zerobeta_nonzeros          r/   _make_eigvalsr?   .   s    <99eR\\%%89::99eT]++<Le$A1*JI%:L#L1$|2DDAlO *,AzkI%&vvejjAo&,.FF*y() H -4BFFBFF,C*y()Hr1   c           	      8   t        d| |f      \  }||}	} || |d      }
|
d   d   j                  j                  t        j                        }|j
                  dv r# || |||	|||      \  }}}}}}t        |||      }n/ || |||	|||      \  }}}}}}}|t        |z  z   }t        |||      }t        |d       t        j                  |j                  dk(        }|j
                  dv s6|s4|j                  j                  }|rt        |||      }|rt        |||      }t        |j                  d         D ]I  }|r!|d d |fxx   t!        |d d |f         z  cc<   |s)|d d |fxx   t!        |d d |f         z  cc<   K |s|s|S |r|r|||fS ||fS ||fS )	N)ggevr'   )lworkr   czz generalized eig algorithm (ggev)        )r!   realastyper(   int_typecoder?   _I_check_infor6   r)   r%   charr0   rangeshaper    )a1b1leftrightoverwrite_aoverwrite_br;   rA   cvlcvrresrB   r9   r:   vlvrworkinfor*   alpharalphai	only_realtr.   s                           r/   _geneigr`   H   s   YR1EDUC
r2R
 CGAJOO""277+E}}*.r2sC/:K+I'tRT4%':;37BS8={8C4E0b"dD f$%':;89qvv}%IMMT!YGGLL&q"a0B&q"a0B 288A;q!tHR1X&Hq!tHR1X&H	   Eb"9"ub5Lr1   FTc           	         t        | |      }t        |j                        dk7  s|j                  d   |j                  d   k7  rt        d      |j                  dk(  rt        t        j                  d|j                              \  }	}
t        j                  |d|	j                        }t        |d	|      }t        j                  |d
|
j                        }t        j                  |d
|
j                        }|s|s|S |r|r|||fS ||fS ||fS |xs t        ||       }|t        ||      }|xs t        ||      }t        |j                        dk7  s|j                  d   |j                  d   k7  rt        d      |j                  |j                  k7  rt        d      t        |||||||      S t        d|f      \  }}||}}t        ||j                  d   ||      }|j                  dv r  ||||||      \  }}}}t        |d	|      }n, ||||||      \  }}}}}|t         |z  z   }t        |d	|      }t#        |dd       t        j$                  |j&                  dk(        }|j                  dv s6|s4|j                  j(                  }|rt+        |||      }|rt+        |||      }|s|s|S |r|r|||fS ||fS ||fS )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_finite   r   r   expected square matrixr$   r   rN   r%   Nr   r   z a and b must have the same shape)geev
geev_lwork)
compute_vl
compute_vrrD   )rB   rk   rl   rS   zeig algorithm (geev)zCdid not converge (only eigenvalues with order >= %d have converged)positiverE   )r   lenrN   
ValueErrorsizer   r(   r   r%   r5   r?   r   r`   r!   r"   rI   rJ   rK   r6   r)   rL   r0   )abrQ   rR   rS   rT   rc   r;   rO   w_nvr_nr*   rX   rY   rP   ri   rj   rk   rl   rB   r[   wrwir^   r_   s                            r/   r   r   r   s   D 
AL	9B
288}RXXa[BHHQK7122 
ww!|q12	TMM"D		:!T#67]]2V4::>]]2V4::>H"by b5L"u5+b!"4K}=!7[Q%7rxx=A!!;56688rxx?@@r2tUK*, 	, ((>FD*!5
J:rxx{&0&02E }}r*4*4+682r4 !T#67#Be/9/90; =BB bL!T#67,<= qvv}%IMMT!YGGLL&q"a0B&q"a0BEb"9"ub5Lr1   )	lowereigvals_onlyrS   rT   typerc   subset_by_indexsubset_by_valuedriverc       	   
      
   |rdnd}|rdnd}g d}|
|vr-t        dj                  |
dj                  |dd	                   t        | |
      }t	        |j
                        dk7  s|j
                  d   |j
                  d   k7  rt        d      |j                  dk(  ryt        t        j                  d|j                              \  }}t        j                  |d|j                        }t        j                  |d|j                        }|r|S ||fS |xs t        ||       }t        |      rdnd}|j
                  d   }d|i}|t        ||
      }|xs t        ||      }t	        |j
                        dk7  s|j
                  d   |j
                  d   k7  rt        d      |j
                  |j
                  k7  r%t        d|j
                   d|j
                         |dvrt        d      t        |      rdn|xs d}|j                  ||d       |d	uxs |	d	u}|r|	rt        d      |rRd |D        \  }}d|cxk  r|cxk  r|k  sn t        d|dz
   d| d| d       |j                  d!|dz   |dz   d"       |	rH|	\  }}t         |cxk  r|cxk  r	t        k  sn t        d#| d$| d       |j                  d||d%       |rd&nd'}|
r>||
d(v rt        |
 d)      ||
d*v rt        d+|
 d,      |r|
d-v rt        d+|
 d.      |d/n|rd0nd1}
d2d3gd2d3gg d4g d5d6}|t!        ||
z   ||
z   d7z   f|g      \  }}||d8}|
d9k(  r|j                  d:|dk(  rdndi       t#        |fi |}t%        |t&              rt)        t+        |||
z      |            } nd2|i} |j                  ||dk(  rdndd;        |dOd<|i|| ^}}}!}"nm|
d1k(  rt!        |d1z   |g      }i } n.t!        ||
z   ||
z   d7z   f|g      \  }}t#        |||=      }d2|i} |j                  ||d>        |dO||d?|| ^}}}!}"|r|d	|!d    n|}|r|s|d	d	d	|!d   f   n|}|"dk(  r|r|S ||fS |"d@k  r"t-        dA|"  dB|j.                  |z   |
z          |"|kD  rt-        dC|"|z
   dD      dEdFdGdHdI}#|
dJv r|#dK   j                  |"      }$t-        |$      |
dLv r|#dM   j                  |"      }$t-        |$      |
dNv rD|r|#dK   j                  |"      }$t-        |$      |#d9   j                  |"|dz         }$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 ``<sy/he>ev`` which uses symmetric QR. ``<sy/he>evr`` is seen as
    the optimal choice for the most general cases. However, there are certain
    occasions that ``<sy/he>evd`` computes faster at the expense of more
    memory usage. ``<sy/he>evx``, while still being faster than ``<sy/he>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)

    LUNV)Nevevdevrevxgvgvdgvxz2"{}" is unknown. Possible values are "None", "{}".z", "r   Nrb   rd   r   zexpected square "a" matrixr$   rf   rg   rh   TFrS   zexpected square "b" matrixzwrong b dimensions z, should be )r   rd      z("type" keyword only accepts 1, 2, and 3.)rT   itypez.Either index or value subset can be requested.c              3   2   K   | ]  }t        |        y wN)int).0xs     r/   	<genexpr>zeigh.<locals>.<genexpr>  s     2/Q#a&/s   z?Requested eigenvalue indices are not valid. Valid range is [0, z] and start <= end, but start=z, end=z	 is givenI)rM   iliuz^Requested eigenvalue bounds are not valid. Valid range is (-inf, inf) and low < high, but low=z, high=)rM   rX   vuhesy)r   r   r   zK requires input b array to be supplied for generalized eigenvalue problems.)r   r   r   r   "zA" does not accept input b array for standard eigenvalue problems.)r   r   r   r   z'" cannot compute subsets of eigenvaluesr   r   r   rB   liwork)rB   r   lrwork)rB   r   r   )syevdsyevrheevdheevr_lwork)nrx   r   	compute_v)rx   r   rr   )uplo)r   jobz)rr   rs   r'   zIllegal value in argument z of internal zThe 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}).zInternal Error.)r   r   r   r   )r   r   r   )r   r   r   )r   r    )rp   formatjoinr   ro   rN   rq   r   r(   r   r%   r5   r   r   updater   r!   r"   
isinstancetupledictzipr   rI   )%rr   rs   rx   ry   rS   rT   rz   rc   r{   r|   r}   r   _jobdrv_strrO   rt   v_nr*   r,   cplxr   drv_argsrP   subsetlohipfx
lwork_specdrvdrvlwclw_argslw
lwork_args
other_argsr[   drv_errmsgs%                                        r/   r   r     s   L 3SD3CDCGW "F66;;wqr{+CDF 	F 
AL	9B
288}RXXa[BHHQK7566 
ww!|q12SMM"D		:MM"F#))<Ha4K5+b!"4K#4D
A{+H}=!7[Q%7rxx=A!!;9::88rxx2288*L
STTy GHH#B'tdmedCDT)Kd/JF ?IJJ 2/2BR!2!! 334Q3% 8&&(Tt9> ? ? 	#R!V26BC B&R&3& $$&4wrd)= > > 	#Rr:; $DC 9&$88x (D D E EM*E Eq )A A B Bv!;;q(OPQQ )6%u $X.#X.88	J 	y%sV|SZ5H&I')d,
UU+U?OO[ts{!BCE.X.b% c*SZ"8"=>J!2J%43;aANO"%"E"Eh"E*"E1z4 U?"3;R9CJ)3<VH9L*M+-r(4JC  qt4B!2Jt45"%"Kb"KH"K
"K1z4 $.:a=A!'!^jm^
1A qyHa4K"9 :D5'!$!3f!< =? @ @AX ;DF8 D? ? @ @
J DJ 0G %dm**40 c"" >)en++D1 c"" >)!$-..t4C c""	 "%.//ac:C c"" enc""r1   rd   )	r   r   rd   r6   valueindexrr   r,   r.   c                 |   t        | t              r| j                         } 	 t        |    } d\  }}dx}}| dk7  rt        |      }	|	j                  dk7  s|	j                  dk7  s|	d   |	d   k  rt        d      | dk(  r|	\  }}|dk(  r|}n|	j                  j                  j                         dvr0t        d	|	j                   d
|	j                  j                   d      |	dz   \  }}t        ||      dk  st        ||      |kD  rt        d      ||z
  dz   }| |||||fS # t        $ r}t        d      |d}~ww xY w)z5Check that select is valid, convert to Fortran style.zinvalid argument for selectN)rE         ?r   r   rd   zBselect_range must be a 2-element array-like in nondecreasing orderhilqpzEwhen using select="i", select_range must contain integers, got dtype z ()zselect_range out of bounds)r   strrx   
_conv_dictKeyErrorrp   r   ndimrq   r%   rL   minmax)
selectselect_rangemax_evmax_lenerX   r   r   r   srs
             r/   _check_selectr   r  s[   &#?F# FBKB{\"77a<277a<2a52a5= 6 7 7Q;FB{ xx}}""$G3 33588*Brxx}}oQP 
 !VFB2r{Q#b"+"7 !=>>"Wq[F2r2r6))1  ?67Q>?s   	D! !	D;*D66D;c                    |s|rt        | |      }|xs t        ||       }nUt        |       }t        |j                  j
                  t              r$t        |      j                         st        d      d}t        |j                        dk7  rt        d      |j                  dk(  rt        t        j                  ddgddgg|j                              \  }	}
t        j                  |d|	j                  	      }t        j                  |d
|
j                  	      }|r|S ||fS t!        ||||j                  d         \  }}}}}}~|dk(  r?|j                  j"                  dv rd}nd}t%        |f|f      \  } ||| ||      \  }}}n|rd}|j                  j"                  dv rt%        dt        dd      f      \  }nt%        dt        dd      f      \  }d |d      z  }|j                  j"                  dv rd}nd}t%        |f|f      \  } ||||||| |||||      \  }}}}}|d| }|s|ddd|f   }t'        ||       |r|S ||fS )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])

    rb   z#array must not contain infs or NaNsr   rd   zexpected a 2-D arrayr   r$   rf   rg   rh   GFDhbevdsbevd)r   rx   overwrite_abfF)lamchfdshbevxsbevx)r   mmaxrM   rx   r   abstolN)r   r   r   
issubclassr%   rz   r   r   r6   rp   ro   rN   rq   r   r(   r5   r   rL   r!   rK   )a_bandrx   ry   overwrite_a_bandr   r   r   rc   rO   rt   r   r*   r,   rX   r   r   r   internal_namebevdr[   r   r   bevxr-   ifails                            r/   r   r     sj   X '\B+HB0G6]bhhmmW-hrl6F6F6HBCC
288}/00 
ww!|bhhAA'7rxxHISMM"D		:MM"F#))<Ha4K%2fbhhqk&3"FBBF 	{88==E!
 $M
 $M -!1B59"L(8 %4DF
1d F88==D %j5#3F2HIFE%j5#3F2HIFEU3Z88==E!#M#M -!1B59#BBl*:4D 1a
 bqE!RaR%Am$a4Kr1   c           	      &    t        | |dd|||      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   )rs   rQ   rR   rS   rc   r;   )r   )rr   rs   rS   rc   r;   s        r/   r   r   F  s"    L qAAQK(#68 8r1   )rx   rS   rT   rz   rc   r{   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)
rs   rx   ry   rS   rT   rz   rc   r{   r|   r}   )r   )
rr   rs   rx   rS   rT   rz   rc   r{   r|   r}   s
             r/   r   r     s+    ` Qe$K'd / r1   c           	      &    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   )rx   ry   r   r   r   rc   )r   )r   rx   r   r   r   rc   s         r/   r   r     s$    p fE'7#/lL Lr1   c           
      (    t        | |d|||||      S )ac
  
    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',
        or 'stev'. When 'auto' (default), it will use 'stemr' 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)ry   r   r   rc   tollapack_driver)r   )r   r   r   r   rc   r   r   s          r/   r	   r	   d  s&    X 	14\!s-I Ir1   c                 R   t        | |      } t        ||      }| |fD ]?  }|j                  dk7  rt        d      |j                  j                  dv s6t        d       | j                  |j                  dz   k7  r&t        d| j                   d|j                   d      t        ||d	| j                        \  }}	}
}}}t        |t              st        d
      d}||vrt        d| d|       |dk(  r	|d	k(  rdnd}t        |       dk(  rv|dk(  r5|	| d	   cxk  r|
k  s'n t        g       }t        dd	g| j                        }n4t        | d	   g| j                        }t        dgg| j                        }|r|S ||fS t        |f| |f      \  }| }|dk(  r5|d	k7  rt        d      |st        d       || |      \  }}t        |      }n|dk(  r+|d	k7  rt        d       || ||      \  }}}t        |      }n|dk(  r;t        |      }d}t        |f| |f      \  }|rdnd} || |||	|
||||	      \  }}}}}not        |j                  dz   |j                        }||dd t        d| |f      \  } || |||	|
|||      \  }}}t        |d        || |||	|
|||||
      \  }}}}t        ||d z          |d| }|r|S |dk(  rJt        d!| |f      \  } || ||      \  }}t        |d"d#$       t!        |      }||   |dd|f   }}||fS ddd|f   }||fS )%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',
        or 'stev'. When 'auto' (default), it will use 'stemr' 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
    rb   r   zexpected a 1-D arrayr   z$Only real arrays currently supportedzd (z%) must have one more element than e (r   r   zlapack_driver must be str)autostemrsterfstebzstevzlapack_driver must be one of z, got r   r   r   r$   r   r   z)sterf can only be used when select == "a"z0sterf can only be used when eigvals_only is Truer   z(stev can only be used when select == "a")r   EBNr'   )stemr_lworkr   )r   rB   r   z (eigh_tridiagonal))steinzstein (eigh_tridiagonal)z"%d eigenvectors failed to convergerm   )r   r   rp   r%   rL   	TypeErrorrq   r   r   r   ro   r   r   r!   floatrK   r   )r   r   ry   r   r   rc   r   r   checkrX   r   r   r   _driversr*   r,   funcr   r[   r-   r   r   orderiblockisplite_r   rB   r   s                                 r/   r   r     s   x 	1<8A1<8AQ::?344;;u$BCC	 
 	vv!3qvvh&KAFF8STUVV -a!)FBBAmS)3449GG#8	 B  -0 1 	1#)Q;G 1v{Q;adbb	Aq!fAGG,AqtfAGG,AtfAGG,AHa4Km-1v6ED  IQ;HII $ % %q!*4F	&	 Q;GHH!Q)4
1dF	'	!Cj!="2QF; $%*1aRR+0&2"1ffd 166!8QWW%3B'(81a&A)!RRR4=?vtD-(QFBB'0fN1am&;;<	"1A G#$Z!Q8ED1aFF3GAt8!EG AJEU8Qq%x[qA !t !RaR%A!tr1   c                 f    | dk  rt        d|  |fz        | dkD  r|rt        d|z   || fz        yy)zCheck info return value.r   z+illegal value in argument %d of internal %sz%s N)rp   r   )r[   r}   rn   s      r/   rK   rK   h  sP    axF!E6?+ , 	,axH58+>?? xr1   c                    t        | |      }t        |j                        dk7  s|j                  d   |j                  d   k7  rt        d      |xs t	        ||       }|j
                  dk(  rt        t        j                  d|j                              }t        j                  |j                  |j                        }|s|S t        t        j                  d|j                        d	      \  }}t        j                  |j                  |j                        }t        j                  |j                  |j                        }||fS |j                  d   dk  r|r|t        |j                  d         fS |S t        d
|f      \  }	}
} |
|d|      \  }}}}}t        |dd       t        |      }t        ||j                  d   ||      } |	||||d      \  }}}t        |dd       t        j                  |d      }|s|S t        d|f      \  }}t        ||||      } ||||||d      \  }}t        |dd       ||fS )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
    rb   rd   r   r   re   r   r$   T)calc_q)gehrdgebalgehrd_lwork)permuterS   zgebal (hessenberg)Frm   )r   r   )r   r   rB   rS   zgehrd (hessenberg)r'   )orghrorghr_lwork)rr   taur   r   rB   rS   zorghr (hessenberg))r   ro   rN   rp   r   rq   r
   r(   r   r%   r   r!   rK   r"   triu)rr   r  rS   rc   rO   h3hq3qr  r  r  bar   r   pivscaler[   r   rB   hqr	  r  r  s                          r/   r
   r
   q  s   ^ 
AL	9B
288}bhhqkRXXa[81225+b!"4K	ww!|q12HHRXXRXX.Hq 9$GFB2A2Aa4K 
xx{as288A;'''	 0 2ACE%!IE5+!&r1+!NBB$*U;BA;rBE"%QGMBT*U;
BA **BREJE;;bR8EbcbRu!LGAt*U;a4Kr1   c                    t        |       t        |      }} | j                  dk  rt        d      |j                  dk  rt        d      |j                  | j                  dz   k7  rt        d      | j                  d   }| j                  dd }|j                  d   |j                  d   k7  rt        d	      |j                  d   |k7  rt        d
      t	        |       }|j                  d      }|dz  dk(  j                         st        d      t        |      }|dd }|d   }|ddd   }	|ddd   }
d}|D ]4  }|ddd   |ddd   k(  j                         sJ d       ||ddd   fz  }6 t        |||fz   | j                  j                        }t        |      }| j                  |d||f<   | ||	fz      j                  |||	|
fz   <   | ||
fz      j                  |||
|	fz   <   t        |||fz   t        j                        }d|d||f<   d|||	|	fz   <   d|||	|
fz   <   d|||
|	fz   <   d|||
|
fz   <   t        d||      j                  }||fS )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]])
    r   zexpected w to be at least 1Drd   zexpected v to be at least 2DzUexpected eigenvectors array to have exactly one dimension more than eigenvalues arrayr'   NrC   zVexpected 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 eigenvaluesr   z(Conjugate pair spanned different arrays!r$   .r   y              ?g      ?y             z...ij,...jk->...ik)r   r   rp   rN   r   sumr6   r   r   rF   r%   rM   r)   r(   cdoubler   )r*   r,   r   Mcomplex_mask	n_complexidx	idx_stackidx_elemjk	stack_indr.   rv   diurY   s                    r/   r   r     s   f a "4Q"7qA 	vvz788vvz788vv! A B 	B 	
A	Awwr{aggbk! ? @ 	@wwr{a ( ) 	) Q<L  b )I MQ##%JKK ,
CCRI2wH 	AAAAI!$Q$1QTT7"'') 	;:	;)a1gZ		  
qAq6z	.B	qBffBsB{O yA4/055ByAq6yA4/055ByAq6 	a1a&j

+AAc2rkN Ai1a&Ai1a&!Ai1a&Ai1a& 
$a	+	0	0Br6Mr1   )NFTFFTFr   )FFFrr   Nr   T)NFTF)FFrr   NT)rr   NTrE   r   )Frr   NTrE   r   )z!did not converge (LAPACK info=%d))FFT),__all__numpyr(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   scipy._lib._utilr   _miscr   r   r    lapackr!   r"   rJ   r0   r?   r`   r   r   r   r   r   r   r   r   r	   r   rK   r
   r   r   r1   r/   <module>r&     s4  P 7 7 7 7 7 0 1 1 4 RXXb4'T 8=BGfRO#T5tdO#d
 qQQ11&

*B JOEIpf 8< %H8Vs5QT4!$sl :??CZLz 9=BHNIb IM>Dpf@YxSr1   