
    `ikO                         d dl Z 	 d dlZdZn# e$ r dZY nw xY w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mZ d d
lmZ  G d dej                  Zd ZdS )    NTF)_core)_base)_csc)_csr)_data)_util)_sputilsc                       e Zd ZdZdZ ej        dddd          Zdd	ZddZ	ddZ
ddZd Zd ZddZddZdddZd Zd dZd!dZd!dZd!dZd"dZdS )#
coo_matrixaR  COOrdinate format sparse matrix.

    This can be instantiated in several ways.

    ``coo_matrix(D)``
        ``D`` is a rank-2 :class:`cupy.ndarray`.

    ``coo_matrix(S)``
        ``S`` is another sparse matrix. It is equivalent to ``S.tocoo()``.

    ``coo_matrix((M, N), [dtype])``
        It constructs an empty matrix whose shape is ``(M, N)``. Default dtype
        is float64.

    ``coo_matrix((data, (row, col)))``
        All ``data``, ``row`` and ``col`` are one-dimenaional
        :class:`cupy.ndarray`.

    Args:
        arg1: Arguments for the initializer.
        shape (tuple): Shape of a matrix. Its length must be two.
        dtype: Data type. It must be an argument of :class:`numpy.dtype`.
        copy (bool): If ``True``, copies of given data are always used.

    .. seealso::
       :class:`scipy.sparse.coo_matrix`

    coozraw T row, raw T colzT diffz
        T diff_out = 1;
        if (i == 0 || row[i - 1] == row[i] && col[i - 1] == col[i]) {
          diff_out = 0;
        }
        diff = diff_out;
        *cupyx_scipy_sparse_coo_sum_duplicates_diffNFc                 n   |"t          |          dk    rt          d          t          j        |          rX|                    | j                  }|j        }|j        }|j        }|j        | j        k    rd}||j	        }|j
        | _
        nt          j        |          rw|\  }	}
t          |	          t          |
          }
}	t          j        d|r|nd          }t          j        dd          }t          j        dd          }|	|
f}d}d| _
        n2t           rt"          j                            |          r||                                }t          j        |j                  }t          j        |j        d          }t          j        |j        d          }d}||j	        }|j
        | _
        nt+          |t,                    rt          |          dk    r	 |\  }\  }}n$# t.          t          f$ r t/          d	          w xY wt          j        |          rI|j        d
k    r>t          j        |          r*|j        d
k    rt          j        |          r|j        d
k    st          d          t          |          t          |          cxk    rt          |          k    sn t          d          d| _
        nt          j        |          r^|j        dk    rt/          d          t          j        |          }|                                \  }}|||f         }|j	        }d| _
        nt/          d	          ||j        }nt;          j        |          }|t:          j        t:          j        t:          j         t:          j!        t:          j"        fvrt          d          |#                    ||          }|#                    d|          }|#                    d|          }|}t          |          dk    st          |          dk    rt          d          t          |$                                          d
z   t          |$                                          d
z   f}t          |          dk    r|$                                |d         k    rt          d          |$                                |d
         k    rt          d          |%                                dk     rt          d          |%                                dk     rt          d          tL          j'        (                    | |           || _        || _        t          j        |          st          d          t          |d                   t          |d
                   f| _)        d S )N   z1Only two-dimensional sparse arrays are supported.Fr   didtypeTzinvalid input format   z(row, column, and data arrays must be 1-Dz7row, column, and data array must all be the same lengthz'expected dimension <= 2 array or matrixzCOnly bool, float32, float64, complex64 and complex128 are supportedcopyz4cannot infer dimensions from zero sized index arraysz#row index exceeds matrix dimensionsz&column index exceeds matrix dimensionsznegative row index foundznegative column index foundz(invalid shape (must be a 2-tuple of int))*len
ValueErrorr   issparseasformatformatdatarowcolshapehas_canonical_formatr   isshapeintcupyzeros_scipy_availablescipysparsetocooarray
isinstancetuple	TypeErrorisdensendim
atleast_2dnonzeror   numpybool_float32float64	complex64
complex128astypemaxminsparse_data_data_matrix__init___shape)selfarg1r   r   r   xr   r   r   mndenses               k/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/sparse/_coo.pyr<   zcoo_matrix.__init__>   sY   UqCE E E >$ B	4dk**A6D%C%C{dk))}
()(>D%%]4   3	4DAqq663q66qA:a%!8S99D*Qc***C*Qc***CFED(,D%% '	4%,"7"7"="= '	4

A:af%%D*QU#...C*QU#...CD}
()(>D%%e$$ 	4Ta8#' jsCCz* 8 8 8 67778 M$'' MDINNM#&& -;+.8q==M#&& ,9+.8q== !KLLLIIS5555SXX5555 MO O O ).D%%]4   	4y1}} IJJJOD))E}}HCc?DKE(,D%% 2333=JEEK&&EemU]%*:< < <!" " " {{5t{,,jj4j((jj4j((=3xx1}}CA JL L L^^a'SWWYY!);<Et99q==wwyyE!H$$ !FGGGwwyyE!H$$ !IJJJwwyy1}} !;<<<wwyy1}} !>??? ))$555}U## 	IGHHH%(mmSq]]2s   'G0 0!HTc                     |rNt          || j                                        | j                                        ff| j        |j                  S t          || j        | j        ff| j        |j                  S )zReturns a matrix with the same sparsity structure as self,
        but with different data.  By default the index arrays
        (i.e. .row and .col) are copied.
        )r   r   )r   r   r   r   r   r   )r>   r   r   s      rD   
_with_datazcoo_matrix._with_data   s    
  	"9:j
4 4 4 4 $(+,DJj" " " "    r   c           
      Z   | j         \  }}|| k    s||k    r t          j        d| j        j                  S t          j        t          |t          |d          z   |t          |d          z
            | j                  }| j        |z   | j	        k    }| j
        r| j        |         }| j        |         }n]t          | j        |         | j        |         | j	        |         ff| j                   }|                                 |j        }|j        }|||t          |d          z   <   |S )a  Returns the k-th diagonal of the matrix.

        Args:
            k (int, optional): Which diagonal to get, corresponding to elements
            a[i, i+k]. Default: 0 (the main diagonal).

        Returns:
            cupy.ndarray : The k-th diagonal.
        r   r   r   )r   r#   emptyr   r   r$   r9   r8   r   r   r    r   sum_duplicates)	r>   krowscolsdiag	diag_maskr   r   diag_coos	            rD   diagonalzcoo_matrix.diagonal   s.    Z
d::d:aty7777z#dSAYY.s1ayy0@AA $
, , ,X\dh.	$ 		!(9%C9Y'DD!49Y#7$(HY$7)9L#M#O(,
4 4 4H ##%%%,C=D $S3q!99_rG   c                 L   | j         \  }}|dk    r||k    s|dk     r| |k    rt          d          |j        rt          |          sdS | j        j        }| j        | j        z
  |k    }|dk     rt          ||z   |          }|j        rt          |t          |                    }t          j	        || j        |k              }t          j
        | | |z   |          }	t          j
        ||          }
nt          |||z
            }|j        rt          |t          |                    }t          j	        || j        |k              }t          j
        ||          }	t          j
        |||z   |          }
|j        r|d|         }nt          j        ||| j                  }t          j        | j        |         |	f          | _        t          j        | j        |         |
f          | _        t          j        | j        |         |f          | _        d| _        dS )ar  Set diagonal or off-diagonal elements of the array.

        Args:
            values (ndarray): New values of the diagonal elements. Values may
                have any length. If the diagonal is longer than values, then
                the remaining diagonal entries will not be set. If values are
                longer than the diagonal, then the remaining values are
                ignored. If a scalar value is given, all of the diagonal is set
                to it.
            k (int, optional): Which off-diagonal to set, corresponding to
                elements a[i,i+k]. Default: 0 (the main diagonal).

        r   zk exceeds matrix dimensionsNr   F)r   r   r.   r   r   r   r   r9   r#   
logical_orarangefullconcatenater   r    )r>   valuesrL   MN	idx_dtype	full_keep	max_indexkeepnew_rownew_colnew_datas               rD   setdiagzcoo_matrix.setdiag   s    z1EEa1ff!a%%QB!GG:;;;; 	s6{{ 	FHN	 Htx'1,	q55AE1I{ 8	3v;;77	?9dh).CDDDk1"qb9nIFFFGk)9===GGAq1uI{ 8	3v;;77	?9dh).CDDDk)9===Gk!Q])DDDG ; 	Fjyj)HHyF$*EEEH #TXd^W$=>>#TXd^W$=>>$diox%@AA	$)!!!rG   c                     | j         dk    }| j         |         | _         | j        |         | _        | j        |         | _        dS )zRemoves zero entories in place.r   N)r   r   r   )r>   inds     rD   eliminate_zeroszcoo_matrix.eliminate_zeros  s8    i1nIcN	8C=8C=rG   c                     | j         S )zcReturns the shape of the matrix.

        Returns:
            tuple: Shape of the matrix.
        )r=   )r>   s    rD   	get_shapezcoo_matrix.get_shape  s     {rG   c                 ,    || j         j        S t          )z>Returns the number of stored values, including explicit zeros.)r   sizer   )r>   axiss     rD   getnnzzcoo_matrix.getnnz  s    <9>!rG   c                    t           st          d          | j                            |          }| j                            |          }| j                            |          }t          j                            |||ff| j	                  S )a:  Returns a copy of the array on host memory.

        Args:
            stream (cupy.cuda.Stream): CUDA stream object. If it is given, the
                copy runs asynchronously. Otherwise, the copy is synchronous.

        Returns:
            scipy.sparse.coo_matrix: Copy of the array on host memory.

        zscipy is not availablerI   )
r%   RuntimeErrorr   getr   r   r&   r'   r   r   )r>   streamr   r   r   s        rD   rn   zcoo_matrix.get"  s       	97888y}}V$$hll6""hll6""|&&C:dj ' 2 2 	2rG   C)orderc                   t          j        || j                  }|| j        k    r| S | j        \  }}|dk    r{t          j        |t	          d|dz
            z  t	          d|dz
            z             }t          j        || j        |          | j        z   }t          ||d                   \  }}n|dk    r{t          j        |t	          d|dz
            z  t	          d|dz
            z             }t          j        || j        |          | j        z   }t          ||d                   \  }}nt          d          | j        }	t          |	||ff|d	          S )
a5  Gives a new shape to a sparse matrix without changing its data.

        Args:
            shape (tuple):
                The new shape should be compatible with the original shape.
            order: {'C', 'F'} (optional)
                Read the elements using this index order. 'C' means to read and
                write the elements using C-like index order. 'F' means to read
                and write the elements using Fortran-like index order. Default:
                C.

        Returns:
            cupyx.scipy.sparse.coo_matrix: sparse matrix

        rp   r   r   )maxvalr   Fz'order' must be 'C' or 'F'Fr   r   )r	   check_shaper   get_index_dtyper8   r#   multiplyr   r   divmodr   r   r   )
r>   rq   r   nrowsncolsr   flat_indicesr_   r`   ra   s
             rD   reshapezcoo_matrix.reshape6  s   " $UDJ77DJKzuC<<,Auqy 1 11C5194E4EEH H HE=/46 6 68<AL%lE!H==GWWc\\,Auqy 1 11C5194E4EEH H HE=/46 6 68<AL%lE!H==GWW9:::98gw%78$& & & 	&rG   c                    | j         rdS t          j        | j        | j        g          }t          j        |          }| j        |         }| j        |         }| j        |         }|                     ||| j        j                  }|dd         	                                r|}|}|}	nCt          j
        |d          }
t          |
d                   dz   }t          j        || j        j                  }t          j        |d          }t          j        |d          }	| j        j        j        dk    r' t          j        dd	d
d          ||||
|||	           n| j        j        j        dk    r' t          j        dd	dd          ||||
|||	           nQ| j        j        j        dk    r< t          j        dddd          |j        |j        |||
|j        |j        ||		  	         || _        || _        |	| _        d| _         dS )af  Eliminate duplicate matrix entries by adding them together.

        .. warning::
            When sorting the indices, CuPy follows the convention of cuSPARSE,
            which is different from that of SciPy. Therefore, the order of the
            output indices may differ:

            .. code-block:: python

                >>> #     1 0 0
                >>> # A = 1 1 0
                >>> #     1 1 1
                >>> data = cupy.array([1, 1, 1, 1, 1, 1], 'f')
                >>> row = cupy.array([0, 1, 1, 2, 2, 2], 'i')
                >>> col = cupy.array([0, 0, 1, 0, 1, 2], 'i')
                >>> A = cupyx.scipy.sparse.coo_matrix((data, (row, col)),
                ...                                   shape=(3, 3))
                >>> a = A.get()
                >>> A.sum_duplicates()
                >>> a.sum_duplicates()  # a is scipy.sparse.coo_matrix
                >>> A.row
                array([0, 1, 1, 2, 2, 2], dtype=int32)
                >>> a.row
                array([0, 1, 2, 1, 2, 2], dtype=int32)
                >>> A.col
                array([0, 0, 1, 0, 1, 2], dtype=int32)
                >>> a.col
                array([0, 0, 0, 1, 1, 2], dtype=int32)

        .. warning::
            Calling this function might synchronize the device.

        .. seealso::
           :meth:`scipy.sparse.coo_matrix.sum_duplicates`

        N)ri   r   r   r   bz5T src_data, int32 src_row, int32 src_col, int32 indexz(raw T data, raw int32 row, raw int32 colz
                    if (src_data) data[index] = true;
                    row[index] = src_row;
                    col[index] = src_col;
                    ,cupyx_scipy_sparse_coo_sum_duplicates_assignfz
                    atomicAdd(&data[index], src_data);
                    row[index] = src_row;
                    col[index] = src_col;
                    czAT src_real, T src_imag, int32 src_row, int32 src_col, int32 indexz4raw T real, raw T imag, raw int32 row, raw int32 colz
                    atomicAdd(&real[index], src_real);
                    atomicAdd(&imag[index], src_imag);
                    row[index] = src_row;
                    col[index] = src_col;
                    4cupyx_scipy_sparse_coo_sum_duplicates_assign_complexT)r    r#   stackr   r   lexsortr   _sum_duplicates_diffri   allcumsumr"   r$   r   rJ   kindElementwiseKernelrealimag)r>   keysrq   src_datasrc_rowsrc_coldiffr   r   r   indexri   s               rD   rK   zcoo_matrix.sum_duplicatesb  s`   J $ 	F z48TX.//T""9U#(5/(5/(('(NN8<<>> /	2DCCC KC000EuRy>>A%D:d$)/:::D*T---C*T---Cy#s**	&K>
 C	 	 GWeT3	E 	E 	E 	E %,,	&K>
 C	 	 GWeT3	E 	E 	E 	E %,,&"J K  -%)TYS2 2 2 	$(!!!rG   c                 T    |                                                      ||          S )a'  Returns a dense matrix representing the same value.

        Args:
            order (str): Not supported.
            out: Not supported.

        Returns:
            cupy.ndarray: Dense array representing the same value.

        .. seealso:: :meth:`scipy.sparse.coo_matrix.toarray`

        )rq   out)tocsrtoarray)r>   rq   r   s      rD   r   zcoo_matrix.toarray  s%     zz||##%S#999rG   c                 2    |r|                                  S | S )zConverts the matrix to COOrdinate format.

        Args:
            copy (bool): If ``False``, it shares data arrays as much as
                possible.

        Returns:
            cupyx.scipy.sparse.coo_matrix: Converted matrix.

        r   )r>   r   s     rD   r(   zcoo_matrix.tocoo  s      	99;;KrG   c                    ddl m} | j        dk    r t          j        | j        | j                  S |                                 }|                                 |	                    |d           |
                    |          }d|_        |S )a{  Converts the matrix to Compressed Sparse Column format.

        Args:
            copy (bool): If ``False``, it shares data arrays as much as
                possible. Actually this option is ignored because all
                arrays in a matrix cannot be shared in coo to csc conversion.

        Returns:
            cupyx.scipy.sparse.csc_matrix: Converted matrix.

        r   cusparser   r   T)cupyxr   nnzr   
csc_matrixr   r   r   rK   coosortcoo2cscr    r>   r   r   r@   s       rD   tocsczcoo_matrix.tocsc       	#"""""8q==?4:TZ@@@@ IIKK	C   Q!%rG   c                    ddl m} | j        dk    r t          j        | j        | j                  S |                                 }|                                 |	                    |d           |
                    |          }d|_        |S )ax  Converts the matrix to Compressed Sparse Row format.

        Args:
            copy (bool): If ``False``, it shares data arrays as much as
                possible. Actually this option is ignored because all
                arrays in a matrix cannot be shared in coo to csr conversion.

        Returns:
            cupyx.scipy.sparse.csr_matrix: Converted matrix.

        r   r   r   rT)r   r   r   r   
csr_matrixr   r   r   rK   r   coo2csrr    r   s       rD   r   zcoo_matrix.tocsr  r   rG   c                     |t          d          | j        d         | j        d         f}t          | j        | j        | j        ff||          S )a?  Returns a transpose matrix.

        Args:
            axes: This option is not supported.
            copy (bool): If ``True``, a returned matrix shares no data.
                Otherwise, it shared data arrays as much as possible.

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

        NzoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.r   r   ru   )r   r   r   r   r   r   )r>   axesr   r   s       rD   	transposezcoo_matrix.transpose  so     GH H H 
1tz!},Y48,-UG G G 	GrG   )NNF)T)r   )N)NN)F)NF)__name__
__module____qualname____doc__r   r   r   r   r<   rF   rR   rb   re   rg   rk   rn   r}   rK   r   r(   r   r   r    rG   rD   r   r      s        : F252	 :	; 	;m3 m3 m3 m3^" " " "   >0* 0* 0* 0*d! ! !     2 2 2 2( %( *& *& *& *& *&Xg) g) g)R: : : :       2   2G G G G G GrG   r   c                 ,    t          | t                    S )zChecks if a given matrix is of COO format.

    Returns:
        bool: Returns if ``x`` is :class:`cupyx.scipy.sparse.coo_matrix`.

    )r*   r   )r@   s    rD   isspmatrix_coor   1  s     a$$$rG   )r1   scipy.sparser&   r%   ImportErrorr#   r   cupyx.scipy.sparser   r   r   r   r:   r   r	   r;   r   r   r   rG   rD   <module>r      s/              $ $ $ $ $ $ # # # # # # # # # # # # 3 3 3 3 3 3 $ $ $ $ $ $ ' ' ' ' ' '\G \G \G \G \G) \G \G \G~% % % % %s    