
    `iJ                        d dl Z d dlZd dlZd dlmZ d dlmZ  ej        d          d.d            Z ej        d          d/d            Z ej        d          d/d	            Z	 ej        d
          d0d            Z
 ej        d          d             Z ej        d          d0d            Zd1dZ ej        d          efd            Z ej        ddddd          Z ej        d          d             Z ej        d          d             Z ej        d          d             Z ej        d          d              Z ej        d!          d1d"            Z ej        d#          d$             Z ej        d%          d0d&            Z ej        d'          d(             Z ej        d)          d*             Z ej        d+          d2d-            ZdS )3    N)_core)_uarraytric                     t          j        dt                     || }nt          |t                    r| |}}t          j        | |||t          n|          S )a   Construct (``N``, ``M``) matrix filled with ones at and below the
    ``k``-th diagonal. The matrix has ``A[i,j] == 1`` for ``i <= j + k``.

    Args:
        N (int): The size of the first dimension of the matrix.
        M (int, optional): The size of the second dimension of the matrix. If
            ``M`` is None, ``M = N`` is assumed.
        k (int, optional):  Number of subdiagonal below which matrix is filled
            with ones. ``k = 0`` is the main diagonal, ``k < 0`` subdiagonal
            and ``k > 0`` superdiagonal.
        dtype (dtype, optional): Data type of the matrix.

    Returns:
        cupy.ndarray: Tri matrix.

    .. seealso:: :func:`scipy.linalg.tri`
    !'tri'/'tril/'triu' are deprecated)warningswarnDeprecationWarning
isinstancestrcupyr   bool)NMkdtypes       x/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/linalg/_special_matrices.pyr   r   	   s_    & M57IJJJy	As		 a5 8Aq!U]TT>>>    trilc                     t          j        dt                     t          | j        d         | j        d         || j        j                  }|| z  }|S )a  Make a copy of a matrix with elements above the ``k``-th diagonal
    zeroed.

    Args:
        m (cupy.ndarray): Matrix whose elements to return
        k (int, optional): Diagonal above which to zero elements.
            ``k == 0`` is the main diagonal, ``k < 0`` subdiagonal and
            ``k > 0`` superdiagonal.

    Returns:
        (cupy.ndarray): Return is the same shape and type as ``m``.

    .. seealso:: :func:`scipy.linalg.tril`
    r   r      )r   r   )r   r	   r
   r   shaper   charmr   ts      r   r   r   )   sN      M57IJJJ 	AGAJ
aqw|<<<AFAHr   triuc                     t          j        dt                     t          | j        d         | j        d         |dz
  | j        j                  }t          j        d||           || z  }|S )a  Make a copy of a matrix with elements below the ``k``-th diagonal
    zeroed.

    Args:
        m (cupy.ndarray): Matrix whose elements to return
        k (int, optional): Diagonal above which to zero elements.
            ``k == 0`` is the main diagonal, ``k < 0`` subdiagonal and
            ``k > 0`` superdiagonal.

    Returns:
        (cupy.ndarray): Return matrix with zeroed elements below the kth
        diagonal and has same shape and type as ``m``.

    .. seealso:: :func:`scipy.linalg.triu`
    r   r   r   out)	r   r	   r
   r   r   r   r   r   subtractr   s      r   r   r   A   sf    " M57IJJJ 	AGAJ
AE17<88AM!QAFAHr   toeplitzc                     |                                  } ||                                 n|                                 }t          | ddd         |dd                   S )aL  Construct a Toeplitz matrix.

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

    Args:
        c (cupy.ndarray): First column of the matrix. Whatever the actual shape
            of ``c``, it will be converted to a 1-D array.
        r (cupy.ndarray, optional): First row of the matrix. If None,
            ``r = conjugate(c)`` is assumed; in this case, if ``c[0]`` is real,
            the result is a Hermitian matrix. r[0] is ignored; the first row of
            the returned matrix is ``[c[0], r[1:]]``. Whatever the actual shape
            of ``r``, it will be converted to a 1-D array.

    Returns:
        cupy.ndarray: The Toeplitz matrix. Dtype is the same as
        ``(c[0] + r[0]).dtype``.

    .. seealso:: :func:`cupyx.scipy.linalg.circulant`
    .. seealso:: :func:`cupyx.scipy.linalg.hankel`
    .. seealso:: :func:`cupyx.scipy.linalg.solve_toeplitz`
    .. seealso:: :func:`cupyx.scipy.linalg.fiedler`
    .. seealso:: :func:`scipy.linalg.toeplitz`
    Nr   )ravel	conjugate_create_toeplitz_matrixcrs     r   r"   r"   [   sP    6 	
		A		A"1TTrT7AabbE222r   	circulantc                 n    |                                  } t          | ddd         | ddd                   S )a  Construct a circulant matrix.

    Args:
        c (cupy.ndarray): 1-D array, the first column of the matrix.

    Returns:
        cupy.ndarray: A circulant matrix whose first column is ``c``.

    .. seealso:: :func:`cupyx.scipy.linalg.toeplitz`
    .. seealso:: :func:`cupyx.scipy.linalg.hankel`
    .. seealso:: :func:`cupyx.scipy.linalg.solve_circulant`
    .. seealso:: :func:`cupyx.scipy.linalg.fiedler`
    .. seealso:: :func:`scipy.linalg.circulant`
    Nr$   r   )r%   r'   )r)   s    r   r+   r+   {   s5      	
		A"1TTrT7AeqeH555r   hankelc                     |                                  } |t          j        |           n|                                 }t          | |dd         d          S )a  Construct a Hankel matrix.

    The Hankel matrix has constant anti-diagonals, with ``c`` as its first
    column and ``r`` as its last row. If ``r`` is not given, then
    ``r = zeros_like(c)`` is assumed.

    Args:
        c (cupy.ndarray): First column of the matrix. Whatever the actual shape
            of ``c``, it will be converted to a 1-D array.
        r (cupy.ndarray, optional): Last row of the matrix. If None,
            ``r = zeros_like(c)`` is assumed. ``r[0]`` is ignored; the last row
            of the returned matrix is ``[c[-1], r[1:]]``. Whatever the actual
            shape of ``r``, it will be converted to a 1-D array.

    Returns:
        cupy.ndarray: The Hankel matrix. Dtype is the same as
        ``(c[0] + r[0]).dtype``.

    .. seealso:: :func:`cupyx.scipy.linalg.toeplitz`
    .. seealso:: :func:`cupyx.scipy.linalg.circulant`
    .. seealso:: :func:`scipy.linalg.hankel`
    Nr   T)r%   r   
zeros_liker'   r(   s     r   r-   r-      sK    0 	
		AiQWWYYA"1aeT222r   Fc                    t          j        | |f          }|j        d         }t           j        j                            |r|n|| j        dz
  d          | j        |j        dz   f|r|n| |f                                          S )Nr   r   )r   strides)r   concatenater1   libstride_tricks
as_stridedsizecopy)r)   r*   r-   valsns        r   r'   r'      s    QF##DQA8!,,+DOvqvax $1"a( - * * +/$&&1r   hadamardc                     | dk     rdn#t          |                                           dz
  }d|z  | k    rt          d          t          j        | | f|          }t          ||          S )a  Construct an Hadamard matrix.

    Constructs an n-by-n Hadamard matrix, using Sylvester's construction. ``n``
    must be a power of 2.

    Args:
        n (int): The order of the matrix. ``n`` must be a power of 2.
        dtype (dtype, optional): The data type of the array to be constructed.

    Returns:
        (cupy.ndarray): The Hadamard matrix.

    .. seealso:: :func:`scipy.linalg.hadamard`
    r   r      z*n must be an positive a power of 2 integer)int
bit_length
ValueErrorr   empty_hadamard_kernel)r9   r   lg2Hs       r   r:   r:      sm      1uu!!3q66,,..2CCx1}}EFFF
Aq65!!AAq!!!r   zT inzT outz;out = (__popc(_ind.get()[0] & _ind.get()[1]) & 1) ? -1 : 1;cupyx_scipy_linalg_hadamard)reduce_dimslesliec                    | j         dk    rt          d          |j         dk    rt          d          | j        }||j        dz   k    rt          d          |j        dk    rt          d          t          j        ||ft          j        | |                    }| |d<   t          j        |dd         |           |S )	a  Create a Leslie matrix.

    Given the length n array of fecundity coefficients ``f`` and the length n-1
    array of survival coefficients ``s``, return the associated Leslie matrix.

    Args:
        f (cupy.ndarray): The "fecundity" coefficients.
        s (cupy.ndarray): The "survival" coefficients, has to be 1-D.  The
            length of ``s`` must be one less than the length of ``f``, and it
            must be at least 1.

    Returns:
        cupy.ndarray: The array is zero except for the first row, which is
        ``f``, and the first sub-diagonal, which is ``s``. The data-type of
        the array will be the data-type of ``f[0]+s[0]``.

    .. seealso:: :func:`scipy.linalg.leslie`
    r   z#Incorrect shape for f. f must be 1Dz#Incorrect shape for s. s must be 1Dz-Length of s must be one less than length of fr   z#The length of s must be at least 1.r   N)ndimr?   r6   r   zerosresult_typefill_diagonal)fsr9   as       r   rF   rF      s    ( 	v{{>???v{{>???	AAFQJHIIIv{{>???
Aq6!1!Q!7!7888AAaDqua   Hr   kronc                     t          j        | |          }|                    | j        |j        z             }t          j        t          j        |d          d          S )a  Kronecker product.

    The result is the block matrix::
        a[0,0]*b    a[0,1]*b  ... a[0,-1]*b
        a[1,0]*b    a[1,1]*b  ... a[1,-1]*b
        ...
        a[-1,0]*b   a[-1,1]*b ... a[-1,-1]*b

    Args:
        a (cupy.ndarray): Input array
        b (cupy.ndarray): Input array

    Returns:
        cupy.ndarray: Kronecker product of ``a`` and ``b``.

    .. seealso:: :func:`scipy.linalg.kron`
    r   )axis)r   outerreshaper   r2   )rO   bos      r   rP   rP      sU    & 	
1aA			!'AG#$$AD,QQ777a@@@@r   
block_diagc                  p     st          j        d          S t                     dk    rt          j          f nt          j           t	          d  D                       rJ fdt          t                               D             }t          d                    |                    t          d  D                       }t          d t          | D                       }t          j
        |t          j                    }d	\  }} D ]'}|j        \  }}	|||||z   |||	z   f<   ||z  }||	z  }(|S )
a/  Create a block diagonal matrix from provided arrays.

    Given the inputs ``A``, ``B``, and ``C``, the output will have these
    arrays arranged on the diagonal::

        [A, 0, 0]
        [0, B, 0]
        [0, 0, C]

    Args:
        A, B, C, ... (cupy.ndarray): Input arrays. A 1-D array of length ``n``
            is treated as a 2-D array with shape ``(1,n)``.

    Returns:
        (cupy.ndarray): Array with ``A``, ``B``, ``C``, ... on the diagonal.
        Output has the same dtype as ``A``.

    .. seealso:: :func:`scipy.linalg.block_diag`
    r   r   r   c              3   ,   K   | ]}|j         d k    V  dS )r<   NrI   .0rO   s     r   	<genexpr>zblock_diag.<locals>.<genexpr>*  s(      
%
%116Q;
%
%
%
%
%
%r   c                 6    g | ]}|         j         d k    |S )r<   r[   )r]   r   arrss     r   
<listcomp>zblock_diag.<locals>.<listcomp>+  s)    @@@Qd1gla.?.?q.?.?.?r   zFarguments in the following positions have dimension greater than 2: {}c              3   $   K   | ]}|j         V  d S N)r   r\   s     r   r^   zblock_diag.<locals>.<genexpr>/  s$      ))q17))))))r   c              3   4   K   | ]}t          |          V  d S rc   )sum)r]   xs     r   r^   zblock_diag.<locals>.<genexpr>0  s(      //Q#a&&//////r   rH   r   r   )r   r@   len
atleast_2danyranger?   formattupleziprJ   rK   r   )
r`   badshapesr   r    r*   r)   arrrrccs
   `         r   rW   rW     sh   *  "z&!!! 4yyA~~&(%

%
%
%
%
%%% ;@@@@%D		**@@@ ..4fSkk; ; 	; ))D)))))F//#v,/////E
*U$"2D"9
:
:
:CDAq  B"%Aa"fHaBh	R	RJr   	companionc                 $   | j         }| j        dk    rt          d          |dk     rt          d          | dd          | d         z  }t          j        |dz
  |dz
  f|j                  }||d<   t          j        |dd         d           |S )as  Create a companion matrix.

    Create the companion matrix associated with the polynomial whose
    coefficients are given in ``a``.

    Args:
        a (cupy.ndarray): 1-D array of polynomial coefficients. The length of
            ``a`` must be at least two, and ``a[0]`` must not be zero.

    Returns:
        (cupy.ndarray): The first row of the output is ``-a[1:]/a[0]``, and the
        first sub-diagonal is all ones. The data-type of the array is the
        same as the data-type of ``-a[1:]/a[0]``.

    .. seealso:: :func:`cupyx.scipy.linalg.fiedler_companion`
    .. seealso:: :func:`scipy.linalg.companion`
    r   z`a` must be one-dimensional.r<   z%The length of `a` must be at least 2.Nr   rH   )r6   rI   r?   r   rJ   r   rL   )rO   r9   	first_rowr)   s       r   rt   rt   ;  s    & 	
Av{{78881uu@AAA
 1221I
AE1q5>999AAaDqua   Hr   helmertc                 F   t          j        |           }t          j        | | d          }|                                ddxx         |z  cc<   |t          j        d| dz             z  }d|d<   | |d<   |t          j        |          dddf         z  }|r|n	|dd         S )aL  Create an Helmert matrix of order ``n``.

    This has applications in statistics, compositional or simplicial analysis,
    and in Aitchison geometry.

    Args:
        n (int): The size of the array to create.
        full (bool, optional): If True the (n, n) ndarray will be returned.
            Otherwise, the default, the submatrix that does not include the
            first row will be returned.

    Returns:
        cupy.ndarray: The Helmert matrix. The shape is (n, n) or (n-1, n)
        depending on the ``full`` argument.

    .. seealso:: :func:`scipy.linalg.helmert`
    r$   Nr   r   )r   aranger   diagonalsqrt)r9   fulldrC   s       r   rw   rw   ^  s    & 	AAArAJJLLOOOqOOOQ!		AAaDAaD1aaag	A11!ABB%r   hilbertc                     t          j        dd| z  t           j                  }t          j        ||           t	          |d|          || dz
  d                   S )a!  Create a Hilbert matrix of order ``n``.

    Returns the ``n`` by ``n`` array with entries ``h[i,j] = 1 / (i + j + 1)``.

    Args:
        n (int): The size of the array to create.

    Returns:
        cupy.ndarray: The Hilbert matrix.

    .. seealso:: :func:`scipy.linalg.hilbert`
    r   r<   rH   N)r*   )r   ry   float64
reciprocalr-   )r9   valuess     r   r~   r~   {  sY     [AaCt|444FOFF###&!*qstt----r   dftc                 F   |dvrt          d|d          t          j        | d          }|dt          j        z  | z  z  }t          j        ||          dddf         }|t          j        |           z  }|%||d	k    rd
t          j        |           z  nd
| z  z  }|S )a  Discrete Fourier transform matrix.

    Create the matrix that computes the discrete Fourier transform of a
    sequence. The nth primitive root of unity used to generate the matrix is
    exp(-2*pi*i/n), where i = sqrt(-1).

    Args:
        n (int): Size the matrix to create.
        scale (str, optional): Must be None, 'sqrtn', or 'n'.
            If ``scale`` is 'sqrtn', the matrix is divided by ``sqrt(n)``.
            If ``scale`` is 'n', the matrix is divided by ``n``.
            If ``scale`` is None (default), the matrix is not normalized, and
            the return value is simply the Vandermonde matrix of the roots of
            unity.

    Returns:
        (cupy.ndarray): The DFT matrix.

    Notes:
        When ``scale`` is None, multiplying a vector by the matrix returned by
        ``dft`` is mathematically equivalent to (but much less efficient than)
        the calculation performed by ``scipy.fft.fft``.

    .. seealso:: :func:`scipy.linalg.dft`
    )Nsqrtnr9   z%scale must be None, 'sqrtn', or 'n'; z is not valid.
complex128rH   y              r   Nr   r   )r?   r   ry   piexpmathr{   )r9   scaler*   omegasr   s        r   r   r     s    6 (((j/4uu7 8 8 	8A\***ATWQAXaQ4(F$+a.. A	'!1!1a	!nn!<Hr   fiedlerc                     | j         dk    rt          d          | j        dk    rt          j        d          S | j        dk    rt          j        d          S | dddf         | z
  } t          j        | |           S )a  Returns a symmetric Fiedler matrix

    Given an sequence of numbers ``a``, Fiedler matrices have the structure
    ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative
    entries. A Fiedler matrix has a dominant positive eigenvalue and other
    eigenvalues are negative. Although not valid generally, for certain inputs,
    the inverse and the determinant can be derived explicitly.

    Args:
        a (cupy.ndarray): coefficient array

    Returns:
        cupy.ndarray: the symmetric Fiedler matrix

    .. seealso:: :func:`cupyx.scipy.linalg.circulant`
    .. seealso:: :func:`cupyx.scipy.linalg.toeplitz`
    .. seealso:: :func:`scipy.linalg.fiedler`
    r   zInput `a` must be a 1D array.r   )r   r   Nr   )rI   r?   r6   r   rJ   abs)rO   s    r   r   r     s|    ( 	v{{8999v{{z!}}v{{z&!!!	!!!T'
QA8A1r   fiedler_companionc                    | j         dk    rt          d          | j        dk     rt          j        d| j                  S | j        dk    r| d          | d         z  d         S | | d         z  } | j        dz
  }t          j        ||f| j                  }t          j        |dd	ddd	df         d           t          j        |dd	ddd	df         | dd	d                     t          j        |d	d	ddd	df         d           t          j        |d	d	ddd	df         | dd	d                     | d          |d
<   d|d<   |S )al  Returns a Fiedler companion matrix

    Given a polynomial coefficient array ``a``, this function forms a
    pentadiagonal matrix with a special structure whose eigenvalues coincides
    with the roots of ``a``.

    Args:
        a (cupy.ndarray): 1-D array of polynomial coefficients in descending
            order with a nonzero leading coefficient. For ``N < 2``, an empty
            array is returned.

    Returns:
        cupy.ndarray: Resulting companion matrix

    Notes:
        Similar to ``companion`` the leading coefficient should be nonzero. In
        the case the leading coefficient is not 1, other coefficients are
        rescaled before the array generation. To avoid numerical issues, it is
        best to provide a monic polynomial.

    .. seealso:: :func:`cupyx.scipy.linalg.companion`
    .. seealso:: :func:`scipy.linalg.fiedler_companion`
    r   zInput `a` must be a 1-D array.r<   r   r   )NNrH      Nrg   rY   )rI   r?   r6   r   rJ   r   rL   )rO   r9   r)   s      r   r   r     sf   2 	v{{9:::vzzz$(((v{{1ad
J''
 	
!A$A	
A
Aq6)))AqAqt!t}a(((qAqt!t}qAwh///q1add|Q'''q1add|a1gX...teAdGAdGHr   convolution_matrixr|   c                    |dk    rt          d          | j        dk    rt          d          | j        dk    rt          d          |dvrt          d          t          j        | d|dz
  fd          }t          j        | d	d	d
         d|dz
  fd          }|dk    rKt          || j                  dz
  }|dz  }||z
  }|||j        |z
           }|| |z
  |j        |z
           }	nV|dk    rCt          || j                  dz
  }|}|||j        |z
           }|| |z
  |j        |z
           }	n|}|| d	         }	t          ||	          S )a  Construct a convolution matrix.

    Constructs the Toeplitz matrix representing one-dimensional convolution.

    Args:
        a (cupy.ndarray): The 1-D array to convolve.
        n (int): The number of columns in the resulting matrix. It gives the
            length of the input to be convolved with ``a``. This is analogous
            to the length of ``v`` in ``numpy.convolve(a, v)``.
        mode (str): This must be one of (``'full'``, ``'valid'``, ``'same'``).
            This is analogous to ``mode`` in ``numpy.convolve(v, a, mode)``.

    Returns:
        cupy.ndarray: The convolution matrix whose row count k depends on
        ``mode``:

        =========== =========================
        ``mode``    k
        =========== =========================
        ``'full'``  m + n - 1
        ``'same'``  max(m, n)
        ``'valid'`` max(m, n) - min(m, n) + 1
        =========== =========================

    .. seealso:: :func:`cupyx.scipy.linalg.toeplitz`
    .. seealso:: :func:`scipy.linalg.convolution_matrix`
    r   zn must be a positive integer.r   z;convolution_matrix expects a one-dimensional array as inputzlen(a) must be at least 1.)r|   validsamez8`mode` argument must be one of ('full', 'valid', 'same')constantNr$   r   r<   r   )r?   rI   r6   r   padminr"   )
rO   r9   modeazraztrimtbtecol0row0s
             r   r   r   	  s   : 	Avv8999v{{ * + + 	+v{{5666,,,LN N 	N 
!a1Xz	*	*B
(1TTrT7Q!Hj
1
1Cv~~1af~~!1WBY"RWRZ- A2b5"$%	AF^^a"RWRZ- A2b5"$%A233xD$r   )Nr   Nr   rc   )F)r|   )r   r   r   r   cupyx.scipy.linalgr   
implementsr   r   r   r"   r+   r-   r'   r=   r:   ElementwiseKernelrA   rF   rP   rW   rt   rw   r~   r   r   r   r    r   r   <module>r      s~            & & & & & & E? ? ? ?> F   . F   2 J3 3 3  3> K  6 6 ! 6& H3 3 3 381 1 1 1 J " " "  ", +5*
GA!u6 6 6  H  D FA A A. L!!* * "!*Z K    ! D I       8 I. . .. E# # # #L I  : '((- - )(-` ())8  8  8  *)8  8  8 r   