
    `iZ                        d 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l	Z		 ddl
ZdZn# e$ r d	ZY nw xY wee	j        e	j        fZee	j        fZ ej        d
ddd          Z ej        dddd          Zd Zd Z ej        dddd          Zd Zd Zd Z ej        ddddd          Z ej        d d!d"d#d          Z	 d3d$Z  ej        d%d&d'd(          Z! G d) d*e"          Z#d+ Z$d, Z%d- Z&d. Z'd4d0Z(d1 Z)d2 Z*dS )5z*Indexing mixin for sparse matrix classes.
    N)_core)
isspmatrix)spmatrix)device)runtimeTFzT d, S ind, int32 minorzraw T answerz+if (ind == minor) atomicAdd(&answer[0], d);#cupyx_scipy_sparse_compress_getitemz"T real, T imag, S ind, int32 minorz$raw T answer_real, raw T answer_imagzo
    if (ind == minor) {
    atomicAdd(&answer_real[0], real);
    atomicAdd(&answer_imag[0], imag);
    }
    +cupyx_scipy_sparse_compress_getitem_complexc                     |||dz            }t          |d                   t          |d                   }}||z
  }|||         }| ||         }	|	||fS )aE  Return a submatrix of the input sparse matrix by slicing major axis.

    Args:
        Ax (cupy.ndarray): data array from input sparse matrix
        Aj (cupy.ndarray): indices array from input sparse matrix
        Ap (cupy.ndarray): indptr array from input sparse matrix
        start (int): starting index of major axis
        stop (int): ending index of major axis

    Returns:
        Bx (cupy.ndarray): data array of output sparse matrix
        Bj (cupy.ndarray): indices array of output sparse matrix
        Bp (cupy.ndarray): indptr array of output sparse matrix

       r   )int)
AxAjApstartstopstart_offsetstop_offsetBpBjBxs
             m/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/sparse/_index.py_get_csr_submatrix_major_axisr   +   sg      
E$(N	B #BqE

C2KK+L	l	B	L$	%B	L$	%Br2:    c                     ||k    ||k     z  }t          j        |j        dz   |j                  }d|d<   ||dd<   t          j        ||           ||         }||         |z
  }| |         }	|	||fS )aE  Return a submatrix of the input sparse matrix by slicing minor axis.

    Args:
        Ax (cupy.ndarray): data array from input sparse matrix
        Aj (cupy.ndarray): indices array from input sparse matrix
        Ap (cupy.ndarray): indptr array from input sparse matrix
        start (int): starting index of minor axis
        stop (int): ending index of minor axis

    Returns:
        Bx (cupy.ndarray): data array of output sparse matrix
        Bj (cupy.ndarray): indices array of output sparse matrix
        Bp (cupy.ndarray): indptr array of output sparse matrix

    r   dtyper   Nout)cupyemptysizer   cumsum)
r   r   r   r   r   maskmask_sumr   r   r   s
             r   _get_csr_submatrix_minor_axisr&   D   s      RKBI&Dz"'A+RX666HHQKHQRRLKh''''	"B	DE	B	DBr2:r   zNint32 out_rows, raw I rows, raw int32 Ap, raw int32 Aj, raw T Ax, raw int32 Bpzint32 Bj, T BxaD  
    const I row = rows[out_rows];

    // Look up starting offset
    const I starting_output_offset = Bp[out_rows];
    const I output_offset = i - starting_output_offset;
    const I starting_input_offset = Ap[row];

    Bj = Aj[starting_input_offset + output_offset];
    Bx = Ax[starting_input_offset + output_offset];
$cupyx_scipy_sparse_csr_row_index_kerc                 D   t          j        |          }t          j        |j        dz   |j                  }d|d<   t          j        ||         |dd                    t          |d                   }t          ||          }t          ||||| |          \  }}	|	||fS )a  Populate indices and data arrays from the given row index
    Args:
        Ax (cupy.ndarray): data array from input sparse matrix
        Aj (cupy.ndarray): indices array from input sparse matrix
        Ap (cupy.ndarray): indptr array from input sparse matrix
        rows (cupy.ndarray): index array of rows to populate
    Returns:
        Bx (cupy.ndarray): data array of output sparse matrix
        Bj (cupy.ndarray): indices array of output sparse matrix
        Bp (cupy.ndarray): indptr array for output sparse matrix
    r   r   r   Nr   r   )	r    diffr!   r"   r   r#   r   _csr_indptr_to_coo_rows_csr_row_index_ker)
r   r   r   rowsrow_nnzr   nnzout_rowsr   r   s
             r   _csr_row_indexr0   q   s     immG	DIM	2	2	2BBqEK2abb6****
bf++C&sB//H$BB??FBr2:r   c                 0   ddl m} t          j        | t          j                  }t          j                    }t          j	        r| dk    rt          d          |                    ||j        j        | |j        dz
  |j        j        |j                   |S )Nr   )cusparser   z@hipSPARSE currently cannot handle sparse matrices with null ptrsr   )cupy_backends.cuda.libsr2   r    r!   numpyint32r   get_cusparse_handler   is_hip
ValueErrorxcsr2coodataptrr"   CUSPARSE_INDEX_BASE_ZERO)r.   r   r2   r/   handles        r   r*   r*      s    000000z#U[111H
 '))F~ ;#(( : ; ; 	;S"'!)X]->)+ + + Or   c                    t          j        | |          } t          j        ||          }t          j        || g          }t          j        |                              |          }| |         }||         }||         }t          j        |j        d          }	t          ||||	|j        dz
             ||	         ||	         ||	         fS )z;Find the unique indices for each row and keep only the lastr   boolr   r"   )r    asarraystacklexsortastypeonesr"   _unique_mask_kern)
ijx	idx_dtypestackedorderindptr_insertsindices_insertsdata_insertsr$   s
             r   _select_last_indicesrP      s    Qi(((AQi(((Aj!Q  GL!!((33EuXNhOU8L9^(777Dnoud).q02 2 2 2 $!6T8JJJr   zqraw I insert_indices, raw T insert_values, raw I insertion_indptr,
        raw I Ap, raw I Aj, raw T Ax, raw I Bpzraw I Bj, raw T Bxa  

        const I input_row_start = Ap[i];
        const I input_row_end = Ap[i+1];
        const I input_count = input_row_end - input_row_start;

        const I insert_row_start = insertion_indptr[i];
        const I insert_row_end = insertion_indptr[i+1];
        const I insert_count = insert_row_end - insert_row_start;

        I input_offset = 0;
        I insert_offset = 0;

        I output_n = Bp[i];

        I cur_existing_index = -1;
        T cur_existing_value = -1;

        I cur_insert_index = -1;
        T cur_insert_value = -1;

        if(input_offset < input_count) {
            cur_existing_index = Aj[input_row_start+input_offset];
            cur_existing_value = Ax[input_row_start+input_offset];
        }

        if(insert_offset < insert_count) {
            cur_insert_index = insert_indices[insert_row_start+insert_offset];
            cur_insert_value = insert_values[insert_row_start+insert_offset];
        }


        for(I jj = 0; jj < input_count + insert_count; jj++) {

            // if we have both available, use the lowest one.
            if(input_offset < input_count &&
               insert_offset < insert_count) {

                if(cur_existing_index < cur_insert_index) {
                    Bj[output_n] = cur_existing_index;
                    Bx[output_n] = cur_existing_value;

                    ++input_offset;

                    if(input_offset < input_count) {
                        cur_existing_index = Aj[input_row_start+input_offset];
                        cur_existing_value = Ax[input_row_start+input_offset];
                    }


                } else {
                    Bj[output_n] = cur_insert_index;
                    Bx[output_n] = cur_insert_value;

                    ++insert_offset;
                    if(insert_offset < insert_count) {
                        cur_insert_index =
                            insert_indices[insert_row_start+insert_offset];
                        cur_insert_value =
                            insert_values[insert_row_start+insert_offset];
                    }
                }

            } else if(input_offset < input_count) {
                Bj[output_n] = cur_existing_index;
                Bx[output_n] = cur_existing_value;

                ++input_offset;
                if(input_offset < input_count) {
                    cur_existing_index = Aj[input_row_start+input_offset];
                    cur_existing_value = Ax[input_row_start+input_offset];
                }

            } else {
                    Bj[output_n] = cur_insert_index;
                    Bx[output_n] = cur_insert_value;

                    ++insert_offset;
                    if(insert_offset < insert_count) {
                        cur_insert_index =
                            insert_indices[insert_row_start+insert_offset];
                        cur_insert_value =
                            insert_values[insert_row_start+insert_offset];
                    }
            }

            output_n++;
        }
    1cupyx_scipy_sparse_csr_copy_existing_indices_kern)	no_returnz#raw I rows, raw I cols, raw I orderzraw bool maskaT  
    I cur_row = rows[i];
    I next_row = rows[i+1];

    I cur_col = cols[i];
    I next_col = cols[i+1];

    I cur_order = order[i];
    I next_order = order[i+1];

    if(cur_row == next_row && cur_col == next_col) {
        if(cur_order < next_order)
            mask[i] = false;
        else
            mask[i+1] = false;
    }
    #cupyx_scipy_sparse_unique_mask_kernc                     ||dk     xx         | z  cc<   ||dk     xx         |z  cc<   t          | ||||||||j        	  	        S )a  Populate data array for a set of rows and columns
    Args
        n_row : total number of rows in input array
        n_col : total number of columns in input array
        Ap : indptr array for input sparse matrix
        Aj : indices array for input sparse matrix
        Ax : data array for input sparse matrix
        Bi : array of rows to extract from input sparse matrix
        Bj : array of columns to extract from input sparse matrix
    Returns
        Bx : data array for output sparse matrix
    r   r@   )_csr_sample_values_kernr"   )n_rown_colr   r   r   Bir   not_found_vals           r   _csr_sample_valuesrZ   '  sg      rAvJJJ%JJJrAvJJJ%JJJ"5%#%r2#%r#0(*	1 1 1 1r   zWI n_row, I n_col, raw I Ap, raw I Aj, raw T Ax,
    raw I Bi, raw I Bj, I not_found_valzraw T Bxat  
    const I j = Bi[i]; // sample row
    const I k = Bj[i]; // sample column
    const I row_start = Ap[j];
    const I row_end   = Ap[j+1];
    T x = 0;
    bool val_found = false;
    for(I jj = row_start; jj < row_end; jj++) {
        if (Aj[jj] == k) {
            x += Ax[jj];
            val_found = true;
        }
    }
    Bx[i] = val_found ? x : not_found_val;
)cupyx_scipy_sparse_csr_sample_values_kernc                       e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )
IndexMixinzS
    This class provides common dispatching and validation logic for indexing.
    c                    t           r<t          j                            t          j                  dk     rt          d          |                     |          \  }}t          |t                    rt          |t                    r| 
                    ||          S t          |t                    r|                     ||          S |j        dk    r|                     ||          S t          d          t          |t                    rt          |t                    r|                     ||          S t          |t                    rC|t          d           k    r||k    r|                                 S |                     ||          S |j        dk    r|                     ||          S t          d          |j        dk    rWt          |t                    r|                     ||          S t          |t                    r|                     ||          S nt          |t                    r|                     ||          S t          |t                    rt          d          |j        d         dk    rN|j        dk    s|j        d         dk    r2|                     |d d df         |                                          S t3          j        ||          \  }}|j        |j        k    rt          d          |j        dk    r3|                     t3          j        |          j        | j                  S |                     ||          S )Nz1.4.0z,Sparse __getitem__() requires Scipy >= 1.4.0r   zindex results in >2 dimensionsr   'number of row and column indices differr   ) scipy_availabler4   libNumpyVersionscipy__version__NotImplementedError_parse_indices
isinstance_int_scalar_types_get_intXintslice_get_intXslicendim_get_intXarray
IndexError_get_sliceXintcopy_get_sliceXslice_get_sliceXarray_get_arrayXint_get_arrayXsliceshape_get_columnXarrayravelr    broadcast_arraysr"   	__class__
atleast_2dr   _get_arrayXarray)selfkeyrowcols       r   __getitem__zIndexMixin.__getitem__Z  s7     	@uy55! #  #%, -  -%>@ @ @ &&s++S c,-- 	F#011 5((c222C'' 5**3444Q**3444=>>>U## 	F#011 7**3444C'' 7%++%%#**99;;&,,S#666Q,,S#666=>>>X]]#011 7**3444C'' 7,,S#6667 #011 F**3444C'' F !ABBB1""A19J9J--c!!!Q$iEEE (c22S9	!!FGGG8q==>>$/#"6"6"<DJ>OOO$$S#...r   c                 L   |                      |          \  }}t          |t                    rnt          |t                    rYt          j        || j                  }|j        dk    rt          d          |                     |||j	        d                    d S t          |t                    r7t          j        |                    | j        d                    d d d f         }nt          j        |          }t          |t                    rNt          j        |                    | j        d                    d d d f         }|j        dk    r|d d d f         }nt          j        |          }t          j        ||          \  }}|j        |j        k    rt#          d          t%          |          r|j        dk    r|d          }|d          }|j        d         dk    o|j        d         dk    }|j        d         dk    o|j        d         dk    }|s|j        d         |j        d         k    r|s+|j        d         |j        d         k    st          d          |j        dk    rd S |                    d          }|                                 |                     |||           d S t          j        || j                  }t          j        ||          \  }}	|j        dk    rd S |                    |j                  }|                     |||           d S )	Nr   r   z&Trying to assign a sequence to an itemr   r_   zshape mismatch in assignmentT)rp   )rf   rg   rh   r    rA   r   r"   r8   _set_intXintflatrj   arangeindicesru   
atleast_1drl   rx   rn   r   tocoosum_duplicates_set_arrayXarray_sparsereshape_set_arrayXarray)
r|   r}   rI   r~   r   rG   rH   broadcast_rowbroadcast_col_s
             r   __setitem__zIndexMixin.__setitem__  s   &&s++Sc,-- 	3 122	Qdj111Av{{ !IJJJc3q	222Fc5!! 	'+s{{4:a=99:111d7CCC/#&&Cc5!! 	'+s{{4:a=99:47CCx1}}!!!T'l/#&&C$S#..17agFGGGa== 	+v{{dGdGGAJ!O?
aMGAJ!O?
aM" AagajAGAJ&>&>" '?&'gajAGAJ&>&> !?@@@v{{T""A((Aq11111 Qdj111A(A..DAqv{{		!'""A!!!Q*****r   c                     t          |t          j        t          j        f          r|j        dk    r|j        dk    rdS dS )Nr   r   TF)rg   r    ndarrayr4   rl   r"   )r|   indexs     r   
_is_scalarzIndexMixin._is_scalar  s<    edlEM:;; 	
aEJ!OO4ur   c                 .   | j         \  }}t          |          \  }}|                     |          r|                                }|                     |          r|                                }t	          |t
                    rt          ||d          }n+t	          |t                    s|                     ||          }t	          |t
                    rt          ||d          }n+t	          |t                    s|                     ||          }||fS )Nr~   column)	ru   _unpack_indexr   itemrg   rh   _normalize_indexrj   
_asindices)r|   r}   MNr~   r   s         r   rf   zIndexMixin._parse_indices  s   z1 %%S??3 	((**C??3 	((**C c,-- 	*"3511CCC'' 	*//#q))Cc,-- 	*"3844CCC'' 	*//#q))CCxr   c                     	 t          j        || j        j                  }n*# t          t
          t          f$ r t          d          w xY w|j        dvrt          d          ||z  S )a  Convert `idx` to a valid index for an axis with a given length.
        Subclasses that need special validation can override this method.

        idx is assumed to be at least a 1-dimensional array-like, but can
        have no more than 2 dimensions.
        r   zinvalid index)r      zIndex dimension must be <= 2)	r    rA   r   r   r8   	TypeErrorMemoryErrorrn   rl   )r|   idxlengthrI   s       r   r   zIndexMixin._asindices  sz    	.S(:;;;AAI{3 	. 	. 	._---	. 6;<<<6zs	    # 'A
c                 ~    | j         \  }}t          ||d          }|                     |t          d                    S )zReturn a copy of row i of the matrix, as a (1 x n) row vector.

        Args:
            i (integer): Row

        Returns:
            cupyx.scipy.sparse.spmatrix: Sparse matrix with single row
        r   N)ru   r   rk   rj   r|   rG   r   r   s       r   getrowzIndexMixin.getrow  s<     z1Q7++""1eDkk222r   c                 ~    | j         \  }}t          ||d          }|                     t          d          |          S )zReturn a copy of column i of the matrix, as a (m x 1) column vector.

        Args:
            i (integer): Column

        Returns:
            cupyx.scipy.sparse.spmatrix: Sparse matrix with single column
        r   N)ru   r   ro   rj   r   s       r   getcolzIndexMixin.getcol  s<     z1Q7++""5;;222r   c                     t                      Nre   r|   r~   r   s      r   ri   zIndexMixin._get_intXint      !###r   c                     t                      r   r   r   s      r   rm   zIndexMixin._get_intXarray  r   r   c                     t                      r   r   r   s      r   rk   zIndexMixin._get_intXslice  r   r   c                     t                      r   r   r   s      r   ro   zIndexMixin._get_sliceXint  r   r   c                     t                      r   r   r   s      r   rq   zIndexMixin._get_sliceXslice  r   r   c                     t                      r   r   r   s      r   rr   zIndexMixin._get_sliceXarray  r   r   c                     t                      r   r   r   s      r   rs   zIndexMixin._get_arrayXint  r   r   c                     t                      r   r   r   s      r   rt   zIndexMixin._get_arrayXslice   r   r   c                     t                      r   r   r   s      r   rv   zIndexMixin._get_columnXarray#  r   r   c                     t                      r   r   r   s      r   r{   zIndexMixin._get_arrayXarray&  r   r   c                     t                      r   r   r|   r~   r   rI   s       r   r   zIndexMixin._set_intXint)  r   r   c                     t                      r   r   r   s       r   r   zIndexMixin._set_arrayXarray,  r   r   c                     t          j        |                                | j                  }t          j        ||          \  }}|                     |||           d S )Nr   )r    rA   toarrayr   rx   r   )r|   r~   r   rI   r   s        r   r   z"IndexMixin._set_arrayXarray_sparse/  sT    LDJ777$Q,,1c3*****r   N)__name__
__module____qualname____doc__r   r   r   rf   r   r   r   ri   rm   rk   ro   rq   rr   rs   rt   rv   r{   r   r   r    r   r   r]   r]   U  sL        2/ 2/ 2/h1+ 1+ 1+f    2  "3 3 33 3 3$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $$ $ $+ + + + +r   r]   c                 R    t           rt          | t          j        j                  S dS )NF)r`   rg   rc   sparser   )r   s    r   _try_is_scipy_spmatrixr   6  s$     8%!67775r   c                 |   t          | t          t          j        t          j        f          st          |           r/| j        dk    r$| j        j        dk    r| 	                                S t          |           } t          | t                    rSt          |           dk    r| \  }}nt          |           dk    r| d         t          d          }}nzt          d          t          |           }|| t          d          }}nH|j        dk     rt!          |          t          d          fS |j        dk    r|	                                S t#          |          st#          |          rt          d          t          |          }t          |          }|t!          |          }|t!          |          }||fS )a   Parse index. Always return a tuple of the form (row, col).
    Valid type for row/col is integer, slice, or array of integers.

    Returns:
          resulting row & col indices : single integer, slice, or
          array of integers. If row & column indices are supplied
          explicitly, they are used as the major/minor indices.
          If only one index is supplied, the minor index is
          assumed to be all (e.g., [maj, :]).
    r   br   r   Nzinvalid number of indiceszoIndexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.)rg   r   r    r   r4   r   rl   r   kindnonzero_eliminate_ellipsistuplelenrj   rn   _compatible_boolean_index_boolean_index_to_arrayr   )r   r~   r   r   bool_rowbool_cols         r   r   r   <  s    
EHdl!M+ 
, 
, "5)) 
aEK$4$;$;}}  &&E % !u::??HCZZ1__QxtCC8999'..;eDkkCCX\\*3//t<<X]];;== # !*S// !  ! ! 	! )--H(--H%h//%h//8Or   c                    | t           u rt          d          t          d          fS t          | t                    s| S t	          |           D ]\  }}|t           u r|} n| S t          |           dk    rt          d          t          d          fS t          |           dk    ra|dk    rD| d         t           u rt          d          t          d          fS t          d          | d         fS | d         t          d          fS g }| |dz   d         D ] }|t           ur|                    |           !|t          |          z   }t          dd|z
            }| d|         t          d          f|z  z   t          |          z   S )z6Process indices with Ellipsis. Returns modified index.Nr   r   r   )Ellipsisrj   rg   r   	enumerater   appendmax)r   rH   vfirst_ellipsistailndnslices          r   r   r   r  s   dU4[[))eU##  %    1==NE   5zzQdU4[[))
5zzQQQx8##dU4[[11$KKq**a%++&& D>!#$$%  HKKNNN	#d))	#BAF^^F.!U4[[NV$;;eDllJJr   c                 |    | | k     s| |k    r#t          d                    ||                     | dk     r| |z  } | S )Nz{} ({}) out of ranger   )rn   format)rI   dimnames      r   r   r     sK    C4xx188/66tQ??@@@1uu	SHr   r   c                     |dk     rdS 	 t          |           dk    r| d         nd}n# t          $ r Y dS w xY wt          |t                    rdS t	          ||dz
            S )zQReturns True if first element of the incompatible
    array type is boolean.
    r   Nr   T)r   r   rg   _bool_scalar_types_first_element_bool)r   max_dimfirsts      r   r   r     s     {{tc((Q,,AD   tt%+,, tugai000s   ( 
66c                     t          | d          r| j        j        dk    r| S n%t          |           rt	          j        | d          S dS )ztReturns a boolean index array that can be converted to
    integer array. Returns None if no such array exists.
    rl   r   r?   r   N)hasattrr   r   r   r    rA   r   s    r   r   r     s[    
 sF /9>S  J ! 
S	!	! /|Cv....4r   c                     | j         dk    rt          d          t          j        | | j                  } t          j        |           d         S )Nr   zinvalid index shaper   r   )rl   rn   r    arrayr   wherer   s    r   r   r     sE    
x!||.///
*S	
*
*
*C:c??1r   )r   )r   )+r   r    r   cupyx.scipy.sparse._baser   r   	cupy.cudar   r   r4   scipy.sparserc   r`   ImportErrorr   integerint_rh   r?   bool_r   ElementwiseKernel_compress_getitem_kern_compress_getitem_complex_kernr   r&   r+   r0   r*   rP   _insert_many_populate_arraysrF   rZ   rU   objectr]   r   r   r   r   r   r   r   r   r   r   <module>r      s           / / / / / / - - - - - -             OO   OOO %-4 EK(  10~1)+ +  "9!8(* 2	"3 	"3   2  8 -U,9
 ,- - "  0  &K K K&  7u62 Xp 
=w[ N [ N [ N ~ ,E+-" *+   6 ./1 1 1 14 2%1+  1#2 2 (^+ ^+ ^+ ^+ ^+ ^+ ^+ ^+B  3 3 3l!K !K !KH  1 1 1 1      s   1 ;;