
    (ph+c                       S r / SQrSSKrSSKrSSKrSSKJrJr  SSKJ	r	  SSK
JrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJrJ r J!r!J"r"J#r#J$r$J%r%J&r&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3J4r4  SSK5J6r6  SS	K
J7r7  SS
K8J9r9J:r:  SSK;J<r<  SSK=J>r>   " S S\5      r? " S S\5      r@ " S S\5      rA " S S\5      rB " S S\5      rC\R                  " \7R                  SS9rE\rF\	" S5       " S S\G5      5       rHS rI\I" 5       rJCIS rKS rLS rMS rNS  rOS! rPS" rQS# rRS$ rS\\\\\\\\0rT\\\\\\\\0rU\4S% jrV\4S& jrWS' rXS( rYS) rZS* r[S+ r\S, r]S- r^S. r_SWS/ jr`\E" \`5      SWS0 j5       raS1 rb\E" \b5      S2 5       rcSWS3 jrd\E" \d5      SXS4 j5       reS5 rf\E" \f5      S6 5       rgS7 rh\E" \h5      S8 5       ri\E" \f5      S9 5       rjSWS: jrk\E" \k5      SYS; j5       rl\E" \f5      S< 5       rmSWS= jrn\E" \n5      SZS> j5       roS? rp\E" \f5      S@ 5       rq\E" \n5      SZSA j5       rrS[SB jrs\E" \s5      S\SC j5       rtSWSD jru\E" \u5      SWSE j5       rvS]SF jrw\E" \w5      S^SG j5       rxS]SH jry\E" \y5      S_SI j5       rz\E" \f5      SJ 5       r{\E" \f5      SK 5       r|SWSL jr}\E" \}5      S`SM j5       r~SN rS[SO jr\E" \5      SaSP j5       rSSQ.SR jr\E" \5      SSQ.SS j5       rSWST jrSbSU jrSWSV jrg)cax  Lite version of scipy.linalg.

Notes
-----
This module is a lite version of the linalg.py module in SciPy which
contains high-level Python interface to the LAPACK library.  The lite
version only accesses the following LAPACK functions: dgesv, zgesv,
dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
)matrix_powersolvetensorsolve	tensorinvinvcholeskyeigvalseigvalshpinvslogdetdetsvdeigeighlstsqnormqrcondmatrix_rankLinAlgError	multi_dot    N)
NamedTupleAny   )
set_module)*arrayasarrayzerosempty
empty_likeintcsingledoublecsinglecdoubleinexactcomplexfloatingnewaxisallInfdotaddmultiplysqrtsumisfinitefinfoerrstate	geterrobjmoveaxisaminamaxprodabs
atleast_2dintp
asanyarrayobject_matmulswapaxesdividecount_nonzeroisnansignargsortsort
reciprocal)normalize_axis_index)	overrides)triueye)_umath_linalg)NDArrayc                   6    \ rS rSr% \\   \S'   \\   \S'   Srg)	EigResult'   eigenvalueseigenvectors N__name__
__module____qualname____firstlineno__rK   r   __annotations____static_attributes__rQ       F/var/www/html/venv/lib/python3.13/site-packages/numpy/linalg/linalg.pyrM   rM   '       #,rY   rM   c                   6    \ rS rSr% \\   \S'   \\   \S'   Srg)
EighResult+   rO   rP   rQ   NrR   rQ   rY   rZ   r]   r]   +   r[   rY   r]   c                   6    \ rS rSr% \\   \S'   \\   \S'   Srg)QRResult/   QRrQ   NrR   rQ   rY   rZ   r`   r`   /   s    s|Os|OrY   r`   c                   6    \ rS rSr% \\   \S'   \\   \S'   Srg)SlogdetResult3   rB   	logabsdetrQ   NrR   rQ   rY   rZ   re   re   3   s    
#,s|rY   re   c                   F    \ rS rSr% \\   \S'   \\   \S'   \\   \S'   Srg)	SVDResult7   USVhrQ   NrR   rQ   rY   rZ   ri   ri   7   s    s|Os|OrY   ri   znumpy.linalg)modulec                       \ rS rSrSrSrg)r   C   a  
Generic Python-exception-derived object raised by linalg functions.

General purpose exception class, derived from Python's ValueError
class, programmatically raised in linalg functions when a Linear
Algebra-related condition would prevent further correct execution of the
function.

Parameters
----------
None

Examples
--------
>>> from numpy import linalg as LA
>>> LA.inv(np.zeros((2,2)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "...linalg.py", line 350,
    in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
  File "...linalg.py", line 249,
    in solve
    raise LinAlgError('Singular matrix')
numpy.linalg.LinAlgError: Singular matrix

rQ   N)rS   rT   rU   rV   __doc__rX   rQ   rY   rZ   r   r   C   s    rY   r   c                      [        5       n U S   n[        SSSSS9   [        5       S   nS S S 5        UWS /$ ! , (       d  f       N= f)Nr   callignore)invalidoverr?   under   )r3   r2   )errobjbufsizeinvalid_call_errmasks      rZ   _determine_error_statesr|   a   sO    [FQiG	&x!
3({1~
3 )400	
3 
3s	   7
Ac                     [        S5      e)NzSingular matrixr   errflags     rZ   _raise_linalgerror_singularr   o   s    
'
((rY   c                     [        S5      e)NzMatrix is not positive definiter~   r   s     rZ   _raise_linalgerror_nonposdefr   r   s    
7
88rY   c                     [        S5      e)NzEigenvalues did not converger~   r   s     rZ   -_raise_linalgerror_eigenvalues_nonconvergencer   u   s    
4
55rY   c                     [        S5      e)NzSVD did not converger~   r   s     rZ   %_raise_linalgerror_svd_nonconvergencer   x   s    
,
--rY   c                     [        S5      e)Nz,SVD did not converge in Linear Least Squaresr~   r   s     rZ   _raise_linalgerror_lstsqr   {   s    
D
EErY   c                     [        S5      e)Nz:Incorrect argument found while performing QR factorizationr~   r   s     rZ   _raise_linalgerror_qrr   ~   s    
 ) * *rY   c                 ,    [        [        5      nXS'   U$ )Nr   )list_linalg_error_extobj)callbackextobjs     rZ   get_linalg_error_extobjr      s    &'F1IMrY   c                 L    [        U 5      n[        U SUR                  5      nX4$ )N__array_prepare__)r   getattr__array_wrap__)anewwraps      rZ   
_makearrayr      s(    
!*C1)3+=+=>D9rY   c                 "    [        U [        5      $ N)
issubclassr'   )ts    rZ   isComplexTyper      s    a))rY   c                 ,    [         R                  X5      $ r   )_real_types_mapgetr   defaults     rZ   	_realTyper      s    q**rY   c                 ,    [         R                  X5      $ r   )_complex_types_mapr   r   s     rZ   _complexTyper      s    !!!--rY   c                  r   [         nSnU  H  nUR                  R                  n[        U[        5      (       aV  [        U5      (       a  Sn[        US S9nU[        L a  [        nM[  Uc$  [        SUR                  R                  < S35      eM  [        nM     U(       a  [        U   n[        U4$ [        U4$ )NFT)r   zarray type z is unsupported in linalg)r"   dtypetyper   r&   r   r   r#   	TypeErrornamer   r%   )arraysresult_type
is_complexr   type_rts         rZ   _commonTyper      s    KJeW%%U##!
5$/BV|$!( ) ) 
 !K  (5##{""rY   c            	          / nU  Ha  nUR                   R                  S;  a3  UR                  [        X"R                   R	                  S5      S95        MP  UR                  U5        Mc     [        U5      S:X  a  US   $ U$ )N)=|r   r   rx   r   )r   	byteorderappendr   newbyteorderlen)r   retarrs      rZ   _to_native_byte_orderr      si    
C99j0JJws))*@*@*EFGJJsO	 
 3x1}1v
rY   c                  f    U  H+  nUR                   S:w  d  M  [        SUR                   -  5      e   g )Nr   z9%d-dimensional array given. Array must be two-dimensionalndimr   r   r   s     rZ   
_assert_2dr      s5    66Q; &()/ 0 0 rY   c                  f    U  H+  nUR                   S:  d  M  [        SUR                   -  5      e   g )Nr   zB%d-dimensional array given. Array must be at least two-dimensionalr   r   s     rZ   _assert_stacked_2dr      s5    66A: /128 9 9 rY   c                  X    U  H$  nUR                   SS  u  p#X#:w  d  M  [        S5      e   g )Nz-Last 2 dimensions of the array must be square)shaper   )r   r   mns       rZ   _assert_stacked_squarer      s.    wwrs|6MNN rY   c                  h    U  H,  n[        U5      R                  5       (       a  M#  [        S5      e   g )Nz#Array must not contain infs or NaNs)r0   r)   r   r   s     rZ   _assert_finiter      s)    {  CDD rY   c                 d    U R                   S:H  =(       a    [        U R                  SS  5      S:H  $ )Nr   r   )sizer7   r   )r   s    rZ   _is_empty_2dr      s)    88q=6T#))BC.1Q66rY   c                     [        U SS5      $ )z
Transpose each matrix in a stack of matrices.

Unlike np.transpose, this only swaps the last two axes, rather than all of
them

Parameters
----------
a : (...,M,N) array_like

Returns
-------
aT : (...,N,M) ndarray
r   )r>   r   s    rZ   	transposer      s     Ar2rY   c                     X4$ r   rQ   )r   baxess      rZ   _tensorsolve_dispatcherr      	    6MrY   c                    [        U 5      u  p[        U5      nU R                  nUbQ  [        [	        SU5      5      nU H%  nUR                  U5        UR                  XF5        M'     U R                  U5      n U R                  XAR                  -
  * S nSnU H  nX-  nM	     U R                  US-  :w  a  [        S5      eU R                  X5      n UR                  5       nU" [        X5      5      n	Xyl        U	$ )az  
Solve the tensor equation ``a x = b`` for x.

It is assumed that all indices of `x` are summed over in the product,
together with the rightmost indices of `a`, as is done in, for example,
``tensordot(a, x, axes=x.ndim)``.

Parameters
----------
a : array_like
    Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
    the shape of that sub-tensor of `a` consisting of the appropriate
    number of its rightmost indices, and must be such that
    ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
    'square').
b : array_like
    Right-hand tensor, which can be of any shape.
axes : tuple of ints, optional
    Axes in `a` to reorder to the right, before inversion.
    If None (default), no reordering is done.

Returns
-------
x : ndarray, shape Q

Raises
------
LinAlgError
    If `a` is singular or not 'square' (in the above sense).

See Also
--------
numpy.tensordot, tensorinv, numpy.einsum

Examples
--------
>>> a = np.eye(2*3*4)
>>> a.shape = (2*3, 4, 2, 3, 4)
>>> b = np.random.randn(2*3, 4)
>>> x = np.linalg.tensorsolve(a, b)
>>> x.shape
(2, 3, 4)
>>> np.allclose(np.tensordot(a, x, axes=3), b)
True

Nr   rx   r   zfInput arrays must satisfy the requirement             prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim]))r   r   r   r   rangeremoveinsertr   r   r   r   reshaperavelr   )
r   r   r   r   anallaxeskoldshaper7   ress
             rZ   r   r      s    ` mGA
A	
BuQ|$ANN1NN2!  KK wwFF|}%HD	  	vv>
 	

 	
		$A		A
uQ{
CIJrY   c                     X4$ r   rQ   )r   r   s     rZ   _solve_dispatcherr   E  r   rY   c                 x   [        U 5      u  p[        U 5        [        U 5        [        U5      u  p[        X5      u  pEUR                  U R                  S-
  :X  a  [
        R                  nO[
        R                  n[        U5      (       a  SOSn[        [        5      nU" XXxS9n	U" U	R                  USS95      $ )a  
Solve a linear matrix equation, or system of linear scalar equations.

Computes the "exact" solution, `x`, of the well-determined, i.e., full
rank, linear matrix equation `ax = b`.

Parameters
----------
a : (..., M, M) array_like
    Coefficient matrix.
b : {(..., M,), (..., M, K)}, array_like
    Ordinate or "dependent variable" values.

Returns
-------
x : {(..., M,), (..., M, K)} ndarray
    Solution to the system a x = b.  Returned shape is identical to `b`.

Raises
------
LinAlgError
    If `a` is singular or not square.

See Also
--------
scipy.linalg.solve : Similar function in SciPy.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The solutions are computed using LAPACK routine ``_gesv``.

`a` must be square and of full-rank, i.e., all rows (or, equivalently,
columns) must be linearly independent; if either is not true, use
`lstsq` for the least-squares best "solution" of the
system/equation.

References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
       FL, Academic Press, Inc., 1980, pg. 22.

Examples
--------
Solve the system of equations ``x0 + 2 * x1 = 1`` and ``3 * x0 + 5 * x1 = 2``:

>>> a = np.array([[1, 2], [3, 5]])
>>> b = np.array([1, 2])
>>> x = np.linalg.solve(a, b)
>>> x
array([-1.,  1.])

Check that the solution is correct:

>>> np.allclose(np.dot(a, x), b)
True

rx   DD->Ddd->d	signaturer   Fcopy)r   r   r   r   r   rJ   solve1r   r   r   r   astype)
r   r   _r   r   result_tgufuncr   r   rs
             rZ   r   r   I  s    B a=DAq1mGAa#KA 	vv!%%$$(++I$%@AFqy8A.//rY   c                     U 4$ r   rQ   )r   inds     rZ   _tensorinv_dispatcherr     	    4KrY   c                     [        U 5      n U R                  nSnUS:  a  X!S USU -   nX!S  H  nX5-  nM	     O[        S5      eU R                  US5      n [	        U 5      nUR                  " U6 $ )a  
Compute the 'inverse' of an N-dimensional array.

The result is an inverse for `a` relative to the tensordot operation
``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
tensordot operation.

Parameters
----------
a : array_like
    Tensor to 'invert'. Its shape must be 'square', i. e.,
    ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
ind : int, optional
    Number of first indices that are involved in the inverse sum.
    Must be a positive integer, default is 2.

Returns
-------
b : ndarray
    `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.

Raises
------
LinAlgError
    If `a` is singular or not 'square' (in the above sense).

See Also
--------
numpy.tensordot, tensorsolve

Examples
--------
>>> a = np.eye(4*6)
>>> a.shape = (4, 6, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=2)
>>> ainv.shape
(8, 3, 4, 6)
>>> b = np.random.randn(4, 6)
>>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
True

>>> a = np.eye(4*6)
>>> a.shape = (24, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=1)
>>> ainv.shape
(8, 3, 24)
>>> b = np.random.randn(24)
>>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
True

rx   r   NzInvalid ind argument.r   )r   r   
ValueErrorr   r   )r   r   r   r7   invshaper   ias          rZ   r   r     s    l 	
AwwHD
QwD>HTcN2$AID   011			$A	QB::x  rY   c                     U 4$ r   rQ   r   s    rZ   _unary_dispatcherr     r   rY   c                     [        U 5      u  p[        U 5        [        U 5        [        U 5      u  p#[	        U5      (       a  SOSn[        [        5      n[        R                  " XUS9nU" UR                  USS95      $ )a  
Compute the (multiplicative) inverse of a matrix.

Given a square matrix `a`, return the matrix `ainv` satisfying
``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.

Parameters
----------
a : (..., M, M) array_like
    Matrix to be inverted.

Returns
-------
ainv : (..., M, M) ndarray or matrix
    (Multiplicative) inverse of the matrix `a`.

Raises
------
LinAlgError
    If `a` is not square or inversion fails.

See Also
--------
scipy.linalg.inv : Similar function in SciPy.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

Examples
--------
>>> from numpy.linalg import inv
>>> a = np.array([[1., 2.], [3., 4.]])
>>> ainv = inv(a)
>>> np.allclose(np.dot(a, ainv), np.eye(2))
True
>>> np.allclose(np.dot(ainv, a), np.eye(2))
True

If a is a matrix object, then the return value is a matrix as well:

>>> ainv = inv(np.matrix(a))
>>> ainv
matrix([[-2. ,  1. ],
        [ 1.5, -0.5]])

Inverses of several matrices can be computed at once:

>>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
>>> inv(a)
array([[[-2.  ,  1.  ],
        [ 1.5 , -0.5 ]],
       [[-1.25,  0.75],
        [ 0.75, -0.25]]])

D->Dd->dr   Fr   )
r   r   r   r   r   r   r   rJ   r   r   )r   r   r   r   r   r   ainvs          rZ   r   r     sq    | mGAq1a.KA'**I$%@AFQFCDH5122rY   c                     U 4$ r   rQ   )r   r   s     rZ   _matrix_power_dispatcherr  5  r   rY   c                    [        U 5      n [        U 5        [        U 5         [        R                  " U5      nU R                  [        :w  a  [        nO"U R                  S:X  a  [        nO[        S5      eUS:X  a1  [        U 5      n [        U R                  S   U R                  S9U S'   U $ US:  a  [        U 5      n [!        U5      nUS	:X  a  U $ US:X  a  U" X 5      $ US
:X  a  U" U" X 5      U 5      $ S=pEUS:  a7  Uc  U OU" XD5      n[#        US5      u  pU(       a  Uc  UOU" XT5      nUS:  a  M7  U$ ! [
         a  n[        S5      UeSnAff = f)a  
Raise a square matrix to the (integer) power `n`.

For positive integers `n`, the power is computed by repeated matrix
squarings and matrix multiplications. If ``n == 0``, the identity matrix
of the same shape as M is returned. If ``n < 0``, the inverse
is computed and then raised to the ``abs(n)``.

.. note:: Stacks of object matrices are not currently supported.

Parameters
----------
a : (..., M, M) array_like
    Matrix to be "powered".
n : int
    The exponent can be any integer or long integer, positive,
    negative, or zero.

Returns
-------
a**n : (..., M, M) ndarray or matrix object
    The return value is the same shape and type as `M`;
    if the exponent is positive or zero then the type of the
    elements is the same as those of `M`. If the exponent is
    negative the elements are floating-point.

Raises
------
LinAlgError
    For matrices that are not square or that (for negative powers) cannot
    be inverted numerically.

Examples
--------
>>> from numpy.linalg import matrix_power
>>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
>>> matrix_power(i, 3) # should = -i
array([[ 0, -1],
       [ 1,  0]])
>>> matrix_power(i, 0)
array([[1, 0],
       [0, 1]])
>>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
array([[ 0.,  1.],
       [-1.,  0.]])

Somewhat more sophisticated example

>>> q = np.zeros((4, 4))
>>> q[0:2, 0:2] = -i
>>> q[2:4, 2:4] = i
>>> q # one of the three quaternion units not equal to 1
array([[ 0., -1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.],
       [ 0.,  0., -1.,  0.]])
>>> matrix_power(q, 2) # = -np.eye(4)
array([[-1.,  0.,  0.,  0.],
       [ 0., -1.,  0.,  0.],
       [ 0.,  0., -1.,  0.],
       [ 0.,  0.,  0., -1.]])

zexponent must be an integerNr   z6matrix_power not supported for stacks of object arraysr   r   r   .rx      )r;   r   r   operatorindexr   r   objectr=   r   r+   NotImplementedErrorr    rI   r   r   r8   divmod)r   r   efmatmulzresultbits          rZ   r   r   9  sZ   B 	1Aq1>NN1 	ww&	
1!DF 	F 	AvqMQWWR[0#	
QFF 	Av	
aq}	
awq}a((
 A
a%A1 .Qgf.@F	 a% MU  >56A=>s   D6 6
E EEc                    [        [        5      n[        R                  n[	        U 5      u  p[        U 5        [        U 5        [        U 5      u  pE[        U5      (       a  SOSnU" XUS9nU" UR                  USS95      $ )a  
Cholesky decomposition.

Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
where `L` is lower-triangular and .H is the conjugate transpose operator
(which is the ordinary transpose if `a` is real-valued).  `a` must be
Hermitian (symmetric if real-valued) and positive-definite. No
checking is performed to verify whether `a` is Hermitian or not.
In addition, only the lower-triangular and diagonal elements of `a`
are used. Only `L` is actually returned.

Parameters
----------
a : (..., M, M) array_like
    Hermitian (symmetric if all elements are real), positive-definite
    input matrix.

Returns
-------
L : (..., M, M) array_like
    Lower-triangular Cholesky factor of `a`.  Returns a matrix object if
    `a` is a matrix object.

Raises
------
LinAlgError
   If the decomposition fails, for example, if `a` is not
   positive-definite.

See Also
--------
scipy.linalg.cholesky : Similar function in SciPy.
scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
                               positive-definite matrix.
scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
                          `scipy.linalg.cho_solve`.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The Cholesky decomposition is often used as a fast way of solving

.. math:: A \mathbf{x} = \mathbf{b}

(when `A` is both Hermitian/symmetric and positive-definite).

First, we solve for :math:`\mathbf{y}` in

.. math:: L \mathbf{y} = \mathbf{b},

and then for :math:`\mathbf{x}` in

.. math:: L.H \mathbf{x} = \mathbf{y}.

Examples
--------
>>> A = np.array([[1,-2j],[2j,5]])
>>> A
array([[ 1.+0.j, -0.-2.j],
       [ 0.+2.j,  5.+0.j]])
>>> L = np.linalg.cholesky(A)
>>> L
array([[1.+0.j, 0.+0.j],
       [0.+2.j, 1.+0.j]])
>>> np.dot(L, L.T.conj()) # verify that L * L.H = A
array([[1.+0.j, 0.-2.j],
       [0.+2.j, 5.+0.j]])
>>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
>>> np.linalg.cholesky(A) # an ndarray object is returned
array([[1.+0.j, 0.+0.j],
       [0.+2.j, 1.+0.j]])
>>> # But a matrix object is returned if A is a matrix object
>>> np.linalg.cholesky(np.matrix(A))
matrix([[ 1.+0.j,  0.+0.j],
        [ 0.+2.j,  1.+0.j]])

r   r   r   Fr   )
r   r   rJ   cholesky_lor   r   r   r   r   r   )r   r   r   r   r   r   r   r   s           rZ   r   r     sv    h %%ABF&&FmGAq1a.KA'**Iqf5A.//rY   c                     U 4$ r   rQ   )r   modes     rZ   _qr_dispatcherr    r   rY   c                    US;  ah  US;   a.  SR                  S5      n[        R                  " U[        SS9  SnO4US;   a  S	n[        R                  " U[        SS9  S
nO[	        SU S35      e[        U 5      u  p[        U 5        U R                  SS u  pE[        U 5      u  pgU R                  USS9n [        U 5      n [        XE5      nXE::  a  [        R                  n	O[        R                  n	[        U5      (       a  SOSn
[!        ["        5      nU	" X
US9nUS:X  a-  [%        U SSU2SS24   5      nUR                  USS9nU" U5      $ US:X  a5  ['        U 5      nUR                  USS9nUR                  USS9nU" U5      U4$ US
:X  a  U R                  USS9n U" U 5      $ US:X  a  XE:  a  Un[        R(                  n	OUn[        R*                  n	[        U5      (       a  SOSn
[!        ["        5      nU	" XXS9n[%        U SSU2SS24   5      nUR                  USS9nUR                  USS9n[-        U" U5      U" U5      5      $ )a  
Compute the qr factorization of a matrix.

Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
upper-triangular.

Parameters
----------
a : array_like, shape (..., M, N)
    An array-like object with the dimensionality of at least 2.
mode : {'reduced', 'complete', 'r', 'raw'}, optional
    If K = min(M, N), then

    * 'reduced'  : returns Q, R with dimensions (..., M, K), (..., K, N) (default)
    * 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
    * 'r'        : returns R only with dimensions (..., K, N)
    * 'raw'      : returns h, tau with dimensions (..., N, M), (..., K,)

    The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
    see the notes for more information. The default is 'reduced', and to
    maintain backward compatibility with earlier versions of numpy both
    it and the old default 'full' can be omitted. Note that array h
    returned in 'raw' mode is transposed for calling Fortran. The
    'economic' mode is deprecated.  The modes 'full' and 'economic' may
    be passed using only the first letter for backwards compatibility,
    but all others must be spelled out. See the Notes for more
    explanation.


Returns
-------
When mode is 'reduced' or 'complete', the result will be a namedtuple with
the attributes `Q` and `R`.

Q : ndarray of float or complex, optional
    A matrix with orthonormal columns. When mode = 'complete' the
    result is an orthogonal/unitary matrix depending on whether or not
    a is real/complex. The determinant may be either +/- 1 in that
    case. In case the number of dimensions in the input array is
    greater than 2 then a stack of the matrices with above properties
    is returned.
R : ndarray of float or complex, optional
    The upper-triangular matrix or a stack of upper-triangular
    matrices if the number of dimensions in the input array is greater
    than 2.
(h, tau) : ndarrays of np.double or np.cdouble, optional
    The array h contains the Householder reflectors that generate q
    along with r. The tau array contains scaling factors for the
    reflectors. In the deprecated  'economic' mode only h is returned.

Raises
------
LinAlgError
    If factoring fails.

See Also
--------
scipy.linalg.qr : Similar function in SciPy.
scipy.linalg.rq : Compute RQ decomposition of a matrix.

Notes
-----
This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
``dorgqr``, and ``zungqr``.

For more information on the qr factorization, see for example:
https://en.wikipedia.org/wiki/QR_factorization

Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
`a` is of type `matrix`, all the return values will be matrices too.

New 'reduced', 'complete', and 'raw' options for mode were added in
NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'.  In
addition the options 'full' and 'economic' were deprecated.  Because
'full' was the previous default and 'reduced' is the new default,
backward compatibility can be maintained by letting `mode` default.
The 'raw' option was added so that LAPACK routines that can multiply
arrays by q using the Householder reflectors can be used. Note that in
this case the returned arrays are of type np.double or np.cdouble and
the h array is transposed to be FORTRAN compatible.  No routines using
the 'raw' return are currently exposed by numpy, but some are available
in lapack_lite and just await the necessary work.

Examples
--------
>>> a = np.random.randn(9, 6)
>>> Q, R = np.linalg.qr(a)
>>> np.allclose(a, np.dot(Q, R))  # a does equal QR
True
>>> R2 = np.linalg.qr(a, mode='r')
>>> np.allclose(R, R2)  # mode='r' returns the same R as mode='full'
True
>>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
>>> Q, R = np.linalg.qr(a)
>>> Q.shape
(3, 2, 2)
>>> R.shape
(3, 2, 2)
>>> np.allclose(a, np.matmul(Q, R))
True

Example illustrating a common use of `qr`: solving of least squares
problems

What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
and you'll see that it should be y0 = 0, m = 1.)  The answer is provided
by solving the over-determined matrix equation ``Ax = b``, where::

  A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
  x = array([[y0], [m]])
  b = array([[1], [0], [2], [1]])

If A = QR such that Q is orthonormal (which is always possible via
Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``.  (In numpy practice,
however, we simply use `lstsq`.)

>>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
>>> A
array([[0, 1],
       [1, 1],
       [1, 1],
       [2, 1]])
>>> b = np.array([1, 2, 2, 3])
>>> Q, R = np.linalg.qr(A)
>>> p = np.dot(Q.T, b)
>>> np.dot(np.linalg.inv(R), p)
array([  1.,   1.])

)reducedcompleter   raw)ffull )z7The 'full' option is deprecated in favor of 'reduced'.
z,For backward compatibility let mode default.r   
stacklevelr  )r  economicz$The 'economic' option is deprecated.r  zUnrecognized mode ''r   NTr   r   r   r   r   .Fr  r  r   r   )joinwarningswarnDeprecationWarningr   r   r   r   r   r   r   minrJ   
qr_r_raw_m
qr_r_raw_nr   r   r   rH   r   qr_complete
qr_reducedr`   )r   r  msgr   r   r   r   r   mnr   r   r   taur   qmcs                   rZ   r   r     s[   H 66= '' D EC MM#1a@D&&8CMM#1a@D24&:;;mGAq7723<DAa.KA	Aa A	QBv))))'**I$%:;F

7C s{3Q; HHXEH*Awu}aLHHXEH*jjj.Aw|zHHXEH*Aw zae**))(++I$%:;Fq:AQsCRC{^A	&A	&ADGT!W%%rY   c                    [        U 5      u  p[        U 5        [        U 5        [        U 5        [	        U 5      u  p#[        [        5      n[        U5      (       a  SOSn[        R                  " XUS9n[        U5      (       d@  [        UR                  S:H  5      (       a  UR                  n[        U5      nO[        U5      nUR                  USS9$ )a  
Compute the eigenvalues of a general matrix.

Main difference between `eigvals` and `eig`: the eigenvectors aren't
returned.

Parameters
----------
a : (..., M, M) array_like
    A complex- or real-valued matrix whose eigenvalues will be computed.

Returns
-------
w : (..., M,) ndarray
    The eigenvalues, each repeated according to its multiplicity.
    They are not necessarily ordered, nor are they necessarily
    real for real matrices.

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

See Also
--------
eig : eigenvalues and right eigenvectors of general arrays
eigvalsh : eigenvalues of real symmetric or complex Hermitian
           (conjugate symmetric) arrays.
eigh : eigenvalues and eigenvectors of real symmetric or complex
       Hermitian (conjugate symmetric) arrays.
scipy.linalg.eigvals : Similar function in SciPy.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

This is implemented using the ``_geev`` LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.

Examples
--------
Illustration, using the fact that the eigenvalues of a diagonal matrix
are its diagonal elements, that multiplying a matrix on the left
by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
of `Q`), preserves the eigenvalues of the "middle" matrix.  In other words,
if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
``A``:

>>> from numpy import linalg as LA
>>> x = np.random.random()
>>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
>>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
(1.0, 1.0, 0.0)

Now multiply a diagonal matrix by ``Q`` on one side and by ``Q.T`` on the other:

>>> D = np.diag((-1,1))
>>> LA.eigvals(D)
array([-1.,  1.])
>>> A = np.dot(Q, D)
>>> A = np.dot(A, Q.T)
>>> LA.eigvals(A)
array([ 1., -1.]) # random

r   zd->Dr   r   Fr   )r   r   r   r   r   r   r   r   rJ   r   r)   imagrealr   r   r   )r   r   r   r   r   r   ws          rZ   r   r     s    N mGAq11a.KA$57F'**IaVDAqvv{A *H#H-H88H58))rY   c                     U 4$ r   rQ   )r   UPLOs     rZ   _eigvalsh_dispatcherr4  >  r   rY   c                 x   UR                  5       nUS;  a  [        S5      e[        [        5      nUS:X  a  [        R
                  nO[        R                  n[        U 5      u  p[        U 5        [        U 5        [        U 5      u  pV[        U5      (       a  SOSnU" XUS9nUR                  [        U5      SS9$ )	a  
Compute the eigenvalues of a complex Hermitian or real symmetric matrix.

Main difference from eigh: the eigenvectors are not computed.

Parameters
----------
a : (..., M, M) array_like
    A complex- or real-valued matrix whose eigenvalues are to be
    computed.
UPLO : {'L', 'U'}, optional
    Specifies whether the calculation is done with the lower triangular
    part of `a` ('L', default) or the upper triangular part ('U').
    Irrespective of this value only the real parts of the diagonal will
    be considered in the computation to preserve the notion of a Hermitian
    matrix. It therefore follows that the imaginary part of the diagonal
    will always be treated as zero.

Returns
-------
w : (..., M,) ndarray
    The eigenvalues in ascending order, each repeated according to
    its multiplicity.

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

See Also
--------
eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
       (conjugate symmetric) arrays.
eigvals : eigenvalues of general real or complex arrays.
eig : eigenvalues and right eigenvectors of general real or complex
      arrays.
scipy.linalg.eigvalsh : Similar function in SciPy.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.

Examples
--------
>>> from numpy import linalg as LA
>>> a = np.array([[1, -2j], [2j, 5]])
>>> LA.eigvalsh(a)
array([ 0.17157288,  5.82842712]) # may vary

>>> # demonstrate the treatment of the imaginary part of the diagonal
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
>>> a
array([[5.+2.j, 9.-2.j],
       [0.+2.j, 2.-1.j]])
>>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
>>> # with:
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
>>> b
array([[5.+0.j, 0.-2.j],
       [0.+2.j, 2.+0.j]])
>>> wa = LA.eigvalsh(a)
>>> wb = LA.eigvals(b)
>>> wa; wb
array([1., 6.])
array([6.+0.j, 1.+0.j])

Lrk    UPLO argument must be 'L' or 'U'r7  D->dr   r   Fr   )upperr   r   r   rJ   eigvalsh_loeigvalsh_upr   r   r   r   r   r   r   )	r   r3  r   r   r   r   r   r   r1  s	            rZ   r	   r	   B  s    V ::<D:;<<$57Fs{****mGAq1a.KA'**Iqf5A88Ih'e844rY   c                 v    [        U 5      u  pU R                  U5      R                  R                  5       n XU4$ r   )r   r   Tr   )r   r   r   s      rZ   _convertarrayr?    s1    a.KA	A>rY   c                    [        U 5      u  p[        U 5        [        U 5        [        U 5        [	        U 5      u  p#[        [        5      n[        U5      (       a  SOSn[        R                  " XUS9u  pg[        U5      (       dA  [        UR                  S:H  5      (       a$  UR                  nUR                  n[        U5      nO[        U5      nUR                  USS9n[!        UR                  USS9U" U5      5      $ )a  
Compute the eigenvalues and right eigenvectors of a square array.

Parameters
----------
a : (..., M, M) array
    Matrices for which the eigenvalues and right eigenvectors will
    be computed

Returns
-------
A namedtuple with the following attributes:

eigenvalues : (..., M) array
    The eigenvalues, each repeated according to its multiplicity.
    The eigenvalues are not necessarily ordered. The resulting
    array will be of complex type, unless the imaginary part is
    zero in which case it will be cast to a real type. When `a`
    is real the resulting eigenvalues will be real (0 imaginary
    part) or occur in conjugate pairs

eigenvectors : (..., M, M) array
    The normalized (unit "length") eigenvectors, such that the
    column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
    eigenvalue ``eigenvalues[i]``.

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

See Also
--------
eigvals : eigenvalues of a non-symmetric array.
eigh : eigenvalues and eigenvectors of a real symmetric or complex
       Hermitian (conjugate symmetric) array.
eigvalsh : eigenvalues of a real symmetric or complex Hermitian
           (conjugate symmetric) array.
scipy.linalg.eig : Similar function in SciPy that also solves the
                   generalized eigenvalue problem.
scipy.linalg.schur : Best choice for unitary and other non-Hermitian
                     normal matrices.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

This is implemented using the ``_geev`` LAPACK routines which compute
the eigenvalues and eigenvectors of general square arrays.

The number `w` is an eigenvalue of `a` if there exists a vector `v` such
that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
`eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
eigenvalues[i] * eigenvalues[:,i]`` for :math:`i \in \{0,...,M-1\}`.

The array `eigenvectors` may not be of maximum rank, that is, some of the
columns may be linearly dependent, although round-off error may obscure
that fact. If the eigenvalues are all different, then theoretically the
eigenvectors are linearly independent and `a` can be diagonalized by a
similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
a @ eigenvectors`` is diagonal.

For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
is preferred because the matrix `eigenvectors` is guaranteed to be
unitary, which is not the case when using `eig`. The Schur factorization
produces an upper triangular matrix rather than a diagonal matrix, but for
normal matrices only the diagonal of the upper triangular matrix is
needed, the rest is roundoff error.

Finally, it is emphasized that `eigenvectors` consists of the *right* (as
in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
= z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
and, in general, the left and right eigenvectors of a matrix are not
necessarily the (perhaps conjugate) transposes of each other.

References
----------
G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
Academic Press, Inc., 1980, Various pp.

Examples
--------
>>> from numpy import linalg as LA

(Almost) trivial example with real eigenvalues and eigenvectors.

>>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
>>> eigenvalues
array([1., 2., 3.])
>>> eigenvectors
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

Real matrix possessing complex eigenvalues and eigenvectors; note that the
eigenvalues are complex conjugates of each other.

>>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
>>> eigenvalues
array([1.+1.j, 1.-1.j])
>>> eigenvectors
array([[0.70710678+0.j        , 0.70710678-0.j        ],
       [0.        -0.70710678j, 0.        +0.70710678j]])

Complex-valued matrix with real eigenvalues (but complex-valued eigenvectors);
note that ``a.conj().T == a``, i.e., `a` is Hermitian.

>>> a = np.array([[1, 1j], [-1j, 1]])
>>> eigenvalues, eigenvectors = LA.eig(a)
>>> eigenvalues
array([2.+0.j, 0.+0.j])
>>> eigenvectors
array([[ 0.        +0.70710678j,  0.70710678+0.j        ], # may vary
       [ 0.70710678+0.j        , -0.        +0.70710678j]])

Be careful about round-off error!

>>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
>>> # Theor. eigenvalues are 1 +/- 1e-9
>>> eigenvalues, eigenvectors = LA.eig(a)
>>> eigenvalues
array([1., 1.])
>>> eigenvectors
array([[1., 0.],
       [0., 1.]])

zD->DDzd->DDr   g        Fr   )r   r   r   r   r   r   r   r   rJ   r   r)   r/  r0  r   r   r   rM   )r   r   r   r   r   r   r1  vts           rZ   r   r     s    J mGAq11a.KA$57F(++IaVDEAAFFcM 2 2FFWWX&)	8%	(BQXXhUX3T"X>>rY   c                    UR                  5       nUS;  a  [        S5      e[        U 5      u  p[        U 5        [	        U 5        [        U 5      u  p4[        [        5      nUS:X  a  [        R                  nO[        R                  n[        U5      (       a  SOSnU" XUS9u  pUR                  [        U5      SS9nU	R                  USS9n	[        X" U	5      5      $ )	a"  
Return the eigenvalues and eigenvectors of a complex Hermitian
(conjugate symmetric) or a real symmetric matrix.

Returns two objects, a 1-D array containing the eigenvalues of `a`, and
a 2-D square array or matrix (depending on the input type) of the
corresponding eigenvectors (in columns).

Parameters
----------
a : (..., M, M) array
    Hermitian or real symmetric matrices whose eigenvalues and
    eigenvectors are to be computed.
UPLO : {'L', 'U'}, optional
    Specifies whether the calculation is done with the lower triangular
    part of `a` ('L', default) or the upper triangular part ('U').
    Irrespective of this value only the real parts of the diagonal will
    be considered in the computation to preserve the notion of a Hermitian
    matrix. It therefore follows that the imaginary part of the diagonal
    will always be treated as zero.

Returns
-------
A namedtuple with the following attributes:

eigenvalues : (..., M) ndarray
    The eigenvalues in ascending order, each repeated according to
    its multiplicity.
eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
    The column ``eigenvectors[:, i]`` is the normalized eigenvector
    corresponding to the eigenvalue ``eigenvalues[i]``.  Will return a
    matrix object if `a` is a matrix object.

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

See Also
--------
eigvalsh : eigenvalues of real symmetric or complex Hermitian
           (conjugate symmetric) arrays.
eig : eigenvalues and right eigenvectors for non-symmetric arrays.
eigvals : eigenvalues of non-symmetric arrays.
scipy.linalg.eigh : Similar function in SciPy (but also solves the
                    generalized eigenvalue problem).

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
``_heevd``.

The eigenvalues of real symmetric or complex Hermitian matrices are always
real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
`a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.

References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
       FL, Academic Press, Inc., 1980, pg. 222.

Examples
--------
>>> from numpy import linalg as LA
>>> a = np.array([[1, -2j], [2j, 5]])
>>> a
array([[ 1.+0.j, -0.-2.j],
       [ 0.+2.j,  5.+0.j]])
>>> eigenvalues, eigenvectors = LA.eigh(a)
>>> eigenvalues
array([0.17157288, 5.82842712])
>>> eigenvectors
array([[-0.92387953+0.j        , -0.38268343+0.j        ], # may vary
       [ 0.        +0.38268343j,  0.        -0.92387953j]])

>>> np.dot(a, eigenvectors[:, 0]) - eigenvalues[0] * eigenvectors[:, 0] # verify 1st eigenval/vec pair
array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
>>> np.dot(a, eigenvectors[:, 1]) - eigenvalues[1] * eigenvectors[:, 1] # verify 2nd eigenval/vec pair
array([0.+0.j, 0.+0.j])

>>> A = np.matrix(a) # what happens if input is a matrix object
>>> A
matrix([[ 1.+0.j, -0.-2.j],
        [ 0.+2.j,  5.+0.j]])
>>> eigenvalues, eigenvectors = LA.eigh(A)
>>> eigenvalues
array([0.17157288, 5.82842712])
>>> eigenvectors
matrix([[-0.92387953+0.j        , -0.38268343+0.j        ], # may vary
        [ 0.        +0.38268343j,  0.        -0.92387953j]])

>>> # demonstrate the treatment of the imaginary part of the diagonal
>>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
>>> a
array([[5.+2.j, 9.-2.j],
       [0.+2.j, 2.-1.j]])
>>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
>>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
>>> b
array([[5.+0.j, 0.-2.j],
       [0.+2.j, 2.+0.j]])
>>> wa, va = LA.eigh(a)
>>> wb, vb = LA.eig(b)
>>> wa; wb
array([1., 6.])
array([6.+0.j, 1.+0.j])
>>> va; vb
array([[-0.4472136 +0.j        , -0.89442719+0.j        ], # may vary
       [ 0.        +0.89442719j,  0.        -0.4472136j ]])
array([[ 0.89442719+0.j       , -0.        +0.4472136j],
       [-0.        +0.4472136j,  0.89442719+0.j       ]])

r6  r8  r7  zD->dDd->ddr   Fr   )r:  r   r   r   r   r   r   r   rJ   eigh_loeigh_upr   r   r   r]   )
r   r3  r   r   r   r   r   r   r1  rA  s
             rZ   r   r   D  s    t ::<D:;<<mGAq1a.KA$57Fs{&&&&(++I1&9EA	8$51A	8%	(Bab""rY   c                     U 4$ r   rQ   )r   full_matrices
compute_uv	hermitians       rZ   _svd_dispatcherrJ    r   rY   c                    SSK n[        U 5      u  pU(       a  U(       a  [        U 5      u  pg[        U5      n[	        U5      n[        U5      SSSS24   n	UR                  XSS9nUR                  XiSS9nUR                  XySSSS24   SS9n[        XxSSSS24   -  5      R                  5       n
[        U" U5      Xe" U
5      5      $ [        U 5      n[	        U5      n[        U5      SSSS24   $ [        U 5        [        U 5      u  p[        [        5      nU R                   SS u  pU(       a  U(       a'  X:  a  ["        R$                  nO7["        R&                  nO&X:  a  ["        R(                  nO["        R*                  n[-        U5      (       a  SOSnU" U UUS	9u  pvnUR/                  US
S9nUR/                  [1        U5      S
S9nUR/                  US
S9n[        U" U5      Xe" U5      5      $ X:  a  ["        R2                  nO["        R4                  n[-        U5      (       a  SOSnU" U UUS	9nUR/                  [1        U5      S
S9nU$ )a  
Singular Value Decomposition.

When `a` is a 2D array, and ``full_matrices=False``, then it is
factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
`u` and the Hermitian transpose of `vh` are 2D arrays with
orthonormal columns and `s` is a 1D array of `a`'s singular
values. When `a` is higher-dimensional, SVD is applied in
stacked mode as explained below.

Parameters
----------
a : (..., M, N) array_like
    A real or complex array with ``a.ndim >= 2``.
full_matrices : bool, optional
    If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
    ``(..., N, N)``, respectively.  Otherwise, the shapes are
    ``(..., M, K)`` and ``(..., K, N)``, respectively, where
    ``K = min(M, N)``.
compute_uv : bool, optional
    Whether or not to compute `u` and `vh` in addition to `s`.  True
    by default.
hermitian : bool, optional
    If True, `a` is assumed to be Hermitian (symmetric if real-valued),
    enabling a more efficient method for finding singular values.
    Defaults to False.

    .. versionadded:: 1.17.0

Returns
-------
When `compute_uv` is True, the result is a namedtuple with the following
attribute names:

U : { (..., M, M), (..., M, K) } array
    Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
    size as those of the input `a`. The size of the last two dimensions
    depends on the value of `full_matrices`. Only returned when
    `compute_uv` is True.
S : (..., K) array
    Vector(s) with the singular values, within each vector sorted in
    descending order. The first ``a.ndim - 2`` dimensions have the same
    size as those of the input `a`.
Vh : { (..., N, N), (..., K, N) } array
    Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
    size as those of the input `a`. The size of the last two dimensions
    depends on the value of `full_matrices`. Only returned when
    `compute_uv` is True.

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

See Also
--------
scipy.linalg.svd : Similar function in SciPy.
scipy.linalg.svdvals : Compute singular values of a matrix.

Notes
-----

.. versionchanged:: 1.8.0
   Broadcasting rules apply, see the `numpy.linalg` documentation for
   details.

The decomposition is performed using LAPACK routine ``_gesdd``.

SVD is usually described for the factorization of a 2D matrix :math:`A`.
The higher-dimensional case will be discussed below. In the 2D case, SVD is
written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
:math:`S= \mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
contains the singular values of `a` and `u` and `vh` are unitary. The rows
of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
the eigenvectors of :math:`A A^H`. In both cases the corresponding
(possibly non-zero) eigenvalues are given by ``s**2``.

If `a` has more than two dimensions, then broadcasting rules apply, as
explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
working in "stacked" mode: it iterates over all indices of the first
``a.ndim - 2`` dimensions and for each combination SVD is applied to the
last two indices. The matrix `a` can be reconstructed from the
decomposition with either ``(u * s[..., None, :]) @ vh`` or
``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
function ``np.matmul`` for python versions below 3.5.)

If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
all the return values.

Examples
--------
>>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
>>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)

Reconstruction based on full SVD, 2D case:

>>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
>>> U.shape, S.shape, Vh.shape
((9, 9), (6,), (6, 6))
>>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
True
>>> smat = np.zeros((9, 6), dtype=complex)
>>> smat[:6, :6] = np.diag(S)
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
True

Reconstruction based on reduced SVD, 2D case:

>>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
>>> U.shape, S.shape, Vh.shape
((9, 6), (6,), (6, 6))
>>> np.allclose(a, np.dot(U * S, Vh))
True
>>> smat = np.diag(S)
>>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
True

Reconstruction based on full SVD, 4D case:

>>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
>>> U.shape, S.shape, Vh.shape
((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
True
>>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
True

Reconstruction based on reduced SVD, 4D case:

>>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
>>> U.shape, S.shape, Vh.shape
((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
>>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
True
>>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
True

r   N.r   axisr   zD->DdDzd->dddr   Fr   r9  r   )numpyr   r   rB   r8   rC   take_along_axisr   	conjugateri   r	   rD   r   r   r   r   r   rJ   svd_m_fsvd_n_fsvd_m_ssvd_n_sr   r   r   svd_msvd_n)r   rG  rH  rI  _nxr   susgnsidxrA  r   r   r   r   r   r   r   vhs                      rZ   r   r     s/   X mGA 7DAq'CAA1:c4R4i(D%%cb%9C##A"#5A##ACqL'9#CA13a<001;;=BT!Wab22AAA73"9%%qa.KA$%JKF7723<DAu&..&..u&..&.. -a 0 0Hh	!y@bHHXEH*HHYx(uH5YYxeY,a!T"X..5"((F"((F+A..FF	1	&9HHYx(uH5rY   c                     U 4$ r   rQ   )xps     rZ   _cond_dispatcherr`    r   rY   c                 6   [        U 5      n [        U 5      (       a  [        S5      eUb  US:X  d  US:X  a:  [        U SS9n[	        SS9   US:X  a  US	   US
   -  nOUS
   US	   -  nSSS5        O[        U 5        [        U 5        [        U 5      u  pE[        U5      (       a  SOSn[	        SS9   [        R                  " XS9n[        XSS9[        XqSS9-  nSSS5        WR                  USS9n[        W5      n[        U5      nUR                  5       (       aE  U[        U 5      R                  SS9) -  nUR                  S:  a	  [         X8'   OU(       a	  [         US'   UR                  S:X  a  US   nU$ ! , (       d  f       N= f! , (       d  f       N= f)a  
Compute the condition number of a matrix.

This function is capable of returning the condition number using
one of seven different norms, depending on the value of `p` (see
Parameters below).

Parameters
----------
x : (..., M, N) array_like
    The matrix whose condition number is sought.
p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
    Order of the norm used in the condition number computation:

    =====  ============================
    p      norm for matrices
    =====  ============================
    None   2-norm, computed directly using the ``SVD``
    'fro'  Frobenius norm
    inf    max(sum(abs(x), axis=1))
    -inf   min(sum(abs(x), axis=1))
    1      max(sum(abs(x), axis=0))
    -1     min(sum(abs(x), axis=0))
    2      2-norm (largest sing. value)
    -2     smallest singular value
    =====  ============================

    inf means the `numpy.inf` object, and the Frobenius norm is
    the root-of-sum-of-squares norm.

Returns
-------
c : {float, inf}
    The condition number of the matrix. May be infinite.

See Also
--------
numpy.linalg.norm

Notes
-----
The condition number of `x` is defined as the norm of `x` times the
norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
(root-of-sum-of-squares) or one of a number of other matrix norms.

References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
       Academic Press, Inc., 1980, pg. 285.

Examples
--------
>>> from numpy import linalg as LA
>>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
>>> a
array([[ 1,  0, -1],
       [ 0,  1,  0],
       [ 1,  0,  1]])
>>> LA.cond(a)
1.4142135623730951
>>> LA.cond(a, 'fro')
3.1622776601683795
>>> LA.cond(a, np.inf)
2.0
>>> LA.cond(a, -np.inf)
1.0
>>> LA.cond(a, 1)
2.0
>>> LA.cond(a, -1)
1.0
>>> LA.cond(a, 2)
1.4142135623730951
>>> LA.cond(a, -2)
0.70710678118654746 # may vary
>>> min(LA.svd(a, compute_uv=False))*min(LA.svd(LA.inv(a), compute_uv=False))
0.70710678118654746 # may vary

z#cond is not defined on empty arraysNr   r   FrH  rt   )r)   ).r   ).r   r   r   r   r   r   rL  r   r   rQ   )r   r   r   r   r2   r   r   r   r   rJ   r   r   r   rA   anyr   r*   )	r^  r_  rX  r   r   r   r   invxnan_masks	            rZ   r   r     sx   ` 	
AA?@@yAFa2ge$(#BwgJ6*fI'
*	 $# 	1q!!!n+A..FF	(# $$Q<DQ)Dx,HHA $ HHXEH* 	
AQxH||~~U1X\\x\00066A:AKAbE 	vv{bEH? $# $#s   	E90*F
9
F

Fc                     U 4$ r   rQ   )AtolrI  s      rZ   _matrix_rank_dispatcherrk    r   rY   c                 `   [        U 5      n U R                  S:  a  [        [        U S:H  5      (       + 5      $ [	        U SUS9nUcJ  UR                  SSS9[        U R                  S	S 5      -  [        UR                  5      R                  -  nO[        U5      S
[        4   n[        X1:  SS9$ )a  
Return matrix rank of array using SVD method

Rank of the array is the number of singular values of the array that are
greater than `tol`.

.. versionchanged:: 1.14
   Can now operate on stacks of matrices

Parameters
----------
A : {(M,), (..., M, N)} array_like
    Input vector or stack of matrices.
tol : (...) array_like, float, optional
    Threshold below which SVD values are considered zero. If `tol` is
    None, and ``S`` is an array with singular values for `M`, and
    ``eps`` is the epsilon value for datatype of ``S``, then `tol` is
    set to ``S.max() * max(M, N) * eps``.

    .. versionchanged:: 1.14
       Broadcasted against the stack of matrices
hermitian : bool, optional
    If True, `A` is assumed to be Hermitian (symmetric if real-valued),
    enabling a more efficient method for finding singular values.
    Defaults to False.

    .. versionadded:: 1.14

Returns
-------
rank : (...) array_like
    Rank of A.

Notes
-----
The default threshold to detect rank deficiency is a test on the magnitude
of the singular values of `A`.  By default, we identify singular values less
than ``S.max() * max(M, N) * eps`` as indicating rank deficiency (with
the symbols defined above). This is the algorithm MATLAB uses [1].  It also
appears in *Numerical recipes* in the discussion of SVD solutions for linear
least squares [2].

This default threshold is designed to detect rank deficiency accounting for
the numerical errors of the SVD computation.  Imagine that there is a column
in `A` that is an exact (in floating point) linear combination of other
columns in `A`. Computing the SVD on `A` will not produce a singular value
exactly equal to 0 in general: any difference of the smallest SVD value from
0 will be caused by numerical imprecision in the calculation of the SVD.
Our threshold for small SVD values takes this numerical imprecision into
account, and the default threshold will detect such numerical rank
deficiency.  The threshold may declare a matrix `A` rank deficient even if
the linear combination of some columns of `A` is not exactly equal to
another column of `A` but only numerically very close to another column of
`A`.

We chose our default threshold because it is in wide use.  Other thresholds
are possible.  For example, elsewhere in the 2007 edition of *Numerical
recipes* there is an alternative threshold of ``S.max() *
np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
this threshold as being based on "expected roundoff error" (p 71).

The thresholds above deal with floating point roundoff error in the
calculation of the SVD.  However, you may have more information about the
sources of error in `A` that would make you consider other tolerance values
to detect *effective* rank deficiency.  The most useful measure of the
tolerance depends on the operations you intend to use on your matrix.  For
example, if your data come from uncertain measurements with uncertainties
greater than floating point epsilon, choosing a tolerance near that
uncertainty may be preferable.  The tolerance may be absolute if the
uncertainties are absolute rather than relative.

References
----------
.. [1] MATLAB reference documentation, "Rank"
       https://www.mathworks.com/help/techdoc/ref/rank.html
.. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
       "Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
       page 795.

Examples
--------
>>> from numpy.linalg import matrix_rank
>>> matrix_rank(np.eye(4)) # Full rank matrix
4
>>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
>>> matrix_rank(I)
3
>>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
1
>>> matrix_rank(np.zeros((4,)))
0
r   r   F)rH  rI  Nr   TrM  keepdimsr   .rL  )r   r   intr)   r   maxr   r1   r   epsr(   r@   )ri  rj  rI  rl   s       rZ   r   r   !  s    | 	
Avvzs1a4y=!!A%95A
{eede+c!''"#,.??%.BTBTTcl3<(r**rY   c                     U 4$ r   rQ   )r   rcondrI  s      rZ   _pinv_dispatcherrt    r   rY   c           	         [        U 5      u  p[        U5      n[        U 5      (       a>  U R                  SS u  pE[	        U R                  SS XT4-   U R
                  S9nU" U5      $ U R                  5       n [        U SUS9u  pxn	US[        4   [        USSS	9-  n
X:  n[        S
XUS9nSX) '   [        [        U	5      [        US[        4   [        U5      5      5      nU" U5      $ )a  
Compute the (Moore-Penrose) pseudo-inverse of a matrix.

Calculate the generalized inverse of a matrix using its
singular-value decomposition (SVD) and including all
*large* singular values.

.. versionchanged:: 1.14
   Can now operate on stacks of matrices

Parameters
----------
a : (..., M, N) array_like
    Matrix or stack of matrices to be pseudo-inverted.
rcond : (...) array_like of float
    Cutoff for small singular values.
    Singular values less than or equal to
    ``rcond * largest_singular_value`` are set to zero.
    Broadcasts against the stack of matrices.
hermitian : bool, optional
    If True, `a` is assumed to be Hermitian (symmetric if real-valued),
    enabling a more efficient method for finding singular values.
    Defaults to False.

    .. versionadded:: 1.17.0

Returns
-------
B : (..., N, M) ndarray
    The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
    is `B`.

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

See Also
--------
scipy.linalg.pinv : Similar function in SciPy.
scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
                     Hermitian matrix.

Notes
-----
The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
defined as: "the matrix that 'solves' [the least-squares problem]
:math:`Ax = b`," i.e., if :math:`\bar{x}` is said solution, then
:math:`A^+` is that matrix such that :math:`\bar{x} = A^+b`.

It can be shown that if :math:`Q_1 \Sigma Q_2^T = A` is the singular
value decomposition of A, then
:math:`A^+ = Q_2 \Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
orthogonal matrices, :math:`\Sigma` is a diagonal matrix consisting
of A's so-called singular values, (followed, typically, by
zeros), and then :math:`\Sigma^+` is simply the diagonal matrix
consisting of the reciprocals of A's singular values
(again, followed by zeros). [1]_

References
----------
.. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
       FL, Academic Press, Inc., 1980, pp. 139-142.

Examples
--------
The following example checks that ``a * a+ * a == a`` and
``a+ * a * a+ == a+``:

>>> a = np.random.randn(9, 6)
>>> B = np.linalg.pinv(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True

r   Nr   F)rG  rI  .r   Trm  rx   )whereoutr   )r   r   r   r   r   r   rP  r   r(   r6   r?   r=   r   r-   )r   rs  rI  r   r   r   r   rY  rX  rA  cutofflarges               rZ   r
   r
     s    ^ mGAENEAwwrs|AGGCRLA6)9Cy	A1EY?HA" 3< 4T#BBFJEq!a(AAfI
23<)A, G
HC9rY   c                     [        U 5      n [        U 5        [        U 5        [        U 5      u  p[	        U5      n[        U5      (       a  SOSn[        R                  " XS9u  pVUR                  " USS9nUR                  USS9n[        XV5      $ )a  
Compute the sign and (natural) logarithm of the determinant of an array.

If an array has a very small or very large determinant, then a call to
`det` may overflow or underflow. This routine is more robust against such
issues, because it computes the logarithm of the determinant rather than
the determinant itself.

Parameters
----------
a : (..., M, M) array_like
    Input array, has to be a square 2-D array.

Returns
-------
A namedtuple with the following attributes:

sign : (...) array_like
    A number representing the sign of the determinant. For a real matrix,
    this is 1, 0, or -1. For a complex matrix, this is a complex number
    with absolute value 1 (i.e., it is on the unit circle), or else 0.
logabsdet : (...) array_like
    The natural log of the absolute value of the determinant.

If the determinant is zero, then `sign` will be 0 and `logabsdet` will be
-Inf. In all cases, the determinant is equal to ``sign * np.exp(logabsdet)``.

See Also
--------
det

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

.. versionadded:: 1.6.0

The determinant is computed via LU factorization using the LAPACK
routine ``z/dgetrf``.


Examples
--------
The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:

>>> a = np.array([[1, 2], [3, 4]])
>>> (sign, logabsdet) = np.linalg.slogdet(a)
>>> (sign, logabsdet)
(-1, 0.69314718055994529) # may vary
>>> sign * np.exp(logabsdet)
-2.0

Computing log-determinants for a stack of matrices:

>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
>>> a.shape
(3, 2, 2)
>>> sign, logabsdet = np.linalg.slogdet(a)
>>> (sign, logabsdet)
(array([-1., -1., -1.]), array([ 0.69314718,  1.09861229,  2.07944154]))
>>> sign * np.exp(logabsdet)
array([-2., -3., -8.])

This routine succeeds where ordinary `det` does not:

>>> np.linalg.det(np.eye(500) * 0.1)
0.0
>>> np.linalg.slogdet(np.eye(500) * 0.1)
(1, -1151.2925464970228)

zD->DdrC  rc  Fr   )
r   r   r   r   r   r   rJ   r   r   re   )r   r   r   real_tr   rB   logdets          rZ   r   r     s    Z 	
Aq1a.KAx F(++I ((@LD;;xe,D]]6].F&&rY   c                     [        U 5      n [        U 5        [        U 5        [        U 5      u  p[	        U5      (       a  SOSn[
        R                  " XS9nUR                  USS9nU$ )a  
Compute the determinant of an array.

Parameters
----------
a : (..., M, M) array_like
    Input array to compute determinants for.

Returns
-------
det : (...) array_like
    Determinant of `a`.

See Also
--------
slogdet : Another way to represent the determinant, more suitable
  for large matrices where underflow/overflow may occur.
scipy.linalg.det : Similar function in SciPy.

Notes
-----

.. versionadded:: 1.8.0

Broadcasting rules apply, see the `numpy.linalg` documentation for
details.

The determinant is computed via LU factorization using the LAPACK
routine ``z/dgetrf``.

Examples
--------
The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:

>>> a = np.array([[1, 2], [3, 4]])
>>> np.linalg.det(a)
-2.0 # may vary

Computing determinants for a stack of matrices:

>>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
>>> a.shape
(3, 2, 2)
>>> np.linalg.det(a)
array([-2., -3., -8.])

r   r   rc  Fr   )r   r   r   r   r   rJ   r   r   )r   r   r   r   r   s        rZ   r   r   N  sa    b 	
Aq1a.KA'**I!1A	&AHrY   c                     X4$ r   rQ   )r   r   rs  s      rZ   _lstsq_dispatcherr    r   rY   c                    [        U 5      u  p[        U5      u  pUR                  S:H  nU(       a  USS2[        4   n[        X5        U R                  SS u  pgUR                  SS u  pXh:w  a  [        S5      e[        X5      u  p[        U5      nUS:X  a  [        R                  " S[        SS9  S	nUc!  [        U
5      R                  [        Xv5      -  nXg::  a  [        R                  nO[        R                   n[#        U
5      (       a  S
OSn[%        [&        5      nU	S:X  a(  [)        UR                  SS XiS-   4-   UR*                  S9nU" XX.US9u  nnnnUS:X  a  SUS'   U	S:X  a  USSU	24   nUSSU	24   nU(       a  UR-                  S	S9nUU:w  d  Xg::  a  [/        / U5      nUR1                  USS9nUR1                  USS9nUR1                  USS9nU" U5      U" U5      UU4$ )a  
Return the least-squares solution to a linear matrix equation.

Computes the vector `x` that approximately solves the equation
``a @ x = b``. The equation may be under-, well-, or over-determined
(i.e., the number of linearly independent rows of `a` can be less than,
equal to, or greater than its number of linearly independent columns).
If `a` is square and of full rank, then `x` (but for round-off error)
is the "exact" solution of the equation. Else, `x` minimizes the
Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
solutions, the one with the smallest 2-norm :math:`||x||` is returned.

Parameters
----------
a : (M, N) array_like
    "Coefficient" matrix.
b : {(M,), (M, K)} array_like
    Ordinate or "dependent variable" values. If `b` is two-dimensional,
    the least-squares solution is calculated for each of the `K` columns
    of `b`.
rcond : float, optional
    Cut-off ratio for small singular values of `a`.
    For the purposes of rank determination, singular values are treated
    as zero if they are smaller than `rcond` times the largest singular
    value of `a`.

    .. versionchanged:: 1.14.0
       If not set, a FutureWarning is given. The previous default
       of ``-1`` will use the machine precision as `rcond` parameter,
       the new default will use the machine precision times `max(M, N)`.
       To silence the warning and use the new default, use ``rcond=None``,
       to keep using the old behavior, use ``rcond=-1``.

Returns
-------
x : {(N,), (N, K)} ndarray
    Least-squares solution. If `b` is two-dimensional,
    the solutions are in the `K` columns of `x`.
residuals : {(1,), (K,), (0,)} ndarray
    Sums of squared residuals: Squared Euclidean 2-norm for each column in
    ``b - a @ x``.
    If the rank of `a` is < N or M <= N, this is an empty array.
    If `b` is 1-dimensional, this is a (1,) shape array.
    Otherwise the shape is (K,).
rank : int
    Rank of matrix `a`.
s : (min(M, N),) ndarray
    Singular values of `a`.

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

See Also
--------
scipy.linalg.lstsq : Similar function in SciPy.

Notes
-----
If `b` is a matrix, then all array results are returned as matrices.

Examples
--------
Fit a line, ``y = mx + c``, through some noisy data-points:

>>> x = np.array([0, 1, 2, 3])
>>> y = np.array([-1, 0.2, 0.9, 2.1])

By examining the coefficients, we see that the line should have a
gradient of roughly 1 and cut the y-axis at, more or less, -1.

We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
and ``p = [[m], [c]]``.  Now use `lstsq` to solve for `p`:

>>> A = np.vstack([x, np.ones(len(x))]).T
>>> A
array([[ 0.,  1.],
       [ 1.,  1.],
       [ 2.,  1.],
       [ 3.,  1.]])

>>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
>>> m, c
(1.0 -0.95) # may vary

Plot the data along with the fitted line:

>>> import matplotlib.pyplot as plt
>>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
>>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
>>> _ = plt.legend()
>>> plt.show()

rx   Nr   zIncompatible dimensionsr"  a
  `rcond` parameter will change to the default of machine precision times ``max(M, N)`` where M and N are the input matrix dimensions.
To use the future default and silence this warning we advise to pass `rcond=None`, to keep using the old, explicitly pass `rcond=-1`.r   r  r   z	DDd->Ddidz	ddd->ddidr   r   r   .rL  Fr   T)r   r   r(   r   r   r   r   r   r!  r"  FutureWarningr1   rq  rp  rJ   lstsq_mlstsq_nr   r   r   r   r   squeezer   r   )r   r   rs  r   r   is_1dr   r   m2n_rhsr   r   result_real_tr   r   r   r^  residsrankrX  s                       rZ   r   r     s   B a=DAmGAFFaKEajMq7723<DAIBw344a#KAh'M  4 $	3 }as1y(v&&&&,Q//[I$%=>Fz!''#2,!QY/qww?ePAvtQAv#zc6E6kNVeV$ II2I
 qyAFr=) 	
U+A]]=u]5F	%A7DL$))rY   c                 @    [        XU4S5      nU" [        USS9SS9nU$ )a  Compute a function of the singular values of the 2-D matrices in `x`.

This is a private utility function used by `numpy.linalg.norm()`.

Parameters
----------
x : ndarray
row_axis, col_axis : int
    The axes of `x` that hold the 2-D matrices.
op : callable
    This should be either numpy.amin or `numpy.amax` or `numpy.sum`.

Returns
-------
result : float or ndarray
    If `x` is 2-D, the return values is a float.
    Otherwise, it is an array with ``x.ndim - 2`` dimensions.
    The return values are either the minimum or maximum or sum of the
    singular values of the matrices, depending on whether `op`
    is `numpy.amin` or `numpy.amax` or `numpy.sum`.

rd  Frb  r   rL  )r4   r   )r^  row_axiscol_axisopyr  s         rZ   _multi_svd_normr  /	  s-    . 	x((3AA%(r2FMrY   c                     U 4$ r   rQ   )r^  ordrM  rn  s       rZ   _norm_dispatcherr  K	  r   rY   c                 	   [        U 5      n [        U R                  R                  [        [
        45      (       d  U R                  [        5      n Uc  U R                  nUb  US;   a  US:X  d  US:X  a  US:X  a  U R                  SS9n [        U R                  R                  5      (       a<  U R                  nU R                  nUR                  U5      UR                  U5      -   nOU R                  U 5      n[        U5      nU(       a  UR                  US/-  5      nU$ U R                  n	Uc  [!        [#        U	5      5      nO$[%        U[         5      (       d   ['        U5      nU4n[-        U5      S:X  GaH  U[.        :X  a  [1        U 5      R3                  X#S9$ U[.        * :X  a  [1        U 5      R5                  X#S9$ US	:X  a5  U S	:g  R                  U R                  R                  5      R7                  X#S9$ US:X  a  [8        R:                  " [1        U 5      X#S9$ Ub  US:X  a;  U R=                  5       U -  R                  n[        [8        R:                  " XUS95      $ [%        U[>        5      (       a  [A        S
U S35      e[1        U 5      nX-  n[8        R:                  " XUS9nU[C        XR                  S9-  nU$ [-        U5      S:X  Ga  Uu  p[E        X5      n[E        X5      nX:X  a  [A        S5      eUS:X  a  [G        XU[H        5      nGOvUS:X  a  [G        XU[J        5      nGO]US:X  a7  X:  a  US-  n[8        R:                  " [1        U 5      US9R3                  US9nGO U[.        :X  a6  X:  a  US-  n[8        R:                  " [1        U 5      US9R3                  US9nOUS:X  a6  X:  a  US-  n[8        R:                  " [1        U 5      US9R5                  US9nOU[.        * :X  a6  X:  a  US-  n[8        R:                  " [1        U 5      US9R5                  US9nOcUS;   a:  [        [8        R:                  " U R=                  5       U -  R                  US95      nO#US:X  a  [G        XU[6        5      nO[A        S5      eU(       a4  [M        U RN                  5      nSXS	   '   SXS   '   UR                  U5      nU$ [A        S5      e! [(         a  n
[+        S5      U
eSn
A
ff = f)a  
Matrix or vector norm.

This function is able to return one of eight different matrix norms,
or one of an infinite number of vector norms (described below), depending
on the value of the ``ord`` parameter.

Parameters
----------
x : array_like
    Input array.  If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
    is None. If both `axis` and `ord` are None, the 2-norm of
    ``x.ravel`` will be returned.
ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
    Order of the norm (see table under ``Notes``). inf means numpy's
    `inf` object. The default is None.
axis : {None, int, 2-tuple of ints}, optional.
    If `axis` is an integer, it specifies the axis of `x` along which to
    compute the vector norms.  If `axis` is a 2-tuple, it specifies the
    axes that hold 2-D matrices, and the matrix norms of these matrices
    are computed.  If `axis` is None then either a vector norm (when `x`
    is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
    is None.

    .. versionadded:: 1.8.0

keepdims : bool, optional
    If this is set to True, the axes which are normed over are left in the
    result as dimensions with size one.  With this option the result will
    broadcast correctly against the original `x`.

    .. versionadded:: 1.10.0

Returns
-------
n : float or ndarray
    Norm of the matrix or vector(s).

See Also
--------
scipy.linalg.norm : Similar function in SciPy.

Notes
-----
For values of ``ord < 1``, the result is, strictly speaking, not a
mathematical 'norm', but it may still be useful for various numerical
purposes.

The following norms can be calculated:

=====  ============================  ==========================
ord    norm for matrices             norm for vectors
=====  ============================  ==========================
None   Frobenius norm                2-norm
'fro'  Frobenius norm                --
'nuc'  nuclear norm                  --
inf    max(sum(abs(x), axis=1))      max(abs(x))
-inf   min(sum(abs(x), axis=1))      min(abs(x))
0      --                            sum(x != 0)
1      max(sum(abs(x), axis=0))      as below
-1     min(sum(abs(x), axis=0))      as below
2      2-norm (largest sing. value)  as below
-2     smallest singular value       as below
other  --                            sum(abs(x)**ord)**(1./ord)
=====  ============================  ==========================

The Frobenius norm is given by [1]_:

    :math:`||A||_F = [\sum_{i,j} abs(a_{i,j})^2]^{1/2}`

The nuclear norm is the sum of the singular values.

Both the Frobenius and nuclear norm orders are only defined for
matrices and raise a ValueError when ``x.ndim != 2``.

References
----------
.. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
       Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15

Examples
--------
>>> from numpy import linalg as LA
>>> a = np.arange(9) - 4
>>> a
array([-4, -3, -2, ...,  2,  3,  4])
>>> b = a.reshape((3, 3))
>>> b
array([[-4, -3, -2],
       [-1,  0,  1],
       [ 2,  3,  4]])

>>> LA.norm(a)
7.745966692414834
>>> LA.norm(b)
7.745966692414834
>>> LA.norm(b, 'fro')
7.745966692414834
>>> LA.norm(a, np.inf)
4.0
>>> LA.norm(b, np.inf)
9.0
>>> LA.norm(a, -np.inf)
0.0
>>> LA.norm(b, -np.inf)
2.0

>>> LA.norm(a, 1)
20.0
>>> LA.norm(b, 1)
7.0
>>> LA.norm(a, -1)
-4.6566128774142013e-010
>>> LA.norm(b, -1)
6.0
>>> LA.norm(a, 2)
7.745966692414834
>>> LA.norm(b, 2)
7.3484692283495345

>>> LA.norm(a, -2)
0.0
>>> LA.norm(b, -2)
1.8570331885190563e-016 # may vary
>>> LA.norm(a, 3)
5.8480354764257312 # may vary
>>> LA.norm(a, -3)
0.0

Using the `axis` argument to compute vector norms:

>>> c = np.array([[ 1, 2, 3],
...               [-1, 1, 4]])
>>> LA.norm(c, axis=0)
array([ 1.41421356,  2.23606798,  5.        ])
>>> LA.norm(c, axis=1)
array([ 3.74165739,  4.24264069])
>>> LA.norm(c, ord=1, axis=1)
array([ 6.,  6.])

Using the `axis` argument to compute matrix norms:

>>> m = np.arange(8).reshape(2,2,2)
>>> LA.norm(m, axis=(1,2))
array([  3.74165739,  11.22497216])
>>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
(3.7416573867739413, 11.224972160321824)

N)r  fror   rx   K)orderz6'axis' must be None, an integer or a tuple of integersrm  r   zInvalid norm order 'z' for vectorsr   zDuplicate axes given.r   rL  r   )Nr  r  nucz Invalid norm order for matrices.z&Improper number of dimensions to norm.)(r   r   r   r   r&   r<   r   floatr   r   r   r0  r/  r+   r.   r   tupler   
isinstancero  	Exceptionr   r   r*   r8   rp  r$  r/   r,   reduceconjstrr   rE   rF   r  r6   r5   r   r   )r^  r  rM  rn  r   x_realx_imagsqnormr   ndr  rX  absxr  r  	ret_shapes                   rZ   r   r   O	  sM   n 	
AaggllWg$677HHUO |vv[L TQYAX$!)c"AQWW\\**F+fjj.@@qv,Ckk$s(+J 
B|U2Ye$$	]t9D w
4yA~#:q6::4:;;SD[q6::4:;;AXF??166<<044$4RRAX::c!f4CC[C1HA##A

1(CDD S!!3C5FGGq6DLD**Tx@CJs))44CJ	Ta!'5'5455!8"1$?CBY!!x>CAX"A**SV(377X7FCCZ"A**SV(377X7FCBY"A**SV(377X7FCSD["A**SV(377X7FC&&szz1668a<"5"5DABCE\!!x=C?@@QWWI!"I1g!"I1g++i(C
ABBI  	]TU[\\	]s   S 
S/S**S/rw  c             #   ,   #    U  S h  vN   Uv   g  N	7fr   rQ   )r   rw  s     rZ   _multidot_dispatcherr  N
  s     
I s   
c                `   [        U 5      nUS:  a  [        S5      eUS:X  a  [        U S   U S   US9$ U  Vs/ s H  n[        U5      PM     n nU S   R                  U S   R                  pTU S   R                  S:X  a  [        U S   5      U S'   U S   R                  S:X  a  [        U S   5      R                  U S'   [        U 6   US:X  a  [        U S   U S   U S   US9nO[        U 5      n[        XSUS-
  US9nUS:X  a  US:X  a  US   $ US:X  d  US:X  a  UR                  5       $ U$ s  snf )	ai	  
Compute the dot product of two or more arrays in a single function call,
while automatically selecting the fastest evaluation order.

`multi_dot` chains `numpy.dot` and uses optimal parenthesization
of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
this can speed up the multiplication a lot.

If the first argument is 1-D it is treated as a row vector.
If the last argument is 1-D it is treated as a column vector.
The other arguments must be 2-D.

Think of `multi_dot` as::

    def multi_dot(arrays): return functools.reduce(np.dot, arrays)


Parameters
----------
arrays : sequence of array_like
    If the first argument is 1-D it is treated as row vector.
    If the last argument is 1-D it is treated as column vector.
    The other arguments must be 2-D.
out : ndarray, optional
    Output argument. This must have the exact kind that would be returned
    if it was not used. In particular, it must have the right type, must be
    C-contiguous, and its dtype must be the dtype that would be returned
    for `dot(a, b)`. This is a performance feature. Therefore, if these
    conditions are not met, an exception is raised, instead of attempting
    to be flexible.

    .. versionadded:: 1.19.0

Returns
-------
output : ndarray
    Returns the dot product of the supplied arrays.

See Also
--------
numpy.dot : dot multiplication with two arguments.

References
----------

.. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
.. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication

Examples
--------
`multi_dot` allows you to write::

>>> from numpy.linalg import multi_dot
>>> # Prepare some data
>>> A = np.random.random((10000, 100))
>>> B = np.random.random((100, 1000))
>>> C = np.random.random((1000, 5))
>>> D = np.random.random((5, 333))
>>> # the actual dot multiplication
>>> _ = multi_dot([A, B, C, D])

instead of::

>>> _ = np.dot(np.dot(np.dot(A, B), C), D)
>>> # or
>>> _ = A.dot(B).dot(C).dot(D)

Notes
-----
The cost for a matrix multiplication can be calculated with the
following function::

    def cost(A, B):
        return A.shape[0] * A.shape[1] * B.shape[1]

Assume we have three matrices
:math:`A_{10x100}, B_{100x5}, C_{5x50}`.

The costs for the two different parenthesizations are as follows::

    cost((AB)C) = 10*100*5 + 10*5*50   = 5000 + 2500   = 7500
    cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000

r   zExpecting at least two arrays.r   rx   r  r   r  )r   r   )r   r   r+   r;   r   r9   r>  r   _multi_dot_three_multi_dot_matrix_chain_order
_multi_dotr   )r   rw  r   r   
ndim_first	ndim_lastr  r  s           rZ   r   r   S
  sC   l 	FA1u9::	
a6!9fQiS11%+,VjmVF, #1INNF2JOO	 ay~~vay)q	bz!r
+--r
 	Av!&)VAYq	sK-f5F1a!e= Q9>d|	qIN||~3 -s   D+c                     U R                   u  pEUR                   u  pgXF-  XW-   -  nXW-  XF-   -  n	X:  a  [        [        X5      X#S9$ [        U [        X5      US9$ )z
Find the best order for three arrays and do the multiplication.

For three arguments `_multi_dot_three` is approximately 15 times faster
than `_multi_dot_matrix_chain_order`

r  )r   r+   )
ri  BCrw  a0a1b0b1c0c1cost1cost2s
             rZ   r  r  
  s_     wwHBwwHDI#EI#E}3q9a))1c!iS))rY   c                    [        U 5      nU  Vs/ s H  o3R                  S   PM     snU S   R                  S   /-   n[        X"4[        S9n[	        X"4[
        S9n[        SU5       Hq  n[        X'-
  5       H]  nX-   n	[        XXU	4'   [        X5       H=  n
XXU
4   XZS-   U	4   -   XH   XJS-      -  XIS-      -  -   nXX4   :  d  M3  XX4'   XX4'   M?     M_     Ms     U(       a  Xe4$ U$ s  snf )a  
Return a np.array that encodes the optimal order of mutiplications.

The optimal order array is then used by `_multi_dot()` to do the
multiplication.

Also return the cost matrix if `return_costs` is `True`

The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
Chapter 15.2, p. 370-378.  Note that Cormen uses 1-based indices.

    cost[i, j] = min([
        cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
        for k in range(i, j)])

r   r   rx   r   )r   r   r   r#   r   r:   r   r*   )r   return_costsr   r   r_  r   rX  lijr   r,  s               rZ   r  r  
  s	   " 	FA $$VV$r
(8(8(;'<<A 	qfF#A 	qfD!A1a[quAAAdG1[dGa!Qi'!$q1v+a!f*<<w;adGadG	 !   "A6(q(% 	%s   C*c           
      t    X#:X  a	  Ub   eX   $ [        [        XX!X#4   5      [        XXU4   S-   U5      US9$ )z4Actually do the multiplication with the given order.rx   r  )r+   r  )r   r  r  r  rw  s        rZ   r  r  
  sN    v{{y:fQad<fUa4[1_a@ 	rY   r   )r   )r  )r7  )NNN)TTF)NN)NF)gV瞯<F)r"  )NNF)F)rq   __all__	functoolsr  r!  typingr   r   _utilsr   
numpy.corer   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   numpy.core.multiarrayrF   rG   numpy.lib.twodim_baserH   rI   numpy.linalgrJ   numpy._typingrK   rM   r]   r`   re   ri   partialarray_function_dispatchfortran_intr   r   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r  r   r   r4  r	   r?  r   r   rJ  r   r`  r   rk  r   rt  r
   r   r   r  r   r  r  r   r  r   r  r  r  rQ   rY   rZ   <module>r     sO  	'
    "            7   + & !
  z J 
 
 $++%%n>   N*  :1 /0 )96.F*

* FFVV%
 ww) 
   + $ .#2
09OE
7
& 01I 2IX *+Q0 ,Q0h ./@! 0@!J *+E3 ,E3P 12p 3pl *+[0 ,[0@ (G& )G&X *+X* ,X*v -.[5 /[5z *+W? ,W?t -.M# /M#d )C *CL )*s +sl 01e+ 2e+T )*^ +^H *+U' ,U'p *+7 ,7x *+\* ,\*~8 )*yC +yC| )- 
 -.! u /up**&)R
rY   