
    5[g0                       d dl mZ d dlmZ d dlZd dlmZmZ ddlm	Z	m
Z
 ddlmZmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ g dZej0                  d   D  ci c]5  } | dj3                  dD cg c]  }ej5                  | |      s| c}      7 c}} Zd$dZ	 	 	 d%dZ	 	 d&dZ	 	 d'dZ	 	 d(dZ d)dZ!d Z"	 	 d*dZ#d+dZ$d+dZ%	 	 d,dZ&de&_'        ddddddZ(	 	 d-d Z)	 	 d.d!Z*	 d)d"Z+d/d#Z,yc c}w c c}} w )0    )warn)productN)
atleast_1d
atleast_2d   )get_lapack_funcs_compute_lwork)LinAlgError_datacopiedLinAlgWarning)_asarray_validated)_decomp_decomp_svd)levinson)find_det_from_lu)solvesolve_triangularsolveh_bandedsolve_bandedsolve_toeplitzsolve_circulantinvdetlstsqpinvpinvhmatrix_balancematmul_toeplitzAll fdFDc                     |dk  rt        d|  d      d|k  rt        d      |y |d      }||k  rt        d|dd	t        d
       yy)zB Check 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        N/var/www/html/bid-api/venv/lib/python3.12/site-packages/scipy/linalg/_basic.py_solve_checkr,   #   sp    ax?wmTUU	
T/00}c
Aqy-eC[ 9+ +q	*     FTc                    d}t        t        | |            }	t        t        ||            }
|	j                  d   }|xs t	        |	|       }|xs t	        |
|      }|	j                  d   |	j                  d   k7  rt        d      ||
j                  d   k7  r|dk(  r|
j                  dk7  st        d      |
j                  dk(  rkt        t        j                  d|	j                        t        j                  d|
j                              j                  }t        j                  |
|      S |
j                  dk(  r|dk(  r
|
d	d	d	f   }
n	|
d	d	d	f   }
d
}|dvrt        | d      |dk(  rt        j                  |	      sd}|	j                  j                  dv rt!        dd      }nt!        dd      }t!        d|	f      }|r$d}d}t        j                  |	      rt#        d      d}d} |||	      }|dk(  rWt!        d|	|
f      \  }}} ||	|      \  }}}t%        ||        ||||
||      \  }}t%        ||        ||||      \  }}n|dk(  rLt!        d|	|
f      \  }}}t'        |||      } ||	|
||||      \  }}}}t%        ||        ||||      \  }}n|dk(  rLt!        d|	|
f      \  }}} t'        | ||      } ||	|
||||      \  }}}}t%        ||        ||||      \  }}n:t!        d|	|
f      \  }!}" |"|	|
|||       \  }}}t%        ||        |!||      \  }}t%        ||||       |r|j)                         }|S )!a  
    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

    ===================  ========
     generic matrix       'gen'
     symmetric            'sym'
     hermitian            'her'
     positive definite    'pos'
    ===================  ========

    If omitted, ``'gen'`` is the default structure.

    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.

    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 if ``assume_a == 'gen'`` (the default). 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, {'gen', 'sym', 'her', 'pos'}
        Valid entries are explained above.
    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 generic, symmetric, Hermitian and positive definite solutions are
    obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
    LAPACK respectively.

    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   dtypeNT)gensymherposz% is not a recognized matrix structurer6   r5   fFr)   fdlangeIzWscipy.linalg.solve can currently not solve a^T x = b or a^H x = b for complex matrices.1r4   )gecongetrfgetrsoverwrite_a)transoverwrite_b)norm)heconhesv
hesv_lwork)lworklowerrB   rD   )syconsysv
sysv_lwork)poconposv)rJ   rB   rD   )r   r   r   shaper   r&   sizer   npeyer3   ones
empty_likendimiscomplexobjcharr   NotImplementedErrorr,   r	   ravel)#abrJ   rB   rD   r0   assume_a
transposedb_is_1Da1b1r'   dtr)   r;   rC   rE   anormr>   r?   r@   luipvtr(   xr*   rF   rG   hesv_lwrI   rK   rL   sysv_lwrN   rO   s#                                      r+   r   r   3   s   | G	&q|D	EB	&q|D	EB
A3R!3K3R!3K	xx{bhhqk!?@@BHHQKQ277a< ' ( ( 
ww!|266!288,bggarxx.HIOO}}Rr** 
ww!|6D!GBAtGB33H:%JKLL 5!4
 
xx}} 4 4
 Wre,E ??2% '> ? ? $OE 5./J02Bx9uer{;D$QD"#>4QBD1t	U	/ 1?ACR JtWw51 Ru',-8-8:D!T 	QBe,t	U	/ 1?ACR JtWw51 Ru',-8-8:D!T 	QBe,t ''8(*Bx1t2r'2'24At 	QB&tD%'GGIHr-   c                    t        | |      }t        ||      }t        |j                        dk7  s|j                  d   |j                  d   k7  rt        d      |j                  d   |j                  d   k7  r&t        d|j                   d|j                   d      |j                  dk(  rkt        t        j                  d|j                  	      t        j                  d|j                  	            j                  }	t        j                  ||		      S |xs t        ||      }dddd
j                  ||      }t        d||f      \  }
|j                  j                  s|dk(  r |
||||||      \  }}n |
|j                   ||| | |      \  }}|dk(  r|S |dkD  rt#        d|dz
  z        t        d| z        )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.])

    r/   r1   r   r   expected square matrixzshapes of a  and b  are incompatibler2   )NTC)trtrs)rD   rJ   rC   unitdiagz1singular matrix: resolution failed at diagonal %dz0illegal value in %dth argument of internal trtrs)r   lenrP   r&   rQ   r   rR   rS   r3   rT   rU   r   getr   flagsf_contiguousrn   r
   )r[   r\   rC   rJ   unit_diagonalrD   r0   r`   ra   dt_nonemptyrp   rf   r(   s                r+   r   r     s   J 
AL	9B	AL	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!!$((6Ej2r(3FE	xx
BKu#m=4 bkU"'i-A4 qyaxM6# $ 	$
Ge  r-   c           
      b   t        ||d      }t        ||d      }|j                  d   |j                  d   k7  rt        d      | \  }}	||	z   dz   |j                  d   k7  r#t        d||	z   dz   |j                  d   fz        |j                  dk(  rkt	        t        j                  d|j                        t        j                  d|j                              j                  }
t        j                  ||
      S |xs t        ||      }|j                  d   dk(  r"t        j                  || 	      }||d
   z  }|S ||	cxk(  rdk(  rTn nQ|xs t        ||      }t        d||f      \  }|dddf   }|dddf   }|dddf   } |||||||||      \  }}}}}ngt        d||f      \  }t        j                  d|z  |	z   dz   |j                  d   f|j                        }|||dddf<    |||	||d|      \  }}}}|dk(  r|S |dkD  rt        d      t        d| z        )an  
    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)r0   
as_inexactr   &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)r2   copy)r   r   )gtsvNr1   )gbsv)overwrite_abrD   singular matrixz5illegal value in %d-th argument of internal gbsv/gtsv)r   rP   r&   rQ   r   rR   rS   r3   rT   rU   r   arrayr   zerosr
   )l_and_uabr\   r   rD   r0   r`   ra   nlowernupperrb   b2r~   dur:   dldu2rf   r(   r   a2rd   pivs                          r+   r   r   r  s`   L 
B\d	KB	ALT	JB 
xx|rxx{"ABBVVbhhqk)  #)F?Q#6"DE F 	F
 
ww!|266!288,bggarxx.HIOO}}Rr**3R!3K	xx|qXXbK1
bh	1#:{2r': RH512Yq!tH3B3Z"2q"b,#/>QAt !RH5XXqx&(1,bhhqk:$**M67A:BT,79CDqyax+,,
 !$(5) * *r-   c                 N   t        | |      }t        ||      }|j                  d   |j                  d   k7  rt        d      |j                  dk(  rkt	        t        j                  d|j                        t        j                  d|j                              j                  }t        j                  ||      S |xs t        ||      }|xs t        ||       }|j                  d   dk(  rlt        d||f      \  }	|r|dd	d	f   j                  }
|dd	df   }n*|dd	d	f   j                  }
|ddd	f   j                         } |	|
|||||      \  }
}}}n!t        d
||f      \  } ||||||      \  }}}|dkD  rt        d|z        |dk  rt        d| z        |S )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])

    r/   rz   r   r{   r   r2   r1   )ptsvN)pbsv)rJ   r   rD   z(%dth leading minor not positive definitez/illegal value in %dth argument of internal pbsv)r   rP   r&   rQ   r   rR   rS   r3   rT   rU   r   r   realconjr
   )r   r\   r   rD   rJ   r0   r`   ra   rb   r   r:   er   rf   r(   r   cs                    r+   r   r     s   N 
B\	:B	AL	9B 
xx|rxx{"ABB 
ww!|266!288,bggarxx.HIOO}}Rr**3R!3K6;r2#6L	xx{a RH51a4A1crc6
A1a4A1ab5	 AaBl)+2q$ !RH5"bL&13
1daxDtKLLax  #'%( ) 	)Hr-   c                    t        | ||d      \  }}}}}|j                  dk(  rt        j                  |      S t        j                  |ddd   |f      }|t        d      |j                  dk(  r$t        |t        j                  |            \  }}	|S t        j                  t        |j                  d         D 
cg c]+  }
t        |t        j                  |dd|
f               d   - c}
      } |j                  | }|S c c}
w )a	  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.

    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, 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   rz   Nz)illegal value, `b` is a required argumentr   )_validate_args_for_toeplitz_opsrQ   rR   rU   concatenater&   rV   r   ascontiguousarraycolumn_stackrangerP   reshape)c_or_crr\   r0   rr   r3   b_shapevalsrf   _is              r+   r   r   q  s   P >Lt5Aq!UG 	vv{}}Q >>1R"W:q/*DyDEEvv{b221561 H	 OO&+AGGAJ&79&7 &dB,@,@1a4,IJ1M&79 :AIIwH	9s    0Dc                     |}|dk  r||j                   z  }d|cxk  r|j                   k  rn n|j                  |   S t        d|  d      )Nr   'zaxis' entry is out of bounds)rV   rP   r&   )anamer[   axisaxs       r+   _get_axis_lenr     sO    	B	Av
affBwwr{
q;<
==r-   c                 r   t        j                  |       } t        d| |      }t        j                  |      }t        d||      }||k7  r&t        d| j                   d|j                   d      |j
                  dk(  rkt        t        j                  d| j                        t        j                  d|j                              j                  }	t        j                  ||	      S t         j                  j                  t        j                  | |d	      d	
      }
t        j                  |
      }|||j                  d	
      |z  t        j                  t         j                         j"                  z  }|j                  dk7  r|j                  dz   |_        nt        j                  |      }||k  }t        j$                  |      }|r|dk(  rt'        d      d|
|<   t         j                  j                  t        j                  ||d	      d	
      }||
z  }|r#t        j(                  |t*              |z  }d||<   t         j                  j-                  |d	
      }t        j.                  |       s!t        j.                  |      s|j0                  }|d	k7  rt        j                  |d	|      }|S )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 rk   rl   r   r$   r2   rz   r    )r   raiseznear singular circulant matrix.r   )rR   r   r   r&   rP   rQ   r   aranger3   rT   rU   fftmoveaxisabsmaxfinfofloat64epsanyr
   	ones_likeboolifftrW   r   )r   r\   singulartolcaxisbaxisoutaxisncnbrb   fcabs_fc
near_zerosis_near_singularfbqmaskrf   s                     r+   r   r     s"   j 	aA	sAu	%B
aA	sAu	%B	Rx<yy@QRSS 	vv{RYYq8WWQagg688= 	}}Qb))	BKK5"-B	7BVVBZF
{jjbj!B&"**)=)A)AA99?		D(CI--$C3Jvvj)w?@@ BzN	BKK5"-B	7B
RA ||AT*Z7$
ABAOOA"//!"4FF"}KK2w'Hr-   c                 t   t        | |      }t        |j                        dk7  s|j                  d   |j                  d   k7  rt        d      |j                  dk(  rKt        t        j                  d|j                              j                  }t        j                  ||      S |xs t        ||       }t        d|f      \  }}} |||      \  }}	}
|
dk(  r6t        ||j                  d         }t        d	|z        } |||	|d
      \  }}
|
dkD  rt        d      |
dk  rt        d|
 z        S )a  
    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.]])

    r/   r1   r   r   rj   r2   )r?   getrigetri_lworkrA   g)\(?)rI   overwrite_lur   z7illegal value in %d-th argument of internal getrf|getri)r   rr   rP   r&   rQ   r   rR   rS   r3   rU   r   r   r	   intr
   )r[   rB   r0   r`   rb   r?   r   r   rd   r   r(   rI   inv_as                r+   r   r     s<   P 
AL	9B
288}RXXa[BHHQK7122 
ww!|*+11}}Rr**3R!3K 0 2A24!8E5+ "+6MBTqy{BHHQK8 D5L!B5qAtax+,,ax '*./ 0 	0Lr-   c                 T   |rt        j                  |       nt        j                  |       }|j                  dk  rt	        d      |j
                  d   |j
                  d   k7  rt	        d|j
                   d      |j                  j                  dvrXt        |j                  j                     }|s#t        d|j                  j                   d	      |j                  |d
         }d}t        |j
                   d
k(  rs|j                  j                  dvrt         j                  nt         j                  }|j                  dk(  r |d      S t        j                  |j
                  dd |      S |j
                  dd dk(  rt!        |j
                   dkD  rjt        j"                  |      }|j                  j                  dv r|S |j                  j                  dk(  r|j                  d      S |j                  d      S |j                  j                  dv r#t        j                  |j%                               S t        j                  |j%                               S t'        ||       s|s|j)                  d      }|j*                  d   r|j*                  d   s|j)                  d      }|j                  dk(  rJt-        |      }t        j.                  |      rt        j                  |      S t        j                  |      S |j                  j                  }|dv r|j1                         rdnd}t        j2                  |j
                  dd |      }t5        |j
                  dd D cg c]  }t7        |       c} D ]  }	t-        ||	         ||	<    |S c c}w )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 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
    r1   z1The input array must be at least two-dimensional.rz   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)rP   r3   )r   r   r   dDr9   r:   Dfdro   )orderC_CONTIGUOUS	WRITEABLEr8   r2   )rR   asarray_chkfiniteasarrayrV   r&   rP   r3   rX   lapack_cast_dict	TypeErrornameastypeminr   
complex128rT   r   squeezeitemr   r}   rt   r   	isrealobjisloweremptyr   r   )
r[   rB   r0   r`   
dtype_chardtyptempr   rf   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}>A::b>Dxx}}$,.HHMMS,@C( *C(* .0XX]]d-BBJJrwwy) .MM"''),. r1s#B HH^$+)>WW3W	ww!|r"#%<<#4

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

((288CR=

3C288CR=9=aq=9:#BsG,C ;J :s   7N%c           
          t        | |      }t        ||      }t        |j                        dk7  rt        d      |j                  \  }	}
t        |j                        dk(  r|j                  d   }nd}|	|j                  d   k7  rt        d|	 d|j                  d    d      |	dk(  s|
dk(  rt	        j
                  |
f|j                  dd	 z   t	        j                  ||      
      }|
dk(  r%t        j                  j                  |d      dz  }nt	        j                  d      }||dt	        j                  d      fS |}|t        j                  }|dvrt        d|z        t        |d|z  f||f      \  }}|j                  j                  dk(  rdnd}|	|
k  rot        |j                        dk(  r/t	        j
                  |
|f|j                  
      }||d	|	d	d	f<   n&t	        j
                  |
|j                  
      }||d	|	 |}|xs t        ||       }|xs t        ||      }|)t	        j                   |j                        j"                  }|dv r|dk(  r%t%        ||	|
||      } |||||||      \  }}}}}}nT|dk(  rO|r&t%        ||	|
||      \  }} ||||||dd      \  }}}}n't%        ||	|
||      \  }}} |||||||dd      \  }}}}dkD  rt'        d      |dk  rt        d| |fz        t	        j(                  g j                  
      }|	|
kD  r<|d	|
 }|
k(  r0t	        j*                  t	        j,                  ||
d	       dz  d      }|}||fS |dk(  rt%        ||	|
||      }t	        j
                  |j                  d   dft        j.                  
      } ||||||dd      \  }}}}}|dk  rt        d| z        |	|
kD  r|d	|
 }|}|t	        j0                  g |j                        |d	fS y	)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()

    r/   r1   zInput array a should be 2Dr   r   z=Shape mismatch: a and b should have the same number of rows (z != z).Nr2   r   )r   )gelsdgelsygelsszLAPACK driver "%s" is not foundz%s_lworkr9   TF)r   r   r   )rB   rD   r   z,SVD did not converge in Linear Least Squaresz.illegal value in %d-th argument of internal %sr   z1illegal value in %d-th argument of internal gelsy)r   rr   rP   r&   rR   r   common_typelinalgrE   r   r   default_lapack_driverr   r3   kindr   r   r   r	   r
   r   sumr   int32r   )r[   r\   condrB   rD   r0   lapack_driverr`   ra   mr'   nrhsrf   residuesdriverlapack_funclapack_lwork	real_datar   rI   vsrankworkr(   iworkrworkresidsx1jptvjs                                  r+   r   r   u  sk   ^ 
AL	9B	AL	9B
288}56688DAq
288}xx{BHHQK &&'SRXXa[M= > 	>AvaHHaTBHHQRL(r20FG6yy~~bq~114Hxx~H(Arxx~--F~,,00:VCDD 0&1;f1D2F24b!;K %**//36UI1u rxx=A1d);+<+<=BBrr1uI!;#4#45BBrF3R!3K3R!3K|xx))*..##W"<AtTBE(3BD%@K@K)M%Aq!T4 w-lAq$Mu#.r2u/4dE5$J 1dD '5\1a594'A#ue#.r2ueU/3UE$C 1dD!8LMM!8M!%}56 7 7Bagg.q52ABqyquq 0q9A&$!!	7	|Q4>xx!a(9)"b$*/?1at!8 %(,u- . .q52ABA"((2qww't33 
r-   r   )atolrtolreturn_rankr0   c                (   t        | |      } t        j                  | dd      \  }}}|j                  j                  j                         }t        j                  |d      }	|dn|}|5t        | j                        t        j                  |      j                  z  n|}|dk  s|dk  rt        d      ||	|z  z   }
t        j                  ||
kD        }|ddd|f   }||d| z  }||d| z  j                         j                  }|r||fS |S )aI  
    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

    r/   F)full_matricesr0           initialN&atol and rtol values must be positive.)r   r   svdr3   rX   rJ   rR   r   rP   r   r   r&   r   r   rn   )r[   r  r  r  r0   ur   vhtmaxSvalr   Bs                r+   r   r   C  s   F 	1<8AqEJHAq"	A66!R D24D.2l3qww<"((1+//)Dr	tbyABB

C66!c'?D	!UdU(A5DMA	
RY  A$wr-   c                 H   t        | |      } t        j                  | |dd      \  }}|j                  j                  j                         }t        j                  t        j                  |      d      }	|dn|}|5t        | j                        t        j                  |      j                  z  n|}|dk  s|dk  rt        d      ||	|z  z   }
t        |      |
kD  }d	||   z  }|dd|f   }||z  |j                         j                  z  }|r|t        |      fS |S )
au  
    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

    r/   Fev)rJ   r0   r   r  r  Nr  r   )r   r   eighr3   rX   rJ   rR   r   r   rP   r   r   r&   r   rn   rr   )r[   r  r  rJ   r  r0   r   r  r  r  r  above_cutoffpsigma_diagr  s                 r+   r   r     s   H 	1<8A<<U4HDAq	A66"&&)R(D24D.2l3qww<"((1+//)Dr	tbyABB

CFSLL,'K	!\/A	
[AFFHJJ&A#k"""r-   c                    t        j                  t        | d            } t        j                  | j                   st        d      | j                  dk(  rt        t        j                  d| j                              \  }}t        j                  | |j                        }|rDt        j                  | t        |             }t        j                  t        |             }	|||	ffS |t        j                  | |j                        fS t        d| f      }
 |
| |||	      \  }}}}}|dk  rt        d
|  d      t        j                  |t              }|||dz    |||dz    |j!                  t"        d      dz
  }| j                  d   }t        j                  |      }	||k  r;t%        ||dz   d ddd   d      D ]   \  }}||z
  |k(  r|	||z
  |g   |	|||z
  g<   " |dkD  r(t%        |d|       D ]  \  }}||k(  r|	||g   |	||g<    |r|||	ffS t        j                  |	      }t        j                  |      ||	<   |t        j&                  |      |ddf   fS )a4  
    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. ]])

    Tr/   z/The data matrix for balancing should be square.r   r1   r2   rP   gebal)scalepermuterB   zHxGEBAL exited with the internal error "illegal value in argument number z8.". See LAPACK documentation for the xGEBAL error codes.r   Fr|   Nrz   )rR   r   r   equalrP   r&   rQ   r   rS   r3   rU   r   rr   r   r   floatr   r   	enumeratediag)Ar  r  separaterB   b_nt_nr  scalingpermr  lohipsr(   r'   r   rf   iperms                      r+   r   r     ss   F 	(>?A88QWWJKK 	vv{!"&&!''":;SMM!399-ll1CF3G99SV$Dwo%%"--333g-E,79Ar2r4 ax >?CeW ELL M 	M
 ll2U+G"RT{GBr!t 
3U	#a	'B	
A99Q<D 
Av2a45	$B$3FCuz#QsUAJ/D!QsU 4
 
Av3B(FCax!3(^D!SN )
 7D/!! MM$E))A,E$Kbggguax(((r-   c                   
 t        | t              r<| \  }}t        ||      j                         }t        ||      j                         }n+t        | |      j                         }|j	                         }|t        d      t        ||      }|j                  }|j                  d   |j                  d   k7  }|r|s|j                  d   |j                  d   k7  rt        d      t        j                  |      xs, t        j                  |      xs t        j                  |      }	|	rt        j                  nt        j                  

fd|||fD        \  }}}|j                  dk(  r|s|j                  dd      }n?|j                  dk7  r0|j                  |j                  d   |j                  dkD  rdnd      }|||
|fS )a  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``.

    r/   z`b` must be an array, not None.r   zIncompatible dimensions.c              3   L   K   | ]  }t        j                  |         yw)r2   N)rR   r   ).0r   r3   s     r+   	<genexpr>z2_validate_args_for_toeplitz_ops.<locals>.<genexpr>  s      =9arzz!5))9s   !$r   rz   )
isinstancetupler   rZ   	conjugater&   rP   rR   rW   r   r   rV   r   rQ   )r   r\   r0   r   enforce_squarer   r   r   is_not_squareis_cmplxr3   s             @r+   r   r     sy   V '5!1q|<BBDq|<BBDw\BHHJKKMy:;;1<8AggGGGAJ!''!*,M=QWWQZ1771:-E344q!MR__Q%7M2??1;MH%BMM2::E=Aq!9=GAq!vv{<IIb!	
1IIaggaj
":aE7""r-   c                    ddl m }m}m}m} t	        | ||dd      \  }}	}}
}|j
                  \  }}t        |	      }t        |      }||z   dz
  }t        |      dk(  r|fn||f}|j                  dk(  rt        j                  ||      S t        j                  |	|ddd   f      }t        j                  |      st        j                  |      r? ||d|	      j                  dd      } |||d|
      } |||z  d|	      d|ddf   }n? ||d|	      j                  dd      } |||d|
      } |||z  d||      d|ddf   } |j                  | S )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.

    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.
    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.])

    r1   )r   r   rfftirfftF)r   r5  r   r   r  rz   )r   workers)r'   r   r;  N)r   r;  r'   )r   r   r9  r:  r   rP   rr   rQ   rR   rU   r   rW   r   )r   rf   r0   r;  r   r   r9  r:  r   r   r3   x_shaper'   r   T_nrowsT_ncolspreturn_shapeembedded_colfft_matfft_xmat_times_xs                         r+   r   r     s|   x -,=LuULAq!UG77DAq!fG!fG'AA!$W!2G:!L 	vv{}}Ql33>>1a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+? ;--r-   )NN)FFFTr4   F)r   FFFT)FFT)FFFT)T)r   Nrz   r   r   )FT)NFFTN)NNTFT)TTFF)FN)-warningsr   	itertoolsr   numpyrR   r   r   lapackr   r	   _miscr
   r   r   r   r   r    r   _solve_toeplitzr   _cythonized_array_utilsr   __all__	typecodesjoincan_castr   r,   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rf   ys   00r+   <module>rQ     s_      ( 4 : : ' " % 5A  \\%020 rww6G6aR[[A5F6GHH02 
*  */9>Rj @E59gT BG"p*f GL#IX\~> 15/0HXFVAJ ;@+/H4V &  tT xv <AZz :?$X)x 48F#R[.C7  H 2s   C<0C7C7	C<7C<