
    `i7                         d dl Z d dlZd dlmZ d dlZd dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlZd ZddZd	 ZddZd Zd ZddZddZdS )    N)linalg)internal)device)_decomposition)_utilc                 d   ddl m} ddlm}m} | j        dk    r%| j        d          |            k    r || |          S t          j        | |           t          j	        |            t          j
        |            | j        |j        k    s| j        |j        dz   k    r(| j        dd         |j        d| j        dz
           k    st          d          t          j        | |          \  }}|j        dk    rt          j        |j        |          S | j        dk    r]|                     |d	d
          } |                    |d	d
          }|                    | |           |                    |d          S |                     |d	d          } t          j        ||          }| j        dd         }t'          t)          j        |                    D ]V}	t)          j        |	|          }
||
                             |d	d
          }|                    | |
         |           |||
<   W|S )a&  Solves a linear matrix equation.

    It computes the exact solution of ``x`` in ``ax = b``,
    where ``a`` is a square and full rank matrix.

    Args:
        a (cupy.ndarray): The matrix with dimension ``(..., M, M)``.
        b (cupy.ndarray): The matrix with dimension ``(..., M)`` or
            ``(..., M, K)``.

    Returns:
        cupy.ndarray:
            The matrix with dimension ``(..., M)`` or ``(..., M, K)``.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.solve`
    r   )lapack)batched_gesvget_batched_gesv_limit      NzEa must have (..., M, M) shape and b must have (..., M) or (..., M, K)TFcopyorderFr   Cdtype)cupyxr	   cupy.cublasr
   r   ndimshaper   _assert_cupy_array_assert_stacked_2d_assert_stacked_square
ValueErrorlinalg_common_typesizecupyemptyastypegesv
empty_likerangenumpyprodunravel_index)abr	   r
   r   r   	out_dtypexr   iindexbis               f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupy/linalg/_solve.pysolver3      sK   0 @@@@@@@@vzzagbk%;%;%=%=== |Aq!!! 
Q"""	Q	 ### 
16		QVqvz11GCRCLAGKQVaZK000  	 /155E9v{{z!'9---v{{HHUSH11HHUSH11Aqxx	x... 	
T--A+++AGCRCLE5:e$$%%  #Au--uX__US_99AeHb!!!%H    c                    |kt          t          | j                            }|D ]2}|                    |           |                    | j        |           3|                     |          } | j        | j        |j        z
   d         }t          j        |          }| 	                    d|          } |
                                }t          | |          }|	                    |          S )a  Solves tensor equations denoted by ``ax = b``.

    Suppose that ``b`` is equivalent to ``cupy.tensordot(a, x)``.
    This function computes tensor ``x`` from ``a`` and ``b``.

    Args:
        a (cupy.ndarray): The tensor with ``len(shape) >= 1``
        b (cupy.ndarray): The tensor with ``len(shape) >= 1``
        axes (tuple of ints): Axes in ``a`` to reorder to the right
            before inversion.

    Returns:
        cupy.ndarray:
            The tensor with shape ``Q`` such that ``b.shape + Q == a.shape``.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.tensorsolve`
    Nr   )listr'   r   removeinsert	transposer   r   r)   reshaperavelr3   )r+   r,   axesallaxeskoldshaper)   results           r2   tensorsolverA   T   s    2 uQV}}%% 	& 	&ANN1NN161%%%%KK  w!&)**+H=""D			"dA			A1a[[F>>(###r4   c                     | j         j                                        }t          j        |           } t          j        t          j        |                     |                    d          S )Nr   axis)r   charlowerr"   ascontiguousarraysumsquareview)r.   
real_dtypes     r2   _nrm2_last_axisrL   }   sR    ##%%Jq!!A8DKz 2 233"====r4   warnc                    |dk    rt          j        dt                     d}t          j        | |           t          j        |            |j        dk    r,t          j        d	                    |j                            | j
        dd         \  }}|j
        d         }||k    rt          j        d	          t          j                            | d
          \  }}}|0t          j        |j                  j        t#          ||          z  }n*|dk    s|dk    rt          j        |j                  j        }d|z  }	t          j        |j        t          j                  }
|j        dk    rE||                                z  }||k    }d|	|<   |
|                    t          j                  z  }
t          j        |j        |                                          |	z  j        }t          j        |j                                        |          }||k    s|
|k    rt          j        d|j                  }n>||                     |          z
  }t          j        t7          |j                            }|||
|fS )as  Return the least-squares solution to a linear matrix equation.

    Solves the equation `a x = b` by computing a vector `x` that
    minimizes the Euclidean 2-norm `|| b - a x ||^2`.  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.

    Args:
        a (cupy.ndarray): "Coefficient" matrix with dimension ``(M, N)``
        b (cupy.ndarray): "Dependent variable" values with dimension ``(M,)``
            or ``(M, K)``
        rcond (float): Cutoff parameter for small singular values.
            For stability it computes the largest singular value denoted by
            ``s``, and sets all singular values smaller than ``s`` to zero.

    Returns:
        tuple:
            A tuple of ``(x, residuals, rank, s)``. Note ``x`` is the
            least-squares solution with shape ``(N,)`` or ``(N, K)`` depending
            if ``b`` was two-dimensional. The sums of ``residuals`` is the
            squared Euclidean 2-norm for each column in b - a*x. The
            ``residuals`` is an empty array if the rank of a is < N or M <= N,
            but  iff b is 1-dimensional, this is a (1,) shape array, Otherwise
            the shape is (K,). The ``rank`` of matrix ``a`` is an integer. The
            singular values of ``a`` are ``s``.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.lstsq`
    rM   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   zA{}-dimensional array given. Array must be at most two-dimensionalr   Nr   zIncompatible dimensionsFfull_matricesr   r   )r   )warningsrM   FutureWarningr   r   
_assert_2dr   r   LinAlgErrorformatr   r"   svdr(   finfor   epsmaxarrayr!   int32rH   dotTconjr#   
atleast_1drL   )r+   r,   rcondmnm2usvhs1rankcutoff	sing_valszr.   residses                    r2   lstsqrn      s;   N * 	 	 	 	Q"""	Qvzz  "99?I I 	I7233<DAq	
BBww !:;;;{q66HAq"}AG$$(3q!994	!uzzAG$$( 
QB:afek**DvzzK	9	EK000 
!#qvvxx	 	 2	%(Aa  AAvvD000aL!5!566fdAr4   c                    t          j        |            t          j        |            t          j        |            | j        dk    rt          |           S t          j        |           \  }}| j        dk    rt          j	        | j
        |          S | j        rdnd}|                     |d|          } t          j        | j
        d         ||          }|dk    r!t          j                            | |           n*t          j                            | j        |j                   |                    |d	          S )
a  Computes the inverse of a matrix.

    This function computes matrix ``a_inv`` from n-dimensional regular matrix
    ``a`` such that ``dot(a, a_inv) == eye(n)``.

    Args:
        a (cupy.ndarray): The regular matrix

    Returns:
        cupy.ndarray: The inverse of a matrix.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.inv`
       r   r   r   Tr   )r   r   Fr   )r   r   r   r   r   _batched_invr    r!   r"   r#   r   _f_contiguousr$   eyer   r	   r%   r]   )r+   r   r-   r   r,   s        r2   invrt      s   * 
Q	Q	 ###v{{A/22E9v{{z!'9---?+CCE	T//A5666A||!Q!#qs###88IE8***r4   c                 H   t          j        |           \  }}| j        dk    rt          j        | j        |          S |t          j        k    r-t          j        j        j	        }t          j        j        j
        }n|t          j        k    r-t          j        j        j        }t          j        j        j        }n|t          j        k    r-t          j        j        j        }t          j        j        j        }nf|t          j        k    r-t          j        j        j        }t          j        j        j        }n)d                    | j                  }t-          |          d| j        v rt          j        | |          S | j        }|                     |d                              d|d         |d                   } t5          j                    }| j        d         }| j        d         }	|	}
|	|
z  | j        z  }| j        j        }|||z  z   }t          j        |||t          j                   }t          j        ||	ft          j!                  }t          j        |ft          j!                  } |||	|j        j        |
|j        j        |j        j        |           t          j"        j         #                    ||           t          j        |           }|
}|	|z  |j        z  }|j        j        }|||z  z   }t          j        |||t          j                   } |||	|j        j        |
|j        j        |j        j        ||j        j        |	  	         t          j"        j         #                    ||           |                    |                              |d	
          S )Nr   zDdtype must be float32, float64, complex64 or complex128 (actual: {})r   r   )r   r   r   r   Fr   )$r   r    r!   r"   r#   r   float32cudacublassgetrfBatchedsgetriBatchedfloat64dgetrfBatcheddgetriBatched	complex64cgetrfBatchedcgetriBatched
complex128zgetrfBatchedzgetriBatchedrU   r   r   r&   r$   r:   r   get_cublas_handleitemsizedataptrarangeuintpr[   r   3_check_cublas_info_array_if_synchronization_allowed)r+   r   r-   getrfgetrimsga_shapehandle
batch_sizerb   ldastepstartstopa_arraypivot_array
info_arraycldcc_arrays                       r2   rq   rq   	  s'   /22E9v{{z!'9---	 .	 .	$,			 .	 .	$.	 	 	 .	 .	$/	!	!	 .	 .%vag 	ooAG||q	2222gG 	
c""**2wr{GBKHHA%''FJ	
A
Cs7QZDFJE4*$$Dk%t4:>>>G*j!_DJ???KZM<<<J	E&!W\%sK,<,@
/
z+ + +KIIz   	A
Cs7QZDFJE4*$$Dk%t4:>>>G	E&!W\%sK,<,@
,
C!4jB B BKIIz   99W$$YU$;;;r4   V瞯<c                 l   t          j        |            | j        dk    rdt          j        |           \  }}| j        dd         \  }}|dk    s|dk    r| j        }t          j        | j        dd         ||fz   |          S t          j	        | 
                                d          \  }}}|t          j        |d          z  }	||	d	         k    }
t          j        ||
           d||
<   t          j        |                    dd          |d	         |                    dd          z            S )ak  Compute the Moore-Penrose pseudoinverse of a matrix.

    It computes a pseudoinverse of a matrix ``a``, which is a generalization
    of the inverse matrix with Singular Value Decomposition (SVD).
    Note that it automatically removes small singular values for stability.

    Args:
        a (cupy.ndarray): The matrix with dimension ``(..., M, N)``
        rcond (float or cupy.ndarray): Cutoff parameter for small singular
            values. For stability it computes the largest singular value
            denoted by ``s``, and sets all singular values smaller than
            ``rcond * s`` to zero. Broadcasts against the stack of matrices.

    Returns:
        cupy.ndarray: The pseudoinverse of ``a`` with dimension
        ``(..., N, M)``.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.pinv`
    r   r   Nr   FrO   r   rC   ).N)out)r   r   r!   r    r   r   r"   r#   r   rV   r^   amax
reciprocalmatmulswapaxes)r+   r`   _r-   ra   rb   rd   re   vtri   leqs              r2   pinvr   G  s)   6 
Qv{{/229wrss|166Q!VVIz!'#2#,!Q/yAAAA!!&&((%@@@HAq" TYqr****F
vi 
 COA1AcF;r{{2r**AiL1::b";M;M,MNNNr4   r   c                 "   t          j        |            |dk    rt          d          | j        }||d         |d|         z   }t	          j        ||d                   }|                     |d          } t          |           } |j        | S )a  Computes the inverse of a tensor.

    This function computes tensor ``a_inv`` from tensor ``a`` such that
    ``tensordot(a_inv, a, ind) == I``, where ``I`` denotes the identity tensor.

    Args:
        a (cupy.ndarray):
            The tensor such that
            ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
        ind (int):
            The positive number used in ``axes`` option of ``tensordot``.

    Returns:
        cupy.ndarray:
            The inverse of a tensor whose shape is equivalent to
            ``a.shape[ind:] + a.shape[:ind]``.

    .. warning::
        This function calls one or more cuSOLVER routine(s) which may yield
        invalid results if input conditions are not met.
        To detect these invalid results, you can set the `linalg`
        configuration to a value that is not `ignore` in
        :func:`cupyx.errstate` or :func:`cupyx.seterr`.

    .. seealso:: :func:`numpy.linalg.tensorinv`
    r   zInvalid ind argumentNr   )r   r   r   r   r   r)   r:   rt   )r+   indr?   invshaper)   a_invs         r2   	tensorinvr   u  s    6 
Q
axx/000wH~#.H=#$$((D			$AFFE5=(##r4   )N)rM   )r   )r   )rQ   r(   r   r"   
cupy._corer   	cupy.cudar   cupy.linalgr   r   r   r3   rA   rL   rn   rt   rq   r   r    r4   r2   <module>r      s*                        & & & & & &       C C CL&$ &$ &$ &$R> > >X X X Xv(+ (+ (+V:< :< :<|+O +O +O +O\$$ $$ $$ $$ $$ $$r4   