
    (ph5)                       S SK r S SK Jr  S SKJr  S SKrS SKJrJr  SSKJ	r	J
r
  SSKJrJrJr  SSKJr  SS	KJrJr  SS
KJr  SSKJrJrJrJr  / SQr\R6                  S    V Vs0 s H>  n U SR9                  S Vs/ s H  n\R;                  X5      (       d  M  UPM     sn5      _M@     snn rS,S jrS r    S-S jr!S r"S r#S r$S r%S r&S r'  S.S jr(  S/S jr)  S0S jr*  S1S jr+S2S jr,S  r-  S3S! jr.S4S" jr/S4S# jr0  S5S$ jr1S%\1l2        SSSSS&.S' jr3  S6S( jr4  S7S) jr5 S2S* jr6S8S+ jr7gs  snf s  snn f )9    N)warn)product)
atleast_1d
atleast_2d   )get_lapack_funcs_compute_lwork)LinAlgError_datacopiedLinAlgWarning)_asarray_validated)_decomp_decomp_svd)levinson)find_det_from_lu	bandwidthissymmetricishermitian)solvesolve_triangularsolveh_bandedsolve_bandedsolve_toeplitzsolve_circulantinvdetlstsqpinvpinvhmatrix_balancematmul_toeplitzAll fdFDc                     US:  a  [        SU*  S35      eSU:  a  [        S5      eUc  gU" S5      nX4:  a  [        SUS S	3[        S
S9  gg)zACheck arguments during the different steps of the solution phase r   z$LAPACK reported an illegal value in z-th argument.zMatrix is singular.NEzIll-conditioned matrix (rcond=z.6gz): result may not be accurate.   
stacklevel)
ValueErrorr
   r   r   )ninfolamchrcondr&   s        F/var/www/html/venv/lib/python3.13/site-packages/scipy/linalg/_basic.py_solve_checkr0   %   sn    ax?wmTUU	
T/00}c
Ay-eC[ 9+ +q	*     c                 l   U R                   S   n[        U 5      u  p#X#s=:X  a  S:X  a  O  OSnOUS:X  a  SnOzUS:X  a  SnOqUS::  a  US::  a	  US:  a  SnO\[        R                  " U R                  [        R
                  5      (       a  [        U 5      (       a  SnO[        U 5      (       a  S	nOS
nXBU4$ )Nr   diagonallower triangularupper triangularr   r'   tridiagonal	hermitian	symmetricgeneral)shaper   np
issubdtypedtypecomplexfloatingr   r   )ar+   n_belown_abovekinds        r/   _find_matrix_structurerC   5   s    	
A |GQ	A!	A!	A'Q,1q5	qww 2 2	3	3A	Q'!!r1   FTc           
         Sn[        [        U SS95      n	[        [        USS95      n
[        X5      u  pU	R                  S   nU=(       d    [        X5      nU=(       d    [        X5      nU	R                  S   U	R                  S   :w  a  [        S5      eXR                  S   :w  a!  US:X  a  U
R                  S:w  d  [        S5      eU
R                  S:X  ad  [        [        R                  " SU	R                  S9[        R                  " SU
R                  S95      R                  n[        R                  " XS9$ U
R                  S:X  a  US:X  a
  U
S	S	S	24   n
O	U
S	S	2S	4   n
S
nUS;  a  [        U S35      eUS;   a  [        R                  " U	5      (       d  SnSu  pUc  [!        U	5      u  pmnU	R                  R"                  S;   a  [%        SSS9nO
[%        SSS9nUS:X  a  [&        nO%US:X  a  [(        nOUS;   a  [+        U5      nO[,        nU(       a+  SnSn[        R                  " U	5      (       a  [/        S5      eOSnSnU" UX5      nS[        R0                  nnUS;   aM  [%        SX45      u  nnnU" XS9u  nnn[3        UU5        U" UUU
UUS9u  nn[3        UU5        U" UUUS9u  nnGOUS;   aG  [%        SX45      u  nnn[5        UX5      nU" XUUUUS 9u  nnnn[3        UU5        U" UUU5      u  nnGOUS!;   aG  [%        S"X45      u  n n!n"[5        U"X5      nU!" XUUUUS 9u  nnnn[3        UU5        U " UUU5      u  nnGOPUS:X  ah  [        R6                  " U	5      n#U
R8                  U#-  R8                  n[        R:                  " U#5      n$U$R=                  5       U$R?                  5       -  nGOUS:X  a  U(       a  U	R8                  OU	n	[        R6                  " U	S#5      [        R6                  " U	S5      [        R6                  " U	S5      n'n&n%[%        S$X45      u  n(n)n*U(" U%U&U'5      u  n%n&n'n+n,n[3        UU5        U)" U%U&U'U+U,XS%9u  nn[3        UU5        U*" U%U&U'U+U,U5      u  nnGO(US&:X  a  U(       a  U	R8                  X4OXU4u  pnUc  [A        U	5      OX4u  p[C        XU	5      n-[%        S'X45      u  n.[        RD                  " SU-  U-   S-   U-R                  S   4U.R                  S9n/U-U/US	2S	S	24'   U." XU/U
S
US(9u    n0nn[3        UU5        OzUS;   a?  US):H  n[G        XX$US*9u  nn[3        UU5        [%        S+X45      n1U1" X(       a  S,OS-S.9u  nnO5[%        S/X45      u  n2n3U3" XUUUS09u  nnn[3        UU5        U2" UU5      u  nn[3        UUUU5        U(       a  URI                  5       nU$ )1a  
Solves the linear equation set ``a @ x == b`` for the unknown ``x``
for square `a` matrix.

If the data matrix is known to be a particular type then supplying the
corresponding string to ``assume_a`` key chooses the dedicated solver.
The available options are

===================  ================================
 diagonal             'diagonal'
 tridiagonal          'tridiagonal'
 banded               'banded'
 upper triangular     'upper triangular'
 lower triangular     'lower triangular'
 symmetric            'symmetric' (or 'sym')
 hermitian            'hermitian' (or 'her')
 positive definite    'positive definite' (or 'pos')
 general              'general' (or 'gen')
===================  ================================

Parameters
----------
a : (N, N) array_like
    Square input data
b : (N, NRHS) array_like
    Input data for the right hand side.
lower : bool, default: False
    Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``.
    If True, the calculation uses only the data in the lower triangle of `a`;
    entries above the diagonal are ignored. If False (default), the
    calculation uses only the data in the upper triangle of `a`; entries
    below the diagonal are ignored.
overwrite_a : bool, default: False
    Allow overwriting data in `a` (may enhance performance).
overwrite_b : bool, default: False
    Allow overwriting data in `b` (may enhance performance).
check_finite : bool, default: True
    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.
assume_a : str, optional
    Valid entries are described above.
    If omitted or ``None``, checks are performed to identify structure so the
    appropriate solver can be called.
transposed : bool, default: False
    If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
    for complex `a`.

Returns
-------
x : (N, NRHS) ndarray
    The solution array.

Raises
------
ValueError
    If size mismatches detected or input a is not square.
LinAlgError
    If the matrix is singular.
LinAlgWarning
    If an ill-conditioned input a is detected.
NotImplementedError
    If transposed is True and input a is a complex matrix.

Notes
-----
If the input b matrix is a 1-D array with N elements, when supplied
together with an NxN input a, it is assumed as a valid column vector
despite the apparent size mismatch. This is compatible with the
numpy.dot() behavior and the returned result is still 1-D array.

The general, symmetric, Hermitian and positive definite solutions are
obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
LAPACK respectively.

The datatype of the arrays define which solver is called regardless
of the values. In other words, even when the complex array entries have
precisely zero imaginary parts, the complex solver will be called based
on the data type of the array.

Examples
--------
Given `a` and `b`, solve for `x`:

>>> import numpy as np
>>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
>>> b = np.array([2, 4, -1])
>>> from scipy import linalg
>>> x = linalg.solve(a, b)
>>> x
array([ 2., -2.,  9.])
>>> np.dot(a, x) == b
array([ True,  True,  True], dtype=bool)

Fcheck_finiter   r   z$Input a needs to be a square matrix.z2Input b has to have same number of rows as input a   r=   NT>   Ngenherpossymbandedr9   r3   r7   r8   r6   r4   r5   positive definitez% is not a recognized matrix structure>   rJ   r7   r8   NNfFr-   fdr3   r6   >   r4   r5   IzWscipy.linalg.solve can currently not solve a^T x = b or a^H x = b for complex matrices.1>   rI   r9   )gecongetrfgetrsoverwrite_a)transoverwrite_b)norm)heconhesv
hesv_lwork)lworklowerrY   r[   >   rL   r8   )syconsysv
sysv_lwork)gttrfgttrsgtcon)r[   rM   gbsvoverwrite_abr[   r4   )ra   r[   rZ   trconLU)uplo)poconposv)ra   rY   r[   )%r   r   r   _ensure_dtype_cdszr:   r   r*   sizer   r;   eyer=   ones
empty_likendimiscomplexobjrC   charr   _matrix_norm_diagonal_matrix_norm_tridiagonal_matrix_norm_triangular_matrix_norm_generalNotImplementedErrorinfr0   r	   diagTabsminmaxr   
_to_bandedzeros_solve_triangularravel)4r?   bra   rY   r[   rF   assume_a
transposedb_is_1Da1b1r+   dtr@   rA   r-   _matrix_normrZ   r\   anormr,   r.   rU   rV   rW   luipvtxr]   r^   hesv_lwr`   rb   rc   sysv_lwdiag_a
abs_diag_adlrR   du_gttrf_gttrs_gtcondu2ipivabrj   a2__trconrq   rr   s4                                                       r/   r   r   K   s*   F G 
&qu=	>B	&qu=	>B'FB
A3R!3K3R!3K	xx{bhhqk!?@@HHQKQ277a< ' ( ( 
ww!|266!288,bggarxx.HIOO}}R** 
ww!|6D!GBAtGB T T H:%JKLL ''0C0C!G%;B%?"7
 
xx}} 4 4
 :,	]	"/	=	=.x8+ ??2% '> ? ? 
 r0ERVV%D %%./J02x9uer;D$QD"#>4QBD1t	)	)/ 1?AC JtWw1 u',-8-8:D!T 	QBe,t	)	)/ 1?AC JtWw1 u',-8-8:D!T 	QBe,t	Z	TTF]VVF^
 :>>#33	]	"RTTRGGBORWWR^RWWR^rA!12MPRx!X%+B2%6"Ar3dQQCrK4QRBT59t	X	<Fw 8&(7%; 	W,3O9R='AS"- RH5XXqy7*Q.<DJJO78Q;Wr2*.KI1aQ 
=	=..#B%*464Q!7bX6RUc<t ''8(*x1t2'2'24At 	QB&tD%'GGIHr1   c                     [         R                  " U5      nU(       a  [         R                  " U5      OUn[         R                  " U5      R	                  5       $ N)r;   r   asarray_chkfiniter   r   )r   r?   rF   rR   s       r/   r{   r{   \  s9     	
A#/QQA66!9==?r1   c                    U S:X  a  UR                   n[        R                  " SS9   [        R                  " [        R                  " U5      5      nUSS === [        R                  " [        R                  " US5      5      -  sss& US S=== [        R                  " [        R                  " US5      5      -  sss& S S S 5        U(       a  [        R
                  " W5      OWnUR                  5       $ ! , (       d  f       N== f)NrS   ignore)invalidr   re   )r   r;   errstater   r   r   r   )r\   r?   rF   rR   s       r/   r|   r|   d  s     s{CC	X	&FF2771:	!"1&&	#2"&&B(( 
' $0QQA557N 
'	&s   BC77
Dc                    ^  U 4S jnU$ )Nc                    > U(       a  [         R                  " U5      OUn[        SU45      nU" XTS:X  a  S5      $ S5      $ )Nlantrr4   rn   ro   r;   r   r   )r\   r?   rF   r   	structures       r/   fun$_matrix_norm_triangular.<locals>.funs  sB    '3B  # 1$/TY2D%DcOO#OOr1    )r   r   s   ` r/   r}   r}   r  s    P Jr1   c                 j    U(       a  [         R                  " U5      OUn[        SU45      nU" X5      $ )Nlanger   )r\   r?   rF   r   s       r/   r~   r~   z  s.    #/QQAWqd+E>r1   c                 z   UR                   S   nX-   S-   n[        R                  " XC4UR                  S9n[        R                  " U5      XQ'   [        SUS-   5       H"  n[        R                  " X&5      XQU-
  US 24'   M$     [        SU S-   5       H$  n[        R                  " X&* 5      XQU-   S U* 24'   M&     U$ )Nr   r   rH   )r:   r;   r   r=   r   range)r@   rA   r?   r+   rowsr   is          r/   r   r     s    	
Aq D	4)177	+B''!*BK1gk" ggamQ;? #1gk"!wwq"~Q;! #Ir1   c                     ^ [         R                  " U 6 m[         R                  " T[         R                  5      (       d	  S U  5       $ [         R                  " T[         R                  5      n[         R
                  " T5      R                  S::  a(  U(       a  [         R                  O[         R                  mOK[         R
                  " T5      R                  S:  a'  U(       a  [         R                  O[         R                  mU4S jU  5       $ )Nc              3   ^   #    U  H#  oR                  [        R                  5      v   M%     g 7fr   )astyper;   float64).0arrays     r/   	<genexpr>%_ensure_dtype_cdsz.<locals>.<genexpr>  s     =fURZZ((fs   +-    @   c              3   B   >#    U  H  oR                  TS S9v   M     g7f)FcopyN)r   )r   r   r=   s     r/   r   r     s     @LLUL+s   )r;   result_typer<   inexactr>   finfobits	complex64float32
complex128r   )arrayscomplexr=   s     @r/   rs   rs     s     NNF#E==

++=f==mmE2#5#56G	xxr! 'RZZ	%			#!(bjj@@@r1   c                 l   [        XS9n[        XS9n[        UR                  5      S:w  d   UR                  S   UR                  S   :w  a  [        S5      eUR                  S   UR                  S   :w  a&  [        SUR                   SUR                   S35      eUR                  S:X  ad  [        [        R                  " SUR                  S	9[        R                  " SUR                  S	95      R                  n	[        R                  " XS	9$ U=(       d    [        X5      n[        XxX#XE5      u  pU
$ )
a  
Solve the equation ``a x = b`` for `x`, assuming a is a triangular matrix.

Parameters
----------
a : (M, M) array_like
    A triangular matrix
b : (M,) or (M, N) array_like
    Right-hand side matrix in ``a x = b``
lower : bool, optional
    Use only data contained in the lower triangle of `a`.
    Default is to use upper triangle.
trans : {0, 1, 2, 'N', 'T', 'C'}, optional
    Type of system to solve:

    ========  =========
    trans     system
    ========  =========
    0 or 'N'  a x  = b
    1 or 'T'  a^T x = b
    2 or 'C'  a^H x = b
    ========  =========
unit_diagonal : bool, optional
    If True, diagonal elements of `a` are assumed to be 1 and
    will not be referenced.
overwrite_b : bool, optional
    Allow overwriting data in `b` (may enhance 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.

Returns
-------
x : (M,) or (M, N) ndarray
    Solution to the system ``a x = b``.  Shape of return matches `b`.

Raises
------
LinAlgError
    If `a` is singular

Notes
-----
.. versionadded:: 0.9.0

Examples
--------
Solve the lower triangular system a x = b, where::

         [3  0  0  0]       [4]
    a =  [2  1  0  0]   b = [2]
         [1  0  1  0]       [4]
         [1  1  1  1]       [2]

>>> import numpy as np
>>> from scipy.linalg import solve_triangular
>>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
>>> b = np.array([4, 2, 4, 2])
>>> x = solve_triangular(a, b, lower=True)
>>> x
array([ 1.33333333, -0.66666667,  2.66666667, -1.33333333])
>>> a.dot(x)  # Check the result
array([ 4.,  2.,  4.,  2.])

rE   rG   r   r   expected square matrixzshapes of a  and b  are incompatiblerH   )r   lenr:   r*   rt   r   r;   ru   r=   rv   rw   r   r   )r?   r   rZ   ra   unit_diagonalr[   rF   r   r   dt_nonemptyr   r   s               r/   r   r     s    J 
A	9B	A	9B
288}RXXa[BHHQK7122	xx{bhhqk!<z
BSTUU 
ww!|&FF1BHH%rwwq'A

% 	 }}R333R!3KRU=NDAHr1   c           	      @   SSSS.R                  X"5      n[        SX45      u  nU R                  R                  (       d  US:X  a  U" XXSX$S9u  pxO U" U R                  XU(       + U(       + US9u  pxUS:X  a  Xx4$ US:  a  [        SUS-
  -  5      e[        SU* -  5      e)	Nr   r   rG   )Nr   C)trtrs)r[   ra   rZ   unitdiagz1singular matrix: resolution failed at diagonal %dz0illegal value in %dth argument of internal trtrs)getr   flagsf_contiguousr   r
   r*   )	r   r   rZ   ra   r   r[   r   r   r,   s	            r/   r   r     s     !!$((6Ej2(3FE	xx
K#=4 bU"'i-A qywaxM6# $ 	$
Ge  r1   c           
      F   [        XSS9n[        X%SS9nUR                  S   UR                  S   :w  a  [        S5      eU u  pX-   S-   UR                  S   :w  a"  [        SX-   S-   UR                  S   4-  5      eUR                  S:X  ad  [	        [
        R                  " SUR                  S9[
        R                  " SUR                  S95      R                  n
[
        R                  " XzS9$ U=(       d    [        Xr5      nUR                  S   S:X  a$  [
        R                  " Xt(       + S	9nXU	S4   -  nU$ Xs=:X  a  S:X  aR  O  OOU=(       d    [        Xa5      n[        S
Xg45      u  nUSSS24   nUSSS24   nUSSS24   nU" XXX3X45      u  npnnO`[        SXg45      u  n[
        R                  " SU-  U	-   S-   UR                  S   4UR                  S9nUUUS2SS24'   U" XUUSUS9u  nnnnUS:X  a  U$ US:  a  [        S5      e[        SU* -  5      e)a  
Solve the equation a x = b for x, assuming a is banded matrix.

The matrix a is stored in `ab` using the matrix diagonal ordered form::

    ab[u + i - j, j] == a[i,j]

Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::

    *    a01  a12  a23  a34  a45
    a00  a11  a22  a33  a44  a55
    a10  a21  a32  a43  a54   *
    a20  a31  a42  a53   *    *

Parameters
----------
(l, u) : (integer, integer)
    Number of non-zero lower and upper diagonals
ab : (`l` + `u` + 1, M) array_like
    Banded matrix
b : (M,) or (M, K) array_like
    Right-hand side
overwrite_ab : bool, optional
    Discard data in `ab` (may enhance performance)
overwrite_b : bool, optional
    Discard data in `b` (may enhance 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.

Returns
-------
x : (M,) or (M, K) ndarray
    The solution to the system a x = b. Returned shape depends on the
    shape of `b`.

Examples
--------
Solve the banded system a x = b, where::

        [5  2 -1  0  0]       [0]
        [1  4  2 -1  0]       [1]
    a = [0  1  3  2 -1]   b = [2]
        [0  0  1  2  2]       [2]
        [0  0  0  1  1]       [3]

There is one nonzero diagonal below the main diagonal (l = 1), and
two above (u = 2). The diagonal banded form of the matrix is::

         [*  * -1 -1 -1]
    ab = [*  2  2  2  2]
         [5  4  3  2  1]
         [1  1  1  1  *]

>>> import numpy as np
>>> from scipy.linalg import solve_banded
>>> ab = np.array([[0,  0, -1, -1, -1],
...                [0,  2,  2,  2,  2],
...                [5,  4,  3,  2,  1],
...                [1,  1,  1,  1,  0]])
>>> b = np.array([0, 1, 2, 2, 3])
>>> x = solve_banded((1, 2), ab, b)
>>> x
array([-2.37288136,  3.93220339, -4.        ,  4.3559322 , -1.3559322 ])

T)rF   
as_inexactre   r   &shapes of ab and b are not compatible.r   zfinvalid values for the number of lower and upper diagonals: l+u+1 (%d) does not equal ab.shape[0] (%d)rH   r   )gtsvNrG   ri   rk   singular matrixz5illegal value in %d-th argument of internal gbsv/gtsv)r   r:   r*   rt   r   r;   ru   r=   rv   rw   r   r   r   r   r
   )l_and_ur   r   rl   r[   rF   r   r   nlowernupperr   b2r   r   rR   r   r   r   r,   rj   r   r   pivs                          r/   r   r     sA   L 
Bd	KB	AT	JB 
xx|rxx{"ABBVbhhqk)  #)?Q#6"DE F 	F
 
ww!|266!288,bggarxx.HIOO}}R**3R!3K	xx|qXXb1 	m	1#:{2': RH512Yq!tH3B3Z"2",#/>QAt !RH5XXqx&(1,bhhqk:$**M67A:BT,79CDqyax+,,
 !$(5) * *r1   c                 <   [        XS9n[        XS9nUR                  S   UR                  S   :w  a  [        S5      eUR                  S:X  ad  [	        [
        R                  " SUR                  S9[
        R                  " SUR                  S95      R                  n[
        R                  " XxS9$ U=(       d    [        Xq5      nU=(       d    [        X`5      nUR                  S   S:X  al  [        SXg45      u  n	U(       a  USS	S	24   R                  n
USS	S24   nO*USS	S	24   R                  n
USSS	24   R                  5       nU	" XXrUU5      u  ppO[        S
Xg45      u  nU" XgXBUS9u  npUS:  a  [        SU-  5      eUS:  a  [        SU* -  5      eU$ )a  
Solve equation a x = b. a is Hermitian positive-definite banded matrix.

Uses Thomas' Algorithm, which is more efficient than standard LU
factorization, but should only be used for Hermitian positive-definite
matrices.

The matrix ``a`` is stored in `ab` either in lower diagonal or upper
diagonal ordered form:

    ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
    ab[    i - j, j] == a[i,j]        (if lower form; i >= j)

Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
``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
----------
ab : (``u`` + 1, M) array_like
    Banded matrix
b : (M,) or (M, K) array_like
    Right-hand side
overwrite_ab : bool, optional
    Discard data in `ab` (may enhance performance)
overwrite_b : bool, optional
    Discard data in `b` (may enhance performance)
lower : bool, optional
    Is the matrix in the lower form. (Default is upper form)
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
-------
x : (M,) or (M, K) ndarray
    The solution to the system ``a x = b``. Shape of return matches shape
    of `b`.

Notes
-----
In the case of a non-positive definite matrix ``a``, the solver
`solve_banded` may be used.

Examples
--------
Solve the banded system ``A x = b``, where::

        [ 4  2 -1  0  0  0]       [1]
        [ 2  5  2 -1  0  0]       [2]
    A = [-1  2  6  2 -1  0]   b = [2]
        [ 0 -1  2  7  2 -1]       [3]
        [ 0  0 -1  2  8  2]       [3]
        [ 0  0  0 -1  2  9]       [3]

>>> import numpy as np
>>> from scipy.linalg import solveh_banded

``ab`` contains the main diagonal and the nonzero diagonals below the
main diagonal. That is, we use the lower form:

>>> ab = np.array([[ 4,  5,  6,  7, 8, 9],
...                [ 2,  2,  2,  2, 2, 0],
...                [-1, -1, -1, -1, 0, 0]])
>>> b = np.array([1, 2, 2, 3, 3, 3])
>>> x = solveh_banded(ab, b, lower=True)
>>> x
array([ 0.03431373,  0.45938375,  0.05602241,  0.47759104,  0.17577031,
        0.34733894])


Solve the Hermitian banded system ``H x = b``, where::

        [ 8   2-1j   0     0  ]        [ 1  ]
    H = [2+1j  5     1j    0  ]    b = [1+1j]
        [ 0   -1j    9   -2-1j]        [1-2j]
        [ 0    0   -2+1j   6  ]        [ 0  ]

In this example, we put the upper diagonals in the array ``hb``:

>>> hb = np.array([[0, 2-1j, 1j, -2-1j],
...                [8,  5,    9,   6  ]])
>>> b = np.array([1, 1+1j, 1-2j, 0])
>>> x = solveh_banded(hb, b)
>>> x
array([ 0.07318536-0.02939412j,  0.11877624+0.17696461j,
        0.10077984-0.23035393j, -0.00479904-0.09358128j])

rE   re   r   r   r   rH   rG   )ptsvN)pbsv)ra   rl   r[   z(%dth leading minor not positive definitez/illegal value in %dth argument of internal pbsv)r   r:   r*   rt   r   r;   ru   r=   rv   rw   r   r   realconjr
   )r   r   rl   r[   ra   rF   r   r   r   r   rR   er   r   r,   r   cs                    r/   r   r     s   N 
B	:B	A	9B 
xx|rxx{"ABB 
ww!|266!288,bggarxx.HIOO}}R**3R!3K6;r#6L	xx{a RH51a4A1crc6
A1a4A1ab5	 AaBl)+q$ !RH5"&13
1axDtKLLax  #'%( ) 	)Hr1   c                 "   [        XUSS9u  p4pnUR                  S:X  a  [        R                  " U5      $ [        R                  " USSS2   U45      nUc  [        S5      eUR                  S:X  a$  [        U[        R                  " U5      5      u  pU$ [        R                  " [        UR                  S   5       V
s/ s H-  n
[        U[        R                  " USS2U
4   5      5      S   PM/     sn
5      nUR                  " U6 nU$ s  sn
f )aw  Solve a Toeplitz system using Levinson Recursion

The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.

.. warning::

    Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
    not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
    before passing them to `solve_toeplitz`.

Parameters
----------
c_or_cr : array_like or tuple of (array_like, array_like)
    The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
    supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
    real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
    of the Toeplitz matrix is ``[c[0], r[1:]]``.
b : (M,) or (M, K) array_like
    Right-hand side in ``T x = b``.
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
    (result entirely NaNs) if the inputs do contain infinities or NaNs.

Returns
-------
x : (M,) or (M, K) ndarray
    The solution to the system ``T x = b``. Shape of return matches shape
    of `b`.

See Also
--------
toeplitz : Toeplitz matrix

Notes
-----
The solution is computed using Levinson-Durbin recursion, which is faster
than generic least-squares methods, but can be less numerically stable.

Examples
--------
Solve the Toeplitz system T x = b, where::

        [ 1 -1 -2 -3]       [1]
    T = [ 3  1 -1 -2]   b = [2]
        [ 6  3  1 -1]       [2]
        [10  6  3  1]       [5]

To specify the Toeplitz matrix, only the first column and the first
row are needed.

>>> import numpy as np
>>> c = np.array([1, 3, 6, 10])    # First column of T
>>> r = np.array([1, -1, -2, -3])  # First row of T
>>> b = np.array([1, 2, 2, 5])

>>> from scipy.linalg import solve_toeplitz, toeplitz
>>> x = solve_toeplitz((c, r), b)
>>> x
array([ 1.66666667, -1.        , -2.66666667,  2.33333333])

Check the result by creating the full Toeplitz matrix and
multiplying it by `x`.  We should get `b`.

>>> T = toeplitz(c, r)
>>> T.dot(x)
array([ 1.,  2.,  2.,  5.])

T)keep_b_shaper   re   Nz)illegal value, `b` is a required argumentr   )_validate_args_for_toeplitz_opsrt   r;   rw   concatenater*   rx   r   ascontiguousarraycolumn_stackr   r:   reshape)c_or_crr   rF   rr   r=   b_shapevalsr   r   r   s              r/   r   r     s   X >Lt5A!G 	vv{}}Q >>1R"W:q/*DyDEEvv{b22156 H	 OO&+AGGAJ&79&7 &dB,@,@1a4,IJ1M&79 :IIwH	9s    4Dc                     UnUS:  a  X1R                   -  nSUs=::  a  UR                   :  a  O  OUR                  U   $ [        SU  S35      e)Nr   'zaxis' entry is out of bounds)rx   r:   r*   )anamer?   axisaxs       r/   _get_axis_lenr   t  sM    	B	Av
ffBwwr{
q;<
==r1   c                    [         R                  " U 5      n [        SX5      n[         R                  " U5      n[        SX5      nXx:w  a&  [        SU R                   SUR                   S35      eUR
                  S:X  ad  [        [         R                  " SU R                  S9[         R                  " SUR                  S95      R                  n	[         R                  " XS9$ [         R                  R                  [         R                  " XS	5      S	S
9n
[         R                  " U
5      nUc|  UR                  S	S
9U-  [         R                  " [         R                   5      R"                  -  nUR                  S:w  a  UR                  S-   Ul        O[         R                  " U5      nX:*  n[         R$                  " U5      nU(       a  US:X  a  ['        S5      eSX'   [         R                  R                  [         R                  " XS	5      S	S
9nX-  nU(       a!  [         R(                  " U[*        S9U-  nSUU'   [         R                  R-                  US	S
9n[         R.                  " U 5      (       d'  [         R.                  " U5      (       d  UR0                  nUS	:w  a  [         R                  " US	U5      nU$ )a  Solve C x = b for x, where C is a circulant matrix.

`C` is the circulant matrix associated with the vector `c`.

The system is solved by doing division in Fourier space. The
calculation is::

    x = ifft(fft(b) / fft(c))

where `fft` and `ifft` are the fast Fourier transform and its inverse,
respectively. For a large vector `c`, this is *much* faster than
solving the system with the full circulant matrix.

Parameters
----------
c : array_like
    The coefficients of the circulant matrix.
b : array_like
    Right-hand side matrix in ``a x = b``.
singular : str, optional
    This argument controls how a near singular circulant matrix is
    handled.  If `singular` is "raise" and the circulant matrix is
    near singular, a `LinAlgError` is raised. If `singular` is
    "lstsq", the least squares solution is returned. Default is "raise".
tol : float, optional
    If any eigenvalue of the circulant matrix has an absolute value
    that is less than or equal to `tol`, the matrix is considered to be
    near singular. If not given, `tol` is set to::

        tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps

    where `abs_eigs` is the array of absolute values of the eigenvalues
    of the circulant matrix.
caxis : int
    When `c` has dimension greater than 1, it is viewed as a collection
    of circulant vectors. In this case, `caxis` is the axis of `c` that
    holds the vectors of circulant coefficients.
baxis : int
    When `b` has dimension greater than 1, it is viewed as a collection
    of vectors. In this case, `baxis` is the axis of `b` that holds the
    right-hand side vectors.
outaxis : int
    When `c` or `b` are multidimensional, the value returned by
    `solve_circulant` is multidimensional. In this case, `outaxis` is
    the axis of the result that holds the solution vectors.

Returns
-------
x : ndarray
    Solution to the system ``C x = b``.

Raises
------
LinAlgError
    If the circulant matrix associated with `c` is near singular.

See Also
--------
circulant : circulant matrix

Notes
-----
For a 1-D vector `c` with length `m`, and an array `b`
with shape ``(m, ...)``,

    solve_circulant(c, b)

returns the same result as

    solve(circulant(c), b)

where `solve` and `circulant` are from `scipy.linalg`.

.. versionadded:: 0.16.0

Examples
--------
>>> import numpy as np
>>> from scipy.linalg import solve_circulant, solve, circulant, lstsq

>>> c = np.array([2, 2, 4])
>>> b = np.array([1, 2, 3])
>>> solve_circulant(c, b)
array([ 0.75, -0.25,  0.25])

Compare that result to solving the system with `scipy.linalg.solve`:

>>> solve(circulant(c), b)
array([ 0.75, -0.25,  0.25])

A singular example:

>>> c = np.array([1, 1, 0, 0])
>>> b = np.array([1, 2, 3, 4])

Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`.  For the
least square solution, use the option ``singular='lstsq'``:

>>> solve_circulant(c, b, singular='lstsq')
array([ 0.25,  1.25,  2.25,  1.25])

Compare to `scipy.linalg.lstsq`:

>>> x, resid, rnk, s = lstsq(circulant(c), b)
>>> x
array([ 0.25,  1.25,  2.25,  1.25])

A broadcasting example:

Suppose we have the vectors of two circulant matrices stored in an array
with shape (2, 5), and three `b` vectors stored in an array with shape
(3, 5).  For example,

>>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
>>> b = np.arange(15).reshape(-1, 5)

We want to solve all combinations of circulant matrices and `b` vectors,
with the result stored in an array with shape (2, 3, 5). When we
disregard the axes of `c` and `b` that hold the vectors of coefficients,
the shapes of the collections are (2,) and (3,), respectively, which are
not compatible for broadcasting. To have a broadcast result with shape
(2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
shape (2, 1, 5). The last dimension holds the coefficients of the
circulant matrices, so when we call `solve_circulant`, we can use the
default ``caxis=-1``. The coefficients of the `b` vectors are in the last
dimension of the array `b`, so we use ``baxis=-1``. If we use the
default `outaxis`, the result will have shape (5, 2, 3), so we'll use
``outaxis=-1`` to put the solution vectors in the last dimension.

>>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
>>> x.shape
(2, 3, 5)
>>> np.set_printoptions(precision=3)  # For compact output of numbers.
>>> x
array([[[-0.118,  0.22 ,  1.277, -0.142,  0.302],
        [ 0.651,  0.989,  2.046,  0.627,  1.072],
        [ 1.42 ,  1.758,  2.816,  1.396,  1.841]],
       [[ 0.401,  0.304,  0.694, -0.867,  0.377],
        [ 0.856,  0.758,  1.149, -0.412,  0.831],
        [ 1.31 ,  1.213,  1.603,  0.042,  1.286]]])

Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):

>>> solve_circulant(c[1], b[1, :])
array([ 0.856,  0.758,  1.149, -0.412,  0.831])

r   r   zShapes of c r   r   r   r'   rH   re   r   r   )r   raiseznear singular circulant matrix.r   )r;   r   r   r*   r:   rt   r   aranger=   rv   rw   fftmoveaxisr   r   r   r   epsanyr
   	ones_likeboolifftry   r   )r   r   singulartolcaxisbaxisoutaxisncnbr   fcabs_fc
near_zerosis_near_singularfbqmaskr   s                     r/   r   r   }  s   j 	aA	sA	%B
aA	sA	%B	x<yy@QRSS 	vv{RYYq8WWQagg688= 	}}Q))	BKK"-B	7BVVBZF
{jjbj!B&"**)=)A)AA99?		D(CI--$CJvvj)w?@@ BN	BKK"-B	7B
A ||AT*Z7$
ABAOOA"//!"4"4FF"}KK2w'Hr1   c                 ^   [        XS9n[        UR                  5      S:w  d   UR                  S   UR                  S   :w  a  [        S5      eUR                  S:X  aF  [        [        R                  " SUR                  S95      R                  n[        R                  " X4S9$ U=(       d    [        X05      n[        SU45      u  pVnU" X1S9u  pn
U
S:X  a0  [        XsR                  S   5      n[        S	U-  5      nU" XUSS
9u  pU
S:  a  [        S5      eU
S:  a  [        SU
* -  5      eW$ )aW  
Compute the inverse of a matrix.

Parameters
----------
a : array_like
    Square matrix to be inverted.
overwrite_a : bool, optional
    Discard data in `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
-------
ainv : ndarray
    Inverse of the matrix `a`.

Raises
------
LinAlgError
    If `a` is singular.
ValueError
    If `a` is not square, or not 2D.

Examples
--------
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1., 2.], [3., 4.]])
>>> linalg.inv(a)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])
>>> np.dot(a, linalg.inv(a))
array([[ 1.,  0.],
       [ 0.,  1.]])

rE   rG   r   r   r   rH   )rV   getrigetri_lworkrX   g)\(?)r`   overwrite_lur   z7illegal value in %d-th argument of internal getrf|getri)r   r   r:   r*   rt   r   r;   ru   r=   rw   r   r   r	   intr
   )r?   rY   rF   r   r   rV   r  r  r   r   r,   r`   inv_as                r/   r   r   I  s*   P 
A	9B
288}RXXa[BHHQK7122 
ww!|*+11}}R**3R!3K 0 2A24!8E+ "6MBTqy{HHQK8 D5L!B5qAax+,,ax '*./ 0 	0Lr1   c                    U(       a  [         R                  " U 5      O[         R                  " U 5      nUR                  S:  a  [	        S5      eUR
                  S   UR
                  S   :w  a  [	        SUR
                   S35      eUR                  R                  S;  a]  [        UR                  R                     nU(       d#  [        SUR                  R                   S	35      eUR                  US
   5      nSn[        UR
                  6 S
:X  at  UR                  R                  S;  a  [         R                  O[         R                  nUR                  S:X  a  U" S5      $ [         R                  " UR
                  SS US9$ UR
                  SS S:X  ar  US   nUR                  S
:X  a  US   nUR                  R                  S;   a  U$ UR                  R                  S:X  a  UR                  S5      $ UR                  S5      $ [!        X05      (       d  U(       d  UR#                  SS9nUR$                  S   (       a  UR$                  S   (       d  UR#                  SS9nUR                  S:X  aR  ['        U5      n[         R(                  " U5      (       a  [         R                  " U5      $ [         R                  " U5      $ UR                  R                  nUS;   a  UR+                  5       (       a  SOSn[         R,                  " UR
                  SS US9n[/        UR
                  SS  Vs/ s H  n[1        U5      PM     sn6  H  n['        X8   5      Xh'   M     U$ s  snf )a  
Compute the determinant of a matrix

The determinant is a scalar that is a function of the associated square
matrix coefficients. The determinant value is zero for singular matrices.

Parameters
----------
a : (..., M, M) array_like
    Input array to compute determinants for.
overwrite_a : bool, optional
    Allow overwriting data in a (may enhance performance).
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
-------
det : (...) float or complex
    Determinant of `a`. For stacked arrays, a scalar is returned for each
    (m, m) slice in the last two dimensions of the input. For example, an
    input of shape (p, q, m, m) will produce a result of shape (p, q). If
    all dimensions are 1 a scalar is returned regardless of ndim.

Notes
-----
The determinant is computed by performing an LU factorization of the
input with LAPACK routine 'getrf', and then calculating the product of
diagonal entries of the U factor.

Even if the input array is single precision (float32 or complex64), the
result will be returned in double precision (float64 or complex128) to
prevent overflows.

Examples
--------
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])  # A singular matrix
>>> linalg.det(a)
0.0
>>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
>>> linalg.det(b)
3.0
>>> # An array with the shape (3, 2, 2, 2)
>>> c = np.array([[[[1., 2.], [3., 4.]],
...                [[5., 6.], [7., 8.]]],
...               [[[9., 10.], [11., 12.]],
...                [[13., 14.], [15., 16.]]],
...               [[[17., 18.], [19., 20.]],
...                [[21., 22.], [23., 24.]]]])
>>> linalg.det(c)  # The resulting shape is (3, 2)
array([[-2., -2.],
       [-2., -2.],
       [-2., -2.]])
>>> linalg.det(c[0, 0])  # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
-2.0
rG   z1The input array must be at least two-dimensional.re   zALast 2 dimensions of the array must be square but received shape .r$   zThe dtype "z6" cannot be cast to float(32, 64) or complex(64, 128).r   TFD      ?N)r:   r=   )r   r   ).r   r   r   dDrQ   rR   Dr   )orderC_CONTIGUOUS	WRITEABLErP   rH   )r;   r   asarrayrx   r*   r:   r=   rz   lapack_cast_dict	TypeErrornamer   r   r   r   rv   r   r   r   r   	isrealobjisloweremptyr   r   )	r?   rY   rF   r   
dtype_chardtypr   r   inds	            r/   r   r     s   ~ %1		a	 bjjmB	ww{LMM	xx|rxx|# 002z< = 	= 
xx}}F"%bhhmm4
k"((-- 9D D E E YYz!}% BHH~XX]]$6rzzBMM77a<977#2d;; 
xx}	]77a<BB88==D I!##!5ryy~I299S>I rs#B HH^$+)>WW3W	ww!|r"#%<<#4#4

3M"--:LM JT&..00Sc

((288CR=

3C288CR=9=aq=9:#BG, ;J :s   :M+c           
         [        XS9n[        XS9n[        UR                  5      S:w  a  [        S5      eUR                  u  p[        UR                  5      S:X  a  UR                  S   nOSnXR                  S   :w  a  [        SU	 SUR                  S    S35      eU	S:X  d  U
S:X  a  [        R
                  " U
4UR                  SS	 -   [        R                  " Xx5      S
9nU
S:X  a"  [        R                  R                  USS9S-  nO[        R                  " S5      nXS[        R                  " S5      4$ UnUc  [        R                  nUS;  a  [        SU S35      e[        UU S34Xx45      u  nnUR                  R                  S:X  a  SOSnX:  aj  [        UR                  5      S:X  a,  [        R
                  " X4UR                  S
9nUUS	U	2S	S	24'   O#[        R
                  " XR                  S
9nUUS	U	& UnU=(       d    [        Xp5      nU=(       d    [        X5      nUc*  [        R                   " UR                  5      R"                  nUS;   Ga  US:X  a  [%        UXX5      nU" XxUUUUS9u  nnnnnnOTUS:X  aN  U(       a#  [%        UXX5      u  nnU" XxUUUSS5      u  nnnnO$[%        UXX5      u  nnnU" XxUUUUSS5      u  nnnnWS:  a  ['        S5      eUS:  a  [        SU* U4-  5      e[        R(                  " / WR                  S
9nX:  a;  US	U
 nWU
:X  a.  [        R*                  " [        R,                  " XS	 5      S-  SS9nUnUUWW4$ US:X  a  [%        UXX5      n[        R
                  " UR                  S   S4[        R.                  S
9nU" XxUUUSS5      u  nnnnnUS:  a  [        SU* -  5      eX:  a  US	U
 nUnU[        R0                  " / UR                  5      US	4$ g	)a  
Compute least-squares solution to equation Ax = b.

Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.

Parameters
----------
a : (M, N) array_like
    Left-hand side array
b : (M,) or (M, K) array_like
    Right hand side array
cond : float, optional
    Cutoff for 'small' singular values; used to determine effective
    rank of a. Singular values smaller than
    ``cond * largest_singular_value`` are considered zero.
overwrite_a : bool, optional
    Discard data in `a` (may enhance performance). Default is False.
overwrite_b : bool, optional
    Discard data in `b` (may enhance 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.
lapack_driver : str, optional
    Which LAPACK driver is used to solve the least-squares problem.
    Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
    (``'gelsd'``) is a good choice.  However, ``'gelsy'`` can be slightly
    faster on many problems.  ``'gelss'`` was used historically.  It is
    generally slow but uses less memory.

    .. versionadded:: 0.17.0

Returns
-------
x : (N,) or (N, K) ndarray
    Least-squares solution.
residues : (K,) ndarray or float
    Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
    ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a
    (0,)-shaped array is returned.
rank : int
    Effective rank of `a`.
s : (min(M, N),) ndarray or None
    Singular values of `a`. The condition number of ``a`` is
    ``s[0] / s[-1]``.

Raises
------
LinAlgError
    If computation does not converge.

ValueError
    When parameters are not compatible.

See Also
--------
scipy.optimize.nnls : linear least squares with non-negativity constraint

Notes
-----
When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped
array and `s` is always ``None``.

Examples
--------
>>> import numpy as np
>>> from scipy.linalg import lstsq
>>> import matplotlib.pyplot as plt

Suppose we have the following data:

>>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
>>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])

We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
to this data.  We first form the "design matrix" M, with a constant
column of 1s and a column containing ``x**2``:

>>> M = x[:, np.newaxis]**[0, 2]
>>> M
array([[  1.  ,   1.  ],
       [  1.  ,   6.25],
       [  1.  ,  12.25],
       [  1.  ,  16.  ],
       [  1.  ,  25.  ],
       [  1.  ,  49.  ],
       [  1.  ,  72.25]])

We want to find the least-squares solution to ``M.dot(p) = y``,
where ``p`` is a vector with length 2 that holds the parameters
``a`` and ``b``.

>>> p, res, rnk, s = lstsq(M, y)
>>> p
array([ 0.20925829,  0.12013861])

Plot the data and the fitted curve.

>>> plt.plot(x, y, 'o', label='data')
>>> xx = np.linspace(0, 9, 101)
>>> yy = p[0] + p[1]*xx**2
>>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
>>> plt.xlabel('x')
>>> plt.ylabel('y')
>>> plt.legend(framealpha=1, shadow=True)
>>> plt.grid(alpha=0.25)
>>> plt.show()

rE   rG   zInput array a should be 2Dr   r   z=Shape mismatch: a and b should have the same number of rows (z != z).NrH   r  )r   )gelsdgelsygelsszLAPACK driver "z" is not found_lworkrQ   TF)r7  r5  r7  )rY   r[   r5  z,SVD did not converge in Linear Least Squaresz.illegal value in %d-th argument of internal %sr6  z1illegal value in %d-th argument of internal gelsy)r   r   r:   r*   r;   r   common_typelinalgr\   r0  r   default_lapack_driverr   r=   rB   r   r   r  r	   r
   r*  sumr   int32r   )r?   r   condrY   r[   rF   lapack_driverr   r   mr+   nrhsr   residuesdriverlapack_funclapack_lwork	real_datar   r`   vsrankworkr,   iworkrworkresidsx1jptvjs                                  r/   r   r     s:   ^ 
A	9B	A	9B
288}56688DA
288}xx{HHQK &&'SRXXa[M= > 	>AvaHHaTBHHQRL(r0FG6yy~~bq~114Hxx~HArxx~--F~,,00?6(.ABB 0&4:861B2D24!;K %**//36UIu rxx=A1);+<+<=BBrr1uI!#4#45BBrF3R!3K3R!3K|xx))*..##W"<tBE(3BD%@K@K)M%Aq!T4 w-lA$Mu#.ru/4dE5$J 1dD '5\159'A#ue#.rueU/3UE$C 1dD!8LMM!8M!%}56 7 7Bagg.52ABqyquq 0q9A&$!!	7	|Q4>xx!a(9)"$*/?1at!8 %(,u- . .52ABA"((2qww't33 
r1   r5  )atolrtolreturn_rankrF   c                "   [        XS9n [        R                  " U SSS9u  pVnUR                  R                  R                  5       n[        R                  " USS9n	Uc  SOUnUc6  [        U R                  5      [        R                  " U5      R                  -  OUnUS:  d  US:  a  [        S5      eXU-  -   n
[        R                  " Xj:  5      nUSS2SU24   nXVSU -  nXWSU -  R                  5       R                  nU(       a  X4$ U$ )a  
Compute the (Moore-Penrose) pseudo-inverse of a matrix.

Calculate a generalized inverse of a matrix using its
singular-value decomposition ``U @ S @ V`` in the economy mode and picking
up only the columns/rows that are associated with significant singular
values.

If ``s`` is the maximum singular value of ``a``, then the
significance cut-off value is determined by ``atol + rtol * s``. Any
singular value below this value is assumed insignificant.

Parameters
----------
a : (M, N) array_like
    Matrix to be pseudo-inverted.
atol : float, optional
    Absolute threshold term, default value is 0.

    .. versionadded:: 1.7.0

rtol : float, optional
    Relative threshold term, default value is ``max(M, N) * eps`` where
    ``eps`` is the machine precision value of the datatype of ``a``.

    .. versionadded:: 1.7.0

return_rank : bool, optional
    If True, return the effective rank of the matrix.
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
-------
B : (N, M) ndarray
    The pseudo-inverse of matrix `a`.
rank : int
    The effective rank of the matrix. Returned if `return_rank` is True.

Raises
------
LinAlgError
    If SVD computation does not converge.

See Also
--------
pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.

Notes
-----
If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
the inverse of ``A`` [1]_. If ``A`` is not invertible then the
Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
that ``||Ax - b||`` is minimized [1]_.

References
----------
.. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
       equations. Mathematical Proceedings of the Cambridge Philosophical
       Society, 52(1), 17-19. doi:10.1017/S0305004100030929

Examples
--------

Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
Moore-Penrose conditions are:

1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
3. ``(AB)* = AB`` (``AB`` is hermitian),
4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.

Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
pseudoinverse is a unique ``B`` that satisfies all four of these
conditions and exists for any ``A``. Note that, unlike the standard
matrix inverse, ``A`` does not have to be a square matrix or have
linearly independent columns/rows.

As an example, we can calculate the Moore-Penrose pseudoinverse of a
random non-square matrix and verify it satisfies the four conditions.

>>> import numpy as np
>>> from scipy import linalg
>>> rng = np.random.default_rng()
>>> A = rng.standard_normal((9, 6))
>>> B = linalg.pinv(A)
>>> np.allclose(A @ B @ A, A)  # Condition 1
True
>>> np.allclose(B @ A @ B, B)  # Condition 2
True
>>> np.allclose((A @ B).conj().T, A @ B)  # Condition 3
True
>>> np.allclose((B @ A).conj().T, B @ A)  # Condition 4
True

rE   F)full_matricesrF           initialN&atol and rtol values must be positive.)r   r   svdr=   rz   ra   r;   r   r:   r   r  r*   r<  r   r   )r?   rQ  rR  rS  rF   urH  vhtmaxSvalrI  Bs                r/   r   r     s    F 	18AqEJHA"	A66!R D24D.2l3qww<"((1+//)Dr	tbyABB

C66!'?D	!UdU(A5DMA	
Y  Awr1   c                 D   [        XS9n [        R                  " XSSS9u  pgUR                  R                  R                  5       n[        R                  " [        R                  " U5      SS9n	Uc  SOUnUc6  [        U R                  5      [        R                  " U5      R                  -  OUnUS:  d  US:  a  [        S5      eXU-  -   n
[        U5      U
:  nS	Xk   -  nUSS2U4   nX|-  UR                  5       R                  -  nU(       a  U[        U5      4$ U$ )
a  
Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.

Calculate a generalized inverse of a complex Hermitian/real symmetric
matrix using its eigenvalue decomposition and including all eigenvalues
with 'large' absolute value.

Parameters
----------
a : (N, N) array_like
    Real symmetric or complex hermetian matrix to be pseudo-inverted

atol : float, optional
    Absolute threshold term, default value is 0.

    .. versionadded:: 1.7.0

rtol : float, optional
    Relative threshold term, default value is ``N * eps`` where
    ``eps`` is the machine precision value of the datatype of ``a``.

    .. versionadded:: 1.7.0

lower : bool, optional
    Whether the pertinent array data is taken from the lower or upper
    triangle of `a`. (Default: lower)
return_rank : bool, optional
    If True, return the effective rank of the matrix.
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
-------
B : (N, N) ndarray
    The pseudo-inverse of matrix `a`.
rank : int
    The effective rank of the matrix.  Returned if `return_rank` is True.

Raises
------
LinAlgError
    If eigenvalue algorithm does not converge.

See Also
--------
pinv : Moore-Penrose pseudoinverse of a matrix.

Examples
--------

For a more detailed example see `pinv`.

>>> import numpy as np
>>> from scipy.linalg import pinvh
>>> rng = np.random.default_rng()
>>> a = rng.standard_normal((9, 6))
>>> a = np.dot(a, a.T)
>>> B = pinvh(a)
>>> np.allclose(a, a @ B @ a)
True
>>> np.allclose(B, B @ a @ B)
True

rE   Fev)ra   rF   rC  rV  rW  NrY  r$  )r   r   eighr=   rz   ra   r;   r   r   r:   r   r  r*   r   r   r   )r?   rQ  rR  ra   rS  rF   rH  r[  r]  r^  r_  above_cutoffpsigma_diagr`  s                 r/   r   r   ^  s    H 	18A<<U4HDA	A66"&&)R(D24D.2l3qww<"((1+//)Dr	tbyABB

CFSLL'K	!\/A	
AFFHJJ&A#k"""r1   c                    [         R                  " [        U SS95      n [         R                  " U R                  6 (       d  [        S5      eU R                  S:X  a  [        [         R                  " SU R                  S95      u  pV[         R                  " XR                  S9nU(       aB  [         R                  " U [        U 5      S9n[         R                  " [        U 5      5      n	XxU	44$ U[         R                  " XR                  S94$ [        SU 45      n
U
" XUUS	9u  p{pnUS:  a  [        S
U*  S35      e[         R                  " U[        S9nXUS-    XUS-   & UR!                  ["        SS9S-
  nU R                  S   n[         R                  " U5      n	X:  a=  [%        XS-   S SSS2   S5       H"  u  nnUU-
  U:X  a  M  XU-
  U/   U	UUU-
  /'   M$     US:  a,  [%        USU 5       H  u  nnUU:X  a  M  U	UU/   U	UU/'   M     U(       a  XxU	44$ [         R                  " U	5      n[         R                  " U5      UU	'   U[         R&                  " U5      USS24   4$ )a   
Compute a diagonal similarity transformation for row/column balancing.

The balancing tries to equalize the row and column 1-norms by applying
a similarity transformation such that the magnitude variation of the
matrix entries is reflected to the scaling matrices.

Moreover, if enabled, the matrix is first permuted to isolate the upper
triangular parts of the matrix and, again if scaling is also enabled,
only the remaining subblocks are subjected to scaling.

The balanced matrix satisfies the following equality

.. math::

                    B = T^{-1} A T

The scaling coefficients are approximated to the nearest power of 2
to avoid round-off errors.

Parameters
----------
A : (n, n) array_like
    Square data matrix for the balancing.
permute : bool, optional
    The selector to define whether permutation of A is also performed
    prior to scaling.
scale : bool, optional
    The selector to turn on and off the scaling. If False, the matrix
    will not be scaled.
separate : bool, optional
    This switches from returning a full matrix of the transformation
    to a tuple of two separate 1-D permutation and scaling arrays.
overwrite_a : bool, optional
    This is passed to xGEBAL directly. Essentially, overwrites the result
    to the data. It might increase the space efficiency. See LAPACK manual
    for details. This is False by default.

Returns
-------
B : (n, n) ndarray
    Balanced matrix
T : (n, n) ndarray
    A possibly permuted diagonal matrix whose nonzero entries are
    integer powers of 2 to avoid numerical truncation errors.
scale, perm : (n,) ndarray
    If ``separate`` keyword is set to True then instead of the array
    ``T`` above, the scaling and the permutation vectors are given
    separately as a tuple without allocating the full array ``T``.

Notes
-----
This algorithm is particularly useful for eigenvalue and matrix
decompositions and in many cases it is already called by various
LAPACK routines.

The algorithm is based on the well-known technique of [1]_ and has
been modified to account for special cases. See [2]_ for details
which have been implemented since LAPACK v3.5.0. Before this version
there are corner cases where balancing can actually worsen the
conditioning. See [3]_ for such examples.

The code is a wrapper around LAPACK's xGEBAL routine family for matrix
balancing.

.. versionadded:: 0.19.0

References
----------
.. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
   Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
   Vol.13(4), 1969, :doi:`10.1007/BF02165404`
.. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
   eigenvector computation", 2014, :arxiv:`1401.5766`
.. [3] D.S. Watkins. A case where balancing is harmful.
   Electron. Trans. Numer. Anal, Vol.23, 2006.

Examples
--------
>>> import numpy as np
>>> from scipy import linalg
>>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])

>>> y, permscale = linalg.matrix_balance(x)
>>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
array([ 3.66666667,  0.4995005 ,  0.91312162])

>>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
array([ 1.2       ,  1.27041742,  0.92658316])  # may vary

>>> permscale  # only powers of 2 (0.5 == 2^(-1))
array([[  0.5,   0. ,  0. ],  # may vary
       [  0. ,   1. ,  0. ],
       [  0. ,   0. ,  1. ]])

TrE   z/The data matrix for balancing should be square.r   rG   rH   r:   gebal)scalepermuterY   zHxGEBAL exited with the internal error "illegal value in argument number z8.". See LAPACK documentation for the xGEBAL error codes.r   Fr   Nre   )r;   r   r   equalr:   r*   rt   r    ru   r=   rw   r	  r   r  r   floatr   r  	enumerater   )Arj  ri  separaterY   b_nt_nr`  scalingpermrh  lohipsr,   r+   r3  r   iperms                      r/   r    r      sY   F 	(>?A88QWWJKK 	vv{!"&&!''":;MM!99-ll1CF3G99SV$Do%%"--333g-E,79A24 ax >?CeW ELL M 	M
 ll2U+GRT{Gr!t 
3U	#a	'B	
A99Q<D 
va45	$B$3FCuz#sUAJ/D!QsU 4
 
Av3B(FCax!3(^D!SN )
 D/!! MM$E))A,E$Kbggguax(((r1   c                 .  ^ [        U [        5      (       a  U u  pV[        XRS9n[        XbS9nO[        XS9nUR                  5       nUR                  S:  d  UR                  S:  a<  Sn[
        R                  " U[        SS9  UR                  5       nUR                  5       nUc  [        S5      e[        XS9nUR                  nUR                  S   UR                  S   :g  n	U(       a  U	(       d   UR                  S   UR                  S   :w  a  [        S5      e[        R                  " U5      =(       d3    [        R                  " U5      =(       d    [        R                  " U5      n
U
(       a  [        R                  O[        R                  mU4S	 jXeU4 5       u  penUR                  S:X  a  U(       d  UR                  S
S5      nOAUR                  S:w  a1  UR                  UR                  S   UR                   S:  a  S
OS5      nXeUTU4$ )aX  Validate arguments and format inputs for toeplitz functions

Parameters
----------
c_or_cr : array_like or tuple of (array_like, array_like)
    The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
    actual shape of ``c``, it will be converted to a 1-D array. If not
    supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
    real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
    of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
    of ``r``, it will be converted to a 1-D array.
b : (M,) or (M, K) array_like
    Right-hand side in ``T x = b``.
check_finite : bool
    Whether to check that the input matrices contain only finite numbers.
    Disabling may give a performance gain, but may result in problems
    (result entirely NaNs) if the inputs do contain infinities or NaNs.
keep_b_shape : bool
    Whether to convert a (M,) dimensional b into a (M, 1) dimensional
    matrix.
enforce_square : bool, optional
    If True (default), this verifies that the Toeplitz matrix is square.

Returns
-------
r : array
    1d array corresponding to the first row of the Toeplitz matrix.
c: array
    1d array corresponding to the first column of the Toeplitz matrix.
b: array
    (M,), (M, 1) or (M, K) dimensional array, post validation,
    corresponding to ``b``.
dtype: numpy datatype
    ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
    ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
    otherwise, it is ``np.float``.
b_shape: tuple
    Shape of ``b`` after passing it through ``_asarray_validated``.

rE   r   zBeginning in SciPy 1.17, multidimensional input will be treated as a batch, not `ravel`ed. To preserve the existing behavior and silence this warning, `ravel` arguments before passing them to `toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.rG   r(   z`b` must be an array, not None.r   zIncompatible dimensions.c              3   N   >#    U  H  n[         R                  " UTS 9v   M     g7f)rH   N)r;   r*  )r   r   r=   s     r/   r   2_validate_args_for_toeplitz_ops.<locals>.<genexpr>  s     =9arzz!5)9s   "%re   )
isinstancetupler   	conjugaterx   warningsr   FutureWarningr   r*   r:   r;   ry   r   r   r   rt   )r   r   rF   r   enforce_squarer   r   msgr   is_not_squareis_cmplxr=   s              @r/   r   r   V  s   V '5!!q<q<wBKKMvvzQVVaZF 	c=Q7GGIGGIy:;;18AggGGGAJ!''!*,M=QWWQZ1771:-E344q!MR__Q%7M2??1;MH%BMM2::E=A!9=GA!vv{<IIb!	
1IIaggaj
":E7""r1   c                    SSK J nJnJnJn  [	        XUSSS9u  ppnUR
                  u  p[        U	5      n[        U5      nX-   S-
  n[        U5      S:X  a  U4OX4nUR                  S:X  a  [        R                  " UUS9$ [        R                  " XSSS2   45      n[        R                  " U5      (       d  [        R                  " U5      (       a6  U" USUS	9R                  SS5      nU" UUSUS
9nU" UU-  SUS	9SU2SS24   nO6U" USUS	9R                  SS5      nU" UUSUS
9nU" UU-  SUUS9SU2SS24   nUR                  " U6 $ )a  Efficient Toeplitz Matrix-Matrix Multiplication using FFT

This function returns the matrix multiplication between a Toeplitz
matrix and a dense matrix.

The Toeplitz matrix has constant diagonals, with c as its first column
and r as its first row. If r is not given, ``r == conjugate(c)`` is
assumed.

.. warning::

    Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
    not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
    before passing them to `matmul_toeplitz`.

Parameters
----------
c_or_cr : array_like or tuple of (array_like, array_like)
    The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
    supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
    real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
    of the Toeplitz matrix is ``[c[0], r[1:]]``.
x : (M,) or (M, K) array_like
    Matrix with which to multiply.
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
    (result entirely NaNs) if the inputs do contain infinities or NaNs.
workers : int, optional
    To pass to scipy.fft.fft and ifft. Maximum number of workers to use
    for parallel computation. If negative, the value wraps around from
    ``os.cpu_count()``. See scipy.fft.fft for more details.

Returns
-------
T @ x : (M,) or (M, K) ndarray
    The result of the matrix multiplication ``T @ x``. Shape of return
    matches shape of `x`.

See Also
--------
toeplitz : Toeplitz matrix
solve_toeplitz : Solve a Toeplitz system using Levinson Recursion

Notes
-----
The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
to efficiently calculate the matrix-matrix product.

Because the computation is based on the FFT, integer inputs will
result in floating point outputs.  This is unlike NumPy's `matmul`,
which preserves the data type of the input.

This is partly based on the implementation that can be found in [1]_,
licensed under the MIT license. More information about the method can be
found in reference [2]_. References [3]_ and [4]_ have more reference
implementations in Python.

.. versionadded:: 1.6.0

References
----------
.. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
   Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
   Gaussian Process Inference with GPU Acceleration" with contributions
   from Max Balandat and Ruihan Wu. Available online:
   https://github.com/cornellius-gp/gpytorch

.. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
   Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
   Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
   Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
   http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html

.. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
   package for audio room simulations and array processing algorithms,
   Proc. IEEE ICASSP, Calgary, CA, 2018.
   https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
   pyroomacoustics/adaptive/util.py

.. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
   Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
   the Seismological Society of America., January, 2017. Vol. 107(1),
   pp. 276-291.

Examples
--------
Multiply the Toeplitz matrix T with matrix x::

        [ 1 -1 -2 -3]       [1 10]
    T = [ 3  1 -1 -2]   x = [2 11]
        [ 6  3  1 -1]       [2 11]
        [10  6  3  1]       [5 19]

To specify the Toeplitz matrix, only the first column and the first
row are needed.

>>> import numpy as np
>>> c = np.array([1, 3, 6, 10])    # First column of T
>>> r = np.array([1, -1, -2, -3])  # First row of T
>>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])

>>> from scipy.linalg import toeplitz, matmul_toeplitz
>>> matmul_toeplitz((c, r), x)
array([[-20., -80.],
       [ -7.,  -8.],
       [  9.,  85.],
       [ 33., 218.]])

Check the result by creating the full Toeplitz matrix and
multiplying it by ``x``.

>>> toeplitz(c, r) @ x
array([[-20, -80],
       [ -7,  -8],
       [  9,  85],
       [ 33, 218]])

The full matrix is never formed explicitly, so this routine
is suitable for very large Toeplitz matrices.

>>> n = 1000000
>>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,))

rG   )r  r  rfftirfftF)r   r  r   r   rg  re   )r   workers)r+   r   r  N)r   r  r+   )r  r  r  r  r   r:   r   rt   r;   rw   r   ry   r   )r   r   rF   r  r  r  r  r  r   r   r=   x_shaper+   r@  T_nrowsT_ncolspreturn_shapeembedded_colfft_matfft_xmat_times_xs                         r/   r!   r!     sr   @ -,=LuULA!G77DA!fG!fGAA!$W!2G:L 	vv{}}Ql33>>11Rj/2L	|$$(:(:lG<DDRKAG475=q#*,,4WHaK9 |!W=EEb!LQ!!W5GEM$+q22:7(A+? --r1   rO   )FFFTNF)r   FFFT)r   FFF)FFT)FFFT)T)r  Nre   r   r   )FT)NFFTN)NNTFT)TTFF)FN)8r~  r   	itertoolsr   numpyr;   r   r   lapackr   r	   _miscr
   r   r   r   r   r#   r   _solve_toeplitzr   _cythonized_array_utilsr   r   r   r   __all__	typecodesjoincan_castr+  r0   rC   r   r{   r|   r}   r~   r   rs   r   r   r   r   r   r   r   r   r   r   r;  r   r   r    r   r!   )r   ys   00r/   <module>r     s       ( 4 : : ' " %3 3A  \\%020 rww6G6aR[[5F6GHH02 
* ", */9=Nb	A @E59Xx CH"', BG"u*p GL#IX`F> 15/0HXFV}B ;@+/H4V &  tT xv <AZz :?$X)x 48O#d_.Q<  H 2s   %D<;D7D7D<7D<