
    2VhR                     0   d dl mZ d dlmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
  G d de      Z ed	d
g      d        Zd Z G d de      Z eddg      d        Zd Z G d de      Z eddg      d        Zd Z G d de      Z eddg      d        Zd Z G d d e      Z ed!d"g      d#        Zd$ Z G d% d&e      Z ed'd(g      d)        Zd* Z G d+ d,e      Z ed-d.g      dQd0       Z G d1 d2e      Z ed3d4g      dRd5       Z  G d6 d7e      Z! ed8d9g      d:        Z"d; Z# G d< d=e      Z$ ed>d?g      dSd@       Z%dSdAZ& G dB dCe      Z' edDdEg      dTdF       Z(dTdGZ) G dH dIe      Z* edJdKg      dUdL       Z+dM Z,dN Z-dO Z.dP Z/y/)V    )backend)keras_export)KerasTensor)any_symbolic_tensors)	Operation)reduce_shapec                   *     e Zd Z fdZd Zd Z xZS )Choleskyc                 "    t         |           y Nsuper__init__self	__class__s    D/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/ops/linalg.pyr   zCholesky.__init__
           c                     t        |      S r   )	_choleskyr   xs     r   callzCholesky.call   s    |r   c                 n    t        |       t        |       t        |j                  |j                        S r   
_assert_2d_assert_squarer   shapedtyper   s     r   compute_output_speczCholesky.compute_output_spec   &    1q177AGG,,r   __name__
__module____qualname__r   r   r!   __classcell__r   s   @r   r
   r
   	   s    -r   r
   zkeras.ops.choleskyzkeras.ops.linalg.choleskyc                 b    t        | f      rt               j                  |       S t        |       S )a   Computes the Cholesky decomposition of a positive semi-definite matrix.

    Args:
        x: Input tensor of shape `(..., M, M)`.

    Returns:
        A tensor of shape `(..., M, M)` representing the lower triangular
        Cholesky factor of `x`.

    )r   r
   symbolic_callr   r   s    r   choleskyr,      s+     QD!z''**Q<r   c                     t        j                  |       } t        |        t        |        	 t         j                  j                  |       S # t        $ r}t        d|       d }~ww xY w)NzCholesky decomposition failed: )r   convert_to_tensorr   r   linalgr,   	Exception
ValueErrorr   es     r   r   r   '   sa    !!!$AqM1@~~&&q)) @:1#>??@s   A 	A(A##A(c                   *     e Zd Z fdZd Zd Z xZS )Detc                 "    t         |           y r   r   r   s    r   r   zDet.__init__2   r   r   c                     t        |      S r   )_detr   s     r   r   zDet.call5       Awr   c                 t    t        |       t        |       t        |j                  d d |j                        S Nr   r   s     r   r!   zDet.compute_output_spec8   s,    1q1773B<11r   r#   r(   s   @r   r5   r5   1   s    2r   r5   zkeras.ops.detzkeras.ops.linalg.detc                 b    t        | f      rt               j                  |       S t        |       S )zComputes the determinant of a square tensor.

    Args:
        x: Input tensor of shape `(..., M, M)`.

    Returns:
        A tensor of shape `(...,)` representing the determinant of `x`.

    )r   r5   r*   r8   r+   s    r   detr>   >   *     QD!u""1%%7Nr   c                     t        j                  |       } t        |        t        |        t         j                  j                  |       S r   )r   r.   r   r   r/   r>   r+   s    r   r8   r8   N   6    !!!$AqM1>>a  r   c                   *     e Zd Z fdZd Zd Z xZS )Eigc                 "    t         |           y r   r   r   s    r   r   zEig.__init__V   r   r   c                     t        |      S r   )_eigr   s     r   r   zEig.callY   r9   r   c                     t        |       t        |       t        |j                  d d |j                        t        |j                  |j                        fS Nr   r   r   r   r    r   s     r   r!   zEig.compute_output_spec\   E    q1agg.)
 	
r   r#   r(   s   @r   rC   rC   U   s    
r   rC   zkeras.ops.eigzkeras.ops.linalg.eigc                 b    t        | f      rt               j                  |       S t        |       S )a$  Computes the eigenvalues and eigenvectors of a square matrix.

    Args:
        x: Input tensor of shape `(..., M, M)`.

    Returns:
        A tuple of two tensors: a tensor of shape `(..., M)` containing
        eigenvalues and a tensor of shape `(..., M, M)` containing eigenvectors.
    )r   rC   r*   rF   r+   s    r   eigrM   e   r?   r   c                     t        j                  |       } t        |        t        |        t         j                  j                  |       S r   )r   r.   r   r   r/   rM   r+   s    r   rF   rF   u   s6    !!!$A1qM>>a  r   c                   *     e Zd Z fdZd Zd Z xZS )Eighc                 "    t         |           y r   r   r   s    r   r   zEigh.__init__}   r   r   c                     t        |      S r   )_eighr   s     r   r   z	Eigh.call   s    Qxr   c                     t        |       t        |       t        |j                  d d |j                        t        |j                  |j                        fS rH   rJ   r   s     r   r!   zEigh.compute_output_spec   rK   r   r#   r(   s   @r   rP   rP   |   s    
r   rP   zkeras.ops.eighzkeras.ops.linalg.eighc                 b    t        | f      rt               j                  |       S t        |       S )a)  Computes the eigenvalues and eigenvectors of a complex Hermitian.

    Args:
        x: Input tensor of shape `(..., M, M)`.

    Returns:
        A tuple of two tensors: a tensor of shape `(..., M)` containing
        eigenvalues and a tensor of shape `(..., M, M)` containing eigenvectors.

    )r   rP   r*   rS   r+   s    r   eighrV      s*     QD!v##A&&8Or   c                     t        j                  |       } t        |        t        |        t         j                  j                  |       S r   )r   r.   r   r   r/   rV   r+   s    r   rS   rS      s6    !!!$A1qM>>q!!r   c                   *     e Zd Z fdZd Zd Z xZS )Invc                 "    t         |           y r   r   r   s    r   r   zInv.__init__   r   r   c                     t        |      S r   )_invr   s     r   r   zInv.call   r9   r   c                 n    t        |       t        |       t        |j                  |j                        S r   r   r   s     r   r!   zInv.compute_output_spec   r"   r   r#   r(   s   @r   rY   rY      s    -r   rY   zkeras.ops.invzkeras.ops.linalg.invc                 b    t        | f      rt               j                  |       S t        |       S )zComputes the inverse of a square tensor.

    Args:
        x: Input tensor of shape `(..., M, M)`.

    Returns:
        A tensor of shape `(..., M, M)` representing the inverse of `x`.

    )r   rY   r*   r\   r+   s    r   invr_      r?   r   c                     t        j                  |       } t        |        t        |        t         j                  j                  |       S r   )r   r.   r   r   r/   r_   r+   s    r   r\   r\      rA   r   c                   *     e Zd Z fdZd Zd Z xZS )LuFactorc                 "    t         |           y r   r   r   s    r   r   zLuFactor.__init__   r   r   c                     t        |      S r   )
_lu_factorr   s     r   r   zLuFactor.call   s    !}r   c                     t        |       |j                  d d }|j                  dd  \  }}t        ||      }t        |||fz   |j                        t        ||fz   |j                        fS r;   )r   r   minr   r    )r   r   batch_shapemnks         r   r!   zLuFactor.compute_output_spec   sl    1ggcrlwwrs|11Iq!f,agg6qd*AGG4
 	
r   r#   r(   s   @r   rb   rb      s    
r   rb   zkeras.ops.lu_factorzkeras.ops.linalg.lu_factorc                 b    t        | f      rt               j                  |       S t        |       S )a@  Computes the lower-upper decomposition of a square matrix.

    Args:
        x: A tensor of shape `(..., M, M)`.

    Returns:
        A tuple of two tensors: a tensor of shape `(..., M, M)` containing the
        lower and upper triangular matrices and a tensor of shape `(..., M)`
        containing the pivots.

    )r   rb   r*   re   r+   s    r   	lu_factorrm      s+     QD!z''**a=r   c                    t        j                  |       } t        |        t        j                          dk(  r	 t        |        t         j
                  j                  |       S # t        $ r}t	        d| d      d }~ww xY w)N
tensorflowzLU decomposition failed: zG. LU decomposition is only supported for square matrices in Tensorflow.)r   r.   r   r   r1   r/   rm   r2   s     r   re   re      s|    !!!$AqML(	1 >>##A&&  	+A3 /? ? 	s   A# #	B ,A;;B c                   ,     e Zd Zd fd	Zd Zd Z xZS )Normc                     t         |           t        |t              r|dvrt	        d|       t        |t
              r|g}|| _        || _        || _        y )N)fronuczXInvalid `ord` argument. Expected one of {'fro', 'nuc'} when using string. Received: ord=)	r   r   
isinstancestrr1   intordaxiskeepdims)r   rx   ry   rz   r   s       r   r   zNorm.__init__   sd    c3.( %%(E+ 
 dC 6D	 r   c           
      x   t        j                  |j                        }d|v s|dk(  rt        j                         }| j                  (t        t        t        |j                                    }n| j                  }t        |      }|dk(  r2t        | j                  t              rt        d| j                         |dk(  rA| j                  d ddt        d      t        d	      dd
ddf	vrt        d| j                         t        t        |j                  | j                  | j                         |      S )Nrw   bool   z6Invalid `ord` argument for vector norm. Received: ord=   rs   rt   infz-infrI   r<   z6Invalid `ord` argument for matrix norm. Received: ord=)ry   rz   r    )r   standardize_dtyper    floatxry   tuplerangelenr   ru   rx   rv   r1   floatr   r   rz   )r   r   output_dtypery   num_axess        r   r!   zNorm.compute_output_spec
  s    009L LF$:">>+L99s177|,-D99Dt9q=Z#6!!%
,  ]txx%L&M
0
 
 
 !!%
,  tyy4==I
 	
r   c                     t        j                  |      }t         j                  j                  || j                  | j
                  | j                        S )Nrx   ry   rz   )r   r.   r/   normrx   ry   rz   r   s     r   r   z	Norm.call,  sC    %%a(~~""488$))dmm # 
 	
r   NNFr$   r%   r&   r   r!   r   r'   r(   s   @r   rq   rq      s    ! 
D
r   rq   zkeras.ops.normzkeras.ops.linalg.normNc                     t        | f      rt        |||      j                  |       S t        j                  |       } t        j
                  j                  | |||      S )aM  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.

    Args:
        x: Input tensor.
        ord: Order of the norm (see table under Notes). The default is `None`.
        axis: 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.
        keepdims: If this is set to `True`, the axes which are reduced are left
            in the result as dimensions with size one.

    Note:
        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:
        - For matrices:
            - `ord=None`: Frobenius norm
            - `ord="fro"`: Frobenius norm
            - `ord="nuc"`: nuclear norm
            - `ord=np.inf`: `max(sum(abs(x), axis=1))`
            - `ord=-np.inf`: `min(sum(abs(x), axis=1))`
            - `ord=0`: not supported
            - `ord=1`: `max(sum(abs(x), axis=0))`
            - `ord=-1`: `min(sum(abs(x), axis=0))`
            - `ord=2`: 2-norm (largest sing. value)
            - `ord=-2`: smallest singular value
            - other: not supported
        - For vectors:
            - `ord=None`: 2-norm
            - `ord="fro"`: not supported
            - `ord="nuc"`: not supported
            - `ord=np.inf`: `max(abs(x))`
            - `ord=-np.inf`: `min(abs(x))`
            - `ord=0`: `sum(x != 0)`
            - `ord=1`: as below
            - `ord=-1`: as below
            - `ord=2`: as below
            - `ord=-2`: as below
            - other: `sum(abs(x)**ord)**(1./ord)`

    Returns:
        Norm of the matrix or vector(s).

    Example:

    >>> x = keras.ops.reshape(keras.ops.arange(9, dtype="float32") - 4, (3, 3))
    >>> keras.ops.linalg.norm(x)
    7.7459664
    r   )r   rq   r*   r   r.   r/   r   )r   rx   ry   rz   s       r   r   r   3  sW    p QD!$:HHKK!!!$A>>qcxHHr   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Qrc                 T    t         |           |dvrt        d|       || _        y )N>   reducedcompletez]`mode` argument value not supported. Expected one of {'reduced', 'complete'}. Received: mode=)r   r   r1   mode)r   r   r   s     r   r   zQr.__init__r  s<    ..""&) 
 	r   c                    t        |j                        dk  rt        d|j                         |j                  d   }|j                  d   }||t        d|j                         t        ||      }t	        |j                  d d       }| j
                  dk(  r8t        |||fz   |j                        t        |||fz   |j                        fS t        |||fz   |j                        t        |||fz   |j                        fS )Nr~   z5Input should have rank >= 2. Received: input.shape = r<   rI   zOInput should have its last 2 dimensions fully-defined. Received: input.shape = r   )r   r    )r   r   r1   rg   r   r   r   r    )r   r   ri   rj   rk   bases         r   r!   zQr.compute_output_spec|  s   qww<!!!"	+  GGBKGGBK9	!!"	+ 
 1IQWWSb\"99	!$!Q-qww?$!Q-qww?  daVm177;daVm177;
 	
r   c                     t        j                  |      }t         j                  j                  || j                        S )Nr   )r   r.   r/   qrr   r   s     r   r   zQr.call  s0    %%a(~~   33r   r   r   r(   s   @r   r   r   q  s    
64r   r   zkeras.ops.qrzkeras.ops.linalg.qrc                     t        | f      rt        |      j                  |       S t        j                  |       } t        j
                  j                  | |      S )a4  Computes the QR decomposition of a tensor.

    Args:
        x: Input tensor of shape `(..., M, N)`.
        mode: A string specifying the mode of the QR decomposition.
            - 'reduced': Returns the reduced QR decomposition. (default)
            - 'complete': Returns the complete QR decomposition.

    Returns:
        A tuple containing two tensors. The first tensor of shape `(..., M, K)`
        is the orthogonal matrix `q` and the second tensor of shape
        `(..., K, N)` is the upper triangular matrix `r`, where `K = min(M, N)`.

    Example:

    >>> x = keras.ops.convert_to_tensor([[1., 2.], [3., 4.], [5., 6.]])
    >>> q, r = qr(x)
    >>> print(q)
    array([[-0.16903079  0.897085]
           [-0.5070925   0.2760267 ]
           [-0.8451542  -0.34503305]], shape=(3, 2), dtype=float32)
    r   )r   r   r*   r   r.   r/   r   )r   r   s     r   r   r     sM    0 QD!t}**1--!!!$A>>QT**r   c                   *     e Zd Z fdZd Zd Z xZS )Solvec                 "    t         |           y r   r   r   s    r   r   zSolve.__init__  r   r   c                     t        ||      S r   )_solver   abs      r   r   z
Solve.call  s    a|r   c                     t        |       t        |       t        |       t        ||       t	        |j
                  |j                        S r   r   r   
_assert_1d_assert_a_b_compatr   r   r    r   s      r   r!   zSolve.compute_output_spec  7    1q11a 177AGG,,r   r#   r(   s   @r   r   r     s    -r   r   zkeras.ops.solvezkeras.ops.linalg.solvec                 h    t        | |f      rt               j                  | |      S t        | |      S a  Solves a linear system of equations given by `a x = b`.

    Args:
        a: A tensor of shape `(..., M, M)` representing the coefficients matrix.
        b: A tensor of shape `(..., M)` or `(..., M, N)` representing the
        right-hand side or "dependent variable" matrix.

    Returns:
        A tensor of shape `(..., M)` or `(..., M, N)` representing the solution
        of the linear system. Returned shape is identical to `b`.

    )r   r   r*   r   r   r   s     r   solver     s1     QF#w$$Q**!Q<r   c                     t        j                  |       } t        j                  |      }t        |        t        |        t	        |       t        | |       t         j                  j                  | |      S r   )r   r.   r   r   r   r   r/   r   r   s     r   r   r     sY    !!!$A!!!$AqM1qMq!>>1%%r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )SolveTriangularc                 0    t         |           || _        y r   )r   r   lower)r   r   r   s     r   r   zSolveTriangular.__init__      
r   c                 0    t        ||| j                        S r   )_solve_triangularr   r   s      r   r   zSolveTriangular.call  s     Atzz22r   c                     t        |       t        |       t        |       t        ||       t	        |j
                  |j                        S r   r   r   s      r   r!   z#SolveTriangular.compute_output_spec  r   r   Fr#   r(   s   @r   r   r     s    3-r   r   zkeras.ops.solve_triangularz!keras.ops.linalg.solve_triangularc                 l    t        | |f      rt        |      j                  | |      S t        | ||      S r   )r   r   r*   r   r   r   r   s      r   solve_triangularr     s7      QF#u%33Aq99Q5))r   c                     t        j                  |       } t        j                  |      }t        |        t        |        t	        |       t        | |       t         j                  j                  | ||      S r   )r   r.   r   r   r   r   r/   r   r   s      r   r   r     s[    !!!$A!!!$AqM1qMq!>>**1a77r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )SVDc                 >    t         |           || _        || _        y r   )r   r   full_matrices
compute_uv)r   r   r   r   s      r   r   zSVD.__init__  s    *$r   c                 D    t        || j                  | j                        S r   )_svdr   r   r   s     r   r   zSVD.call  s    At))4??;;r   c                    t        |       |j                  dd  \  }}|j                  d d }|t        ||      fz   }| j                  r|||fz   }|||fz   }n"||t        ||      fz   }|t        ||      |fz   }| j                  rAt        ||j                        t        ||j                        t        ||j                        fS t        ||j                        S r;   )r   r   rg   r   r   r   r    )r   r   rowscolumnsbatchess_shapeu_shapev_shapes           r   r!   zSVD.compute_output_spec  s    1g''#2,Sw/11t,G' 22Gs4'9 ::GT7!3W ==G??GQWW-GQWW-GQWW- 
 7AGG,,r   TTr#   r(   s   @r   r   r     s    %
<-r   r   zkeras.ops.svdzkeras.ops.linalg.svdc                 j    t        | f      rt        ||      j                  |       S t        | ||      S )a  Computes the singular value decomposition of a matrix.

    Args:
        x: Input tensor of shape `(..., M, N)`.

    Returns:
        A tuple of three tensors: a tensor of shape `(..., M, M)` containing the
        left singular vectors, a tensor of shape `(..., M, N)` containing the
        singular values and a tensor of shape `(..., N, N)` containing the
        right singular vectors.

    )r   r   r*   r   r   r   r   s      r   svdr   3  s5     QD!=*-;;A>>=*--r   c                     t        j                  |       } t        |        t         j                  j	                  | ||      S r   )r   r.   r   r/   r   r   s      r   r   r   F  s2    !!!$AqM>>a
;;r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )Lstsqc                 0    t         |           || _        y r   )r   r   rcond)r   r   r   s     r   r   zLstsq.__init__M  r   r   c                 Z    t         j                  j                  ||| j                        S )Nr   )r   r/   lstsqr   r   s      r   r   z
Lstsq.callQ  s"    ~~##Aq

#;;r   c                    t        |j                        dk7  rt        d|j                         t        |j                        dvrt        d|j                         |j                  \  }}|j                  d   |k7  r%t        d|j                   d|j                         t        |j                        dk(  r*|j                  d   }t        ||f|j                  	      }|S t        |f|j                  	      }|S )
Nr~   z-Expected a to have rank 2. Received: a.shape=)r}   r~   z2Expected b to have rank 1 or 2. Received: b.shape=r   zAExpected b.shape[0] to be equal to a.shape[0]. Received: a.shape=
, b.shape=r}   r   )r   r   r1   r   r    )r   r   r   ri   rj   rk   r   s          r   r!   zLstsq.compute_output_specT  s    qww<1?yI  qww<v%DQWWIN  ww1771:?77):aggY8 
 qww<1
AQF!''2A  QD0Ar   r   r#   r(   s   @r   r   r   L  s    <r   r   zkeras.ops.lstsqzkeras.ops.linalg.lstsqc                     t        | |f      rt        |      j                  | |      S t        j                  j                  | ||      S )az  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
    L2 norm of `b - a * x`.

    If there are multiple minimizing solutions,
    the one with the smallest L2 norm  is returned.

    Args:
        a: "Coefficient" matrix of shape `(M, N)`.
        b: Ordinate or "dependent variable" values,
            of shape `(M,)` or `(M, K)`.
            If `b` is two-dimensional, the least-squares solution
            is calculated for each of the K columns of `b`.
        rcond: 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`.

    Returns:
        Tensor with shape `(N,)` or `(N, K)` containing
        the least-squares solutions.

    **NOTE:** The output differs from `numpy.linalg.lstsq`.
    NumPy returns a tuple with four elements, the first of which
    being the least-squares solutions and the others
    being essentially never used.
    Keras only returns the first value. This is done both
    to ensure consistency across backends (which cannot be achieved
    for the other values) and to simplify the API.
    r   )r   r   r*   r   r/   r   )r   r   r   s      r   r   r   l  sE    N QF#5!//155>>1E22r   c                  N    | D ]   }|j                   dk  st        d| d       y )Nr}   z8Expected input to have rank >= 1. Received scalar input .)ndimr1   arraysr   s     r   r   r     s5     66A:J1#QO r   c                  b    | D ]*  }|j                   dk  st        d|j                   d       y )Nr~   z<Expected input to have rank >= 2. Received input with shape r   )r   r1   r   r   s     r   r   r     s>     66A:--.WWIQ8 r   c                  p    | D ]1  }|j                   dd  \  }}||k7  st        d|j                           y )Nr<   z?Expected a square matrix. Received non-square input with shape )r   r1   )r   r   ri   rj   s       r   r   r     sL     wwrs|16889yB r   c                    | j                   |j                   k(  rE| j                  d   |j                  d   k7  r%t        d| j                   d|j                         y | j                   |j                   dz
  k(  rE| j                  d   |j                  d   k7  r%t        d| j                   d|j                         y y )Nr<   zbIncompatible shapes between `a` and `b`. Expected `a.shape[-2] == b.shape[-2]`. Received: a.shape=r   r}   rI   zbIncompatible shapes between `a` and `b`. Expected `a.shape[-1] == b.shape[-1]`. Received: a.shape=)r   r   r1   r   s     r   r   r     s    vv772;!''"+%%%&WWIZyB  & 
166A:	772;!''"+%%%&WWIZyB  & 
r   r   r   r   r   r   )0	keras.srcr   keras.src.api_exportr   keras.src.backendr   r   keras.src.ops.operationr   keras.src.ops.operation_utilsr   r
   r,   r   r5   r>   r8   rC   rM   rF   rP   rV   rS   rY   r_   r\   rb   rm   re   rq   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   <module>r      so    - ) 2 - 6
-y 
- #%@AB C @
2) 
2  678 9!
) 
   678 9!
9 
  !89: ; "
-) 
-  678 9!
y 
$ $&BCD E"'6
9 6
r !89::I ;:Iz(4 (4V ~456+ 7+:-I -  ":;< =$&-i -  !#FG**$8-) -<  678. 9.$<I @  ":;<(3 =(3Vr   