
    `iN                         d dl 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mZ ddZdd	Z	dd
Z
d ZddZddZddZ	 	 ddZddZddZddZddZdS )    N)_coo)_csc)_csr)_dia)_sputilsdc           
         || }t          |           t          |          }} | |k    r|dk    r|dv rut          j        |dz   d          }t          j        |d          }t          j        ||          }|dk    rt          j        }nt          j        } ||||f||f          S |dk    r]t          j        |d          }	t          j        |d          }
t          j        ||          }t          j	        ||	|
ff||f          S t          j        dt          dt          | |z   |                    f|          }t          ||| |                              |          S )	a  Creates a sparse matrix with ones on diagonal.

    Args:
        m (int): Number of rows.
        n (int or None): Number of columns. If it is ``None``,
            it makes a square matrix.
        k (int): Diagonal to place ones on.
        dtype: Type of a matrix to create.
        format (str or None): Format of the result, e.g. ``format="csr"``.

    Returns:
        cupyx.scipy.sparse.spmatrix: Created sparse matrix.

    .. seealso:: :func:`scipy.sparse.eye`

    Nr   )csrcsc   idtyper
   coo)intcupyarangeonesr   
csr_matrixr   
csc_matrixr   
coo_matrixmaxminspdiagsasformat)mnkr   formatindptrindicesdataclsrowcoldiagss               q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/sparse/_construct.pyeyer(   
   sj   " 	yq663q66qAAvv!q&&^##[Qc222Fk!3///G9Qe,,,Doo3gv.A777u__+as+++C+as+++C9Qe,,,D?D3*#51v>>>Iq#aQUA//0>>>E5!Q""++F333    c                 (    t          | | ||          S )a  Creates an identity matrix in sparse format.

    .. note::
       Currently it only supports csr, csc and coo formats.

    Args:
        n (int): Number of rows and columns.
        dtype: Type of a matrix to create.
        format (str or None): Format of the result, e.g. ``format="csr"``.

    Returns:
        cupyx.scipy.sparse.spmatrix: Created identity matrix.

    .. seealso:: :func:`scipy.sparse.identity`

    )r   r   )r(   )r   r   r   s      r'   identityr+   4   s    " q!50000r)   c                 \    t          j        | |f||f                              |          S )a  Creates a sparse matrix from diagonals.

    Args:
        data (cupy.ndarray): Matrix diagonals stored row-wise.
        diags (cupy.ndarray): Diagonals to set.
        m (int): Number of rows.
        n (int): Number of cols.
        format (str or None): Sparse format, e.g. ``format="csr"``.

    Returns:
        cupyx.scipy.sparse.spmatrix: Created sparse matrix.

    .. seealso:: :func:`scipy.sparse.spdiags`

    shape)r   
dia_matrixr   )r"   r&   r   r   r   s        r'   r   r   H   s/      ?D%=A777@@HHHr)   c                 z   dk    rdnd}t          j        d | D                       }| d         j        |         }t          j        d | D             t          |j        |                    }t          j        |j        |          }t          j        t          fd| D                       dz   |          } |d          }d}	d}
| D ]}|j        |         |k    rt          d|z            |j
        ||
|
|j
        j        z   <   |
|j
        j        z  }
t          |	|	|j                 z             }|j        d	d
         ||<   ||xx         |z  cc<   |	|j                 z  }	||j        d
         z  }||d
<   dk    rt          j        |||f|	|f          S t          j        |||f||	f          S )zYFast path for stacking CSR/CSC matrices
    (i) vstack for CSR, (ii) hstack for CSC.
    r   r   c                     g | ]	}|j         
S  )r"   .0bs     r'   
<listcomp>z,_compressed_sparse_stack.<locals>.<listcomp>`   s    444QV444r)   c                     g | ]	}|j         
S r2   )r    r3   s     r'   r6   z,_compressed_sparse_stack.<locals>.<listcomp>b   s    0J0J0Ja0J0J0Jr)   )arraysmaxvalr   c              3   2   K   | ]}|j                  V  d S Nr-   )r4   r5   axiss     r'   	<genexpr>z+_compressed_sparse_stack.<locals>.<genexpr>e   s=       - - ! GDM - - - - - -r)   z#incompatible dimensions for axis %dNr-   )r   concatenater.   r   get_index_dtyper   sizeemptysum
ValueErrorr!   slicer    r   r   r   r   )blocksr<   
other_axisr"   constant_dim	idx_dtyper!   r    last_indptrsum_dimsum_indicesr5   idxss    `           r'   _compressed_sparse_stackrN   [   s5    aiiQJ44V44455D!9?:.L(0J0J60J0J0J03DI|0L0LN N NIj)444GZ - - - -%+- - - - -/018AC C CF)A,,KGK 
$ 
$7:,..5
BD D D:;)K	667qy~%Wg566x}tt#174= qx|#F2Jqyygv6&-|%<> > > 	> gv6&2G%<> > > 	>r)   c                 (    t          | g||          S )a  Stacks sparse matrices horizontally (column wise)

    Args:
        blocks (sequence of cupyx.scipy.sparse.spmatrix):
            sparse matrices to stack

        format (str):
            sparse format of the result (e.g. "csr")
            by default an appropriate sparse matrix format is returned.
            This choice is subject to change.
        dtype (dtype, optional):
            The data-type of the output matrix.  If not given, the dtype is
            determined from that of ``blocks``.

    Returns:
        cupyx.scipy.sparse.spmatrix: the stacked sparse matrix

    .. seealso:: :func:`scipy.sparse.hstack`

    Examples:
        >>> from cupy import array
        >>> from cupyx.scipy.sparse import csr_matrix, hstack
        >>> A = csr_matrix(array([[1., 2.], [3., 4.]]))
        >>> B = csr_matrix(array([[5.], [6.]]))
        >>> hstack([A, B]).toarray()
        array([[1., 2., 5.],
               [3., 4., 6.]])
    r   r   bmatrF   r   r   s      r'   hstackrT   ~   s    : u5555r)   c                 :    t          d | D             ||          S )a  Stacks sparse matrices vertically (row wise)

    Args:
        blocks (sequence of cupyx.scipy.sparse.spmatrix)
            sparse matrices to stack
        format (str, optional):
            sparse format of the result (e.g. "csr")
            by default an appropriate sparse matrix format is returned.
            This choice is subject to change.
        dtype (dtype, optional):
            The data-type of the output matrix.  If not given, the dtype is
            determined from that of `blocks`.

    Returns:
        cupyx.scipy.sparse.spmatrix: the stacked sparse matrix

    .. seealso:: :func:`scipy.sparse.vstack`

    Examples:
        >>> from cupy import array
        >>> from cupyx.scipy.sparse import csr_matrix, vstack
        >>> A = csr_matrix(array([[1., 2.], [3., 4.]]))
        >>> B = csr_matrix(array([[5., 6.]]))
        >>> vstack([A, B]).toarray()
        array([[1., 2.],
               [3., 4.],
               [5., 6.]])
    c                     g | ]}|gS r2   r2   r3   s     r'   r6   zvstack.<locals>.<listcomp>   s    %%%!%%%r)   rP   rQ   rS   s      r'   vstackrW      s(    : %%f%%%fEBBBBr)   c           	      P	   t          |           }t          | d                   }g }t          |          D ]C}t          |          D ]1}| |         |         !|                    | |         |                    2Dt          |          dk    rt          j        d|          S |dk    rF|dv rBt          d |D                       r)t          |d          }||                    |          }|S |dk    rF|dv rBt          d	 |D                       r)t          |d          }||                    |          }|S t          j	        ||ft                    }	t          j	        |dz   t          j                  }
t          j	        |dz   t          j                  }t          |          D ]N}t          |          D ]:}| |         |         (t          j        | |         |                   }|| |         |<   d
|	|         |<   |
|dz            dk    r|j        d         |
|dz   <   nV|
|dz            |j        d         k    r<d                    |||
|dz            |j        d                   }t          |          ||dz            dk    r|j        d         ||dz   <   ||dz            |j        d         k    r<d                    ||||dz            |j        d                   }t          |          <Pt          d |D                       }|d |D             }|rt!          j        | nd}t          j        |
          }t          j        |          }|d         |d         f}t'          j        ||          }t!          j        t-          |                    }t'          j        ||          }t'          j        ||          }d}t          j        |	          \  }}t1          ||          D ]\  }}| t3          |                   t3          |                   }t5          |||j        z             }|j        ||<   |j        ||         z   ||<   |j        ||         z   ||<   ||j        z  }t          j        |||ff|                              |          S )a  Builds a sparse matrix from sparse sub-blocks

    Args:
        blocks (array_like):
            Grid of sparse matrices with compatible shapes.
            An entry of None implies an all-zero matrix.
        format ({'bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil'}, optional):
            The sparse format of the result (e.g. "csr").  By default an
            appropriate sparse matrix format is returned.
            This choice is subject to change.
        dtype (dtype, optional):
            The data-type of the output matrix.  If not given, the dtype is
            determined from that of `blocks`.
    Returns:
        bmat (sparse matrix)

    .. seealso:: :func:`scipy.sparse.bmat`

    Examples:
        >>> from cupy import array
        >>> from cupyx.scipy.sparse import csr_matrix, bmat
        >>> A = csr_matrix(array([[1., 2.], [3., 4.]]))
        >>> B = csr_matrix(array([[5.], [6.]]))
        >>> C = csr_matrix(array([[7.]]))
        >>> bmat([[A, B], [None, C]]).toarray()
        array([[1., 2., 5.],
               [3., 4., 6.],
               [0., 0., 7.]])
        >>> bmat([[A, None], [None, C]]).toarray()
        array([[1., 2., 0.],
               [3., 4., 0.],
               [0., 0., 7.]])

    r   N)r   r   r   r   )Nr
   c              3   J   K   | ]}t          |t          j                  V  d S r;   )
isinstancer   r   r3   s     r'   r=   zbmat.<locals>.<genexpr>   sB       & & 1do.. & & & & & &r)   )Nr   c              3   J   K   | ]}t          |t          j                  V  d S r;   )rZ   r   r   r3   s     r'   r=   zbmat.<locals>.<genexpr>   s.      FFQ*Q00FFFFFFr)   Tzeblocks[{i},:] has incompatible row dimensions. Got blocks[{i},{j}].shape[0] == {got}, expected {exp}.)r   jexpgotzeblocks[:,{j}] has incompatible row dimensions. Got blocks[{i},{j}].shape[1] == {got}, expected {exp}.c              3   $   K   | ]}|j         V  d S r;   )nnz)r4   blocks     r'   r=   zbmat.<locals>.<genexpr>#  s$      11Eei111111r)   c                     g | ]	}|j         
S r2   r   )r4   blks     r'   r6   zbmat.<locals>.<listcomp>%  s    777Cci777r)   r>   )r9   r-   ) lenrangeappendr   r   allrN   astypenumpyzerosboolint64r.   r   rD   rC   r   upcastcumsumr   rB   r@   r   nonzerozipr   rE   r`   r"   r$   r%   r   )rF   r   r   MNblocks_flatr   r   A
block_maskbrow_lengthsbcol_lengthsr   r\   msgr`   
all_dtypesrow_offsetscol_offsetsr.   r"   rI   r$   r%   iijjBidxs                               r'   rR   rR      s   T 	FAF1IAK1XX 1 1q 	1 	1Aay|'""6!9Q<000	1 ;1vU3333 	
Q6]** & &$& & & & & + %[!44A
q&&V},,FF+FFFFF -$[!44AaV4000J;qs%+666L;qs%+666L 1XX * *q 	* 	*Aay|'OF1IaL11 q	!#'
1a !$))()
L1%%!!A#&!'!*44--3Va18DQqS8I89
 .4 .D .D 
 %S//)!$))()
L1%%!!A#&!'!*44--3Va18DQqS8I89
 .4 .D .D 
 %S//)1	*4 11[111
1
1C}77;777
0:D,,,|,,K,|,,K_k"o.E:c'''D(E

;;;I
*S	
*
*
*C
*S	
*
*
*C
C]:&&FBB  13q66N3q66"Cqu%%FS	5;q>)C5;q>)Cqu?D3*-U;;;DDVLLLr)   {Gz?r   c                 ^   |dk     s|dk    rt          d          t          j        |          }|j        dvrt	          d|z            | |z  }t          || z  |z            }|t          j        }n@t          |t
          t          j        f          rt          j        	                    |          }||j
        }|                    ||d          }	|	| z  }
|	|
| z  z
  } ||                              |          }t          j        |||
ff| |f	                              |          S )
a  Generates a random sparse matrix.

    This function generates a random sparse matrix. First it selects non-zero
    elements with given density ``density`` from ``(m, n)`` elements.
    So the number of non-zero elements ``k`` is ``k = m * n * density``.
    Value of each element is selected with ``data_rvs`` function.

    Args:
        m (int): Number of rows.
        n (int): Number of cols.
        density (float): Ratio of non-zero entries.
        format (str): Matrix format.
        dtype (~cupy.dtype): Type of the returned matrix values.
        random_state (cupy.random.RandomState or int):
            State of random number generator.
            If an integer is given, the method makes a new state for random
            number generator and uses it.
            If it is not given, the default state is used.
            This state is used to generate random indexes for nonzero entries.
        data_rvs (callable): A function to generate data for a random matrix.
            If it is not given, `random_state.rand` is used.

    Returns:
        cupyx.scipy.sparse.spmatrix: Generated matrix.

    .. seealso:: :func:`scipy.sparse.random`

    r   r   z(density expected to be 0 <= density <= 1fdztype %s not supportedNF)rA   replacer-   )rD   r   r   charNotImplementedErrorr   randomrZ   integerRandomStaterandchoicerh   r   r   r   )r   r   densityr   r   random_statedata_rvsmnr   indr\   r   valss                r'   r   r   ?  s?   < {{gkkCDDDJuEz!"9E"ABBB	
QBGaK!OA{	L3"5	6	6 ={..|<<$


bq%

8
8CqAa!eA8A;;e$$D?	1vq!f& & &&.hv&6&67r)   c                 *    t          | |||||          S )aN  Generates a random sparse matrix.

    See :func:`cupyx.scipy.sparse.random` for detail.

    Args:
        m (int): Number of rows.
        n (int): Number of cols.
        density (float): Ratio of non-zero entries.
        format (str): Matrix format.
        dtype (~cupy.dtype): Type of the returned matrix values.
        random_state (cupy.random.RandomState or int):
            State of random number generator.
            If an integer is given, the method makes a new state for random
            number generator and uses it.
            If it is not given, the default state is used.
            This state is used to generate random indexes for nonzero entries.

    Returns:
        cupyx.scipy.sparse.spmatrix: Generated matrix.

    .. seealso:: :func:`scipy.sparse.rand`
    .. seealso:: :func:`cupyx.scipy.sparse.random`

    )r   )r   r   r   r   r   r   s         r'   r   r   w  s    2 !Q===r)   c           
      `   t          j        |          rRt          |           dk    st          j        | d                   rt          j        |           g} n6t          d          t          t          t          j        |                     } t          |t          j	                  r|
                                }t          j        |          }t          |           t          |          k    rt          d          |<t          | d                   t          t          |d                             z   f}|t          j        |  }|\  t          fd|D                       }t          d|          }t          j        t          |          |f|          }t#                    }t%          |           D ]\  }}	||         }
t          d|
          }t#          |
z   |
z
  |          }|dk     rt          d|
|fz            	 |	dd|f         |||||z   f<   f# t
          $ rL t          |	          |k    r7t          |	          dk    r$t          d	|t          |	          |
fz             w xY wt'          j        ||ff
                              |          S )a  Construct a sparse matrix from diagonals.

    Args:
        diagonals (sequence of array_like):
            Sequence of arrays containing the matrix diagonals, corresponding
            to `offsets`.
        offsets (sequence of int or an int):
            Diagonals to set:
                - k = 0  the main diagonal (default)
                - k > 0  the k-th upper diagonal
                - k < 0  the k-th lower diagonal
        shape (tuple of int):
            Shape of the result. If omitted, a square matrix large enough
            to contain the diagonals is returned.
        format ({"dia", "csr", "csc", "lil", ...}):
            Matrix format of the result.  By default (format=None) an
            appropriate sparse matrix format is returned.  This choice is
            subject to change.
        dtype (dtype): Data type of the matrix.

    Returns:
        cupyx.scipy.sparse.spmatrix: Generated matrix.

    Notes:
        This function differs from `spdiags` in the way it handles
        off-diagonals.

        The result from `diags` is the sparse equivalent of::

            cupy.diag(diagonals[0], offsets[0])
            + ...
            + cupy.diag(diagonals[k], offsets[k])

        Repeated diagonal offsets are disallowed.
    r   z*Different number of diagonals and offsets.Nc                 ^    g | ])}t          |z   |z
            t          d |          z   *S )r   )r   r   )r4   offsetr   r   s     r'   r6   zdiags.<locals>.<listcomp>  sH     $ $ $ VQZ((3q&>>9 $ $ $r)   r   z"Offset %d (index %d) out of bounds.r   zUDiagonal length (index %d: %d at offset %d) does not agree with matrix size (%d, %d).r-   )r   isscalarlikerd   r   
atleast_1drD   listmaprZ   ndarraygetri   absr   common_typer   rj   r   	enumerater   r/   r   )	diagonalsoffsetsr.   r   r   rq   data_arrKr\   diagonalr   r   lengthr   r   s                @@r'   r&   r&     s   J W%% :y>>Q("7	!"E"E334IIIJJJT_i8899	'4<((  ++--w''G 9~~W%%EFFF }	!C
OO 4 44A } ), DAq $ $ $ $ $"$ $ $ 	% 	%AAq		Az3w<<+5999HAq		A ++  86NNQZVQ//A::4{BD D D	&.sGVG|&<HQ!F(
]## 	 	 	8}}&&3x==A+=+= 73x==&!Q:889 9 9 	 ?Hg.q!f===FFvNNNs   H**AJ c                    t          j        |           } t          j        |          }| j        d         |j        d         z  | j        d         |j        d         z  f}| j        dk    s|j        dk    r't          j        |                              |          S t          |d         |d                   t          j        d          j        k    rt          j        }nt          j	        }| j
                            |d          |j        d         z  }|                    |j                  }| j                            |d          |j        d         z  }|                    |j                  }| j                            |j                  }|                    d|j                  |                    d|j                  }}||j
        z  }||j        z  }|                                |                                }}|                    d|j                  |j        z  }|                                }t          j        |||ff|                              |          S )a  Kronecker product of sparse matrices A and B.

    Args:
        A (cupyx.scipy.sparse.spmatrix): a sparse matrix.
        B (cupyx.scipy.sparse.spmatrix): a sparse matrix.
        format (str): the format of the returned sparse matrix.

    Returns:
        cupyx.scipy.sparse.spmatrix:
            Generated sparse matrix with the specified ``format``.

    .. seealso:: :func:`scipy.sparse.kron`

    r   r   int32T)copyr>   r-   )r   r   r.   r`   r   r   r   iinforl   r   r$   rh   repeatr%   r"   reshaperavel)rt   r~   r   	out_shaper   r$   r%   r"   s           r'   kronr     s   & 	AAagaj(!'!*qwqz*ABIuzzQUaZZy))226:::
9Q<1&&G)<)<)@@@

 %,,u4,
(
(171:
5C
**QU

C
%,,u4,
(
(171:
5C
**QU

C6==D {{2qu%%s{{2qu'='=C15LC15LCyy{{CIIKKC <<AE""QV+D::<<D?	Sz)- - --5Xf-=-=>r)   c                    t          j        |           } t          j        |          }| j        d         | j        d         k    rt          d          |j        d         |j        d         k    rt          d          t	          j        | j        |j                  }t          t          |j        d         |          | |          }t          |t          | j        d         |          |          }||z   	                    |          S )a%  Kronecker sum of sparse matrices A and B.

    Kronecker sum is the sum of two Kronecker products
    ``kron(I_n, A) + kron(B, I_m)``, where ``I_n`` and ``I_m`` are identity
    matrices.

    Args:
        A (cupyx.scipy.sparse.spmatrix): a sparse matrix.
        B (cupyx.scipy.sparse.spmatrix): a sparse matrix.
        format (str): the format of the returned sparse matrix.

    Returns:
        cupyx.scipy.sparse.spmatrix:
            Generated sparse matrix with the specified ``format``.

    .. seealso:: :func:`scipy.sparse.kronsum`

    r   r   zA is not square matrixzB is not square matrixr   )r   )
r   r   r.   rD   r   rm   r   r   r(   r   )rt   r~   r   r   LRs         r'   kronsumr   %  s    & 	AAwqzQWQZ1222wqzQWQZ1222OAGQW--ES5)))1V<<<AQAGAJe,,,V<<<AEF###r)   )Nr   r   N)r   Nr;   )NN)r   r   NNN)r   r   NN)r   NNN)ri   r   cupyx.scipy.sparser   r   r   r   r   r(   r+   r   rN   rT   rW   rR   r   r   r&   r   r   r2   r)   r'   <module>r      s     # # # # # # # # # # # # # # # # # # # # # # # # ' ' ' ' ' ''4 '4 '4 '4T1 1 1 1(I I I I& >  >  >F6 6 6 6@C C C C@~M ~M ~M ~MB 48'+57 57 57 57p> > > >8ZO ZO ZO ZOz2> 2> 2> 2>j!$ !$ !$ !$ !$ !$r)   