
    ^jO                         d Z dZg dZddlZddlmZ ddlmZm	Z	 ddl
mZmZmZmZmZ dd	lmZ dd
lmZ  G d de      Zd Z G d dee	      Z G d dee      Zy)z#Compressed Sparse Row matrix formatzrestructuredtext en)	csr_array
csr_matrixisspmatrix_csr    N   )spmatrix)_spbasesparray)	csr_tocsc	csr_tobsrcsr_count_blocksget_csr_submatrixcsr_sample_values)upcast)
_cs_matrixc                       e Zd ZdZdZddZej
                  j                  e_        ddZej                  j                  e_        ddZ	ej                  j                  e	_        d fd	Z
ej                  j                  e
_        ddZej                  j                  e_        ddZej                  j                  e_        e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 xZS )	_csr_basecsr)r      c                     ||dk7  rt        d      | j                  dk(  r|r| j                         S | S | j                  \  }}| j	                  | j
                  | j                  | j                  f||f|      S )N)r   r   zvSparse arrays/matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.r   shapecopy)
ValueErrorndimr   r   _csc_containerdataindicesindptr)selfaxesr   MNs        J/opt/ringagent/.cad-venv/lib/python3.12/site-packages/scipy/sparse/_csr.py	transposez_csr_base.transpose   s     L M M 99>"&499;0D0zz1""DIIt||$(KK$19:AT # K 	K    c                    | j                   dk7  rt        d      | j                  | j                  | j                        }| j                          | j                  | j                  | j                  }}}|j                  |j                  }}t        | j                  d         D ];  }||   }	||dz      }
||	|
 j                         ||<   ||	|
 j                         ||<   = |S )Nr   z.Cannot convert a 1d sparse array to lil formatdtyper   r   )r   r   _lil_containerr   r(   sum_duplicatesr   r   r   rowsrangetolist)r   r   lilptrinddatr+   r   nstartends              r#   tolilz_csr_base.tolil$   s    99>MNN!!$**DJJ!?kk$,,tyyCXXsxxdtzz!}% 	.AFEac(C%n++-DG%n++-DG		. 
r%   c                 *    |r| j                         S | S Nr   )r   r   s     r#   tocsrz_csr_base.tocsr7   s    99;Kr%   c                 J    t         |   |      }| j                  |_        |S )Nr8   )supertocoohas_canonical_format)r   r   A	__class__s      r#   r<   z_csr_base.tocoo?   s(    GMtM$ "&!:!:r%   c           
         | j                   dk7  rt        d      | j                  \  }}| j                  | j                  | j
                  ft        | j                  |            }t        j                  |dz   |      }t        j                  | j                  |      }t        j                  | j                  t        | j                              }t        ||| j                  j                  |d      | j
                  j                  |d      | j                  |||       | j                  |||f| j                        }d	|_        |S )
Nr   z.Cannot convert a 1d sparse array to csc formatmaxvalr   r'   Fr8   r   T)r   r   r   _get_index_dtyper   r   maxnnznpemptyr   r(   r
   astyper   r   has_sorted_indices)	r   r   r!   r"   	idx_dtyper   r   r   r>   s	            r#   tocscz_csr_base.tocscI   s   99>MNNzz1))4;;*E+.txx+; * =	!a%y1((48895xxtzz(:;!Q++$$YU$;,,%%ie%<))	 w 7tzzJ#r%   c                    | j                   dk7  rt        d      |ddlm} | j	                   ||             S |dk(  rR| j
                  j                  ddd      | j                  | j                  f}| j                  || j                  |      S |\  }}| j                  \  }}|dk  s|dk  s||z  d	k7  s||z  d	k7  rt        d
|       t        ||||| j                  | j                        }	| j                  | j                  | j                  ft        ||z  |	            }
t        j                  ||z  dz   |
      }t        j                  |	|
      }t        j                   |	||f| j"                        }t%        ||||| j                  j'                  |
d      | j                  j'                  |
d      | j
                  |||j)                         
       | j                  |||f| j                        S )Nr   z.Cannot convert a 1d sparse array to bsr formatr   )estimate_blocksize)	blocksize)r   r   r   r   zinvalid blocksize rA   r'   Fr8   rC   )r   r   _spfuncsrN   tobsrr   reshaper   r   _bsr_containerr   r   rD   rE   rG   rH   zerosr(   r   rI   ravel)r   rO   r   rN   arg1RCr!   r"   blksrK   r   r   r   s                 r#   rR   z_csr_base.tobsra   s   99>MNN4::(:4(@:AA%II%%b1-dll4;;GD&&t4::D&II CAa**CAa1uAQ!q1uz #5i[!ABB#Aa!DKKED--t{{DLL.I/21a4 . @IXXad1fI6Fhht95G88T!AJdjj9DaAqkk(((?ll)))%)@iigtzz|	5 &&w'tzz '  r%   c                     | S )zBswap the members of x if this is a column-oriented matrix
         xs    r#   _swapz_csr_base._swap   s	     r%   c              #     K   | j                   dk(  r| j                  j                  d      }d}t        | j                  | j
                        D ]%  \  }}t        ||z
        D ]  }|  | |dz   }' t        | j                  d   |z
        D ]  }|  y t        j                  d| j                  j                        }t        | t              r| j                  dd  nd| j                  d   f}d}| j                  dd  D ]C  }	|	|z
  |d<   | j                  ||	 }
| j
                  ||	 }| j                  ||
|f|d       |	}E y w)Nr   r   r   r'   Tr   )r   r(   typezipr   r   r,   r   rG   rU   r   
isinstancer	   r?   )r   zerouvd_r   r   i0i1r   r   s               r#   __iter__z_csr_base.__iter__   sM    99>::??1%DADLL$))4 1q1u AJE	
 4::a=1,- 
!4;;#4#45",T7";

12!TZZPQ]AS++ab/ 	BRF1Ill2b)G99R#D..$!8D.QQB	s   EEc                    | j                   dk(  r5|dvrt        d| d      | j                  d| j                  d   fd      S | j                  \  }}t	        |      }|dk  r||z  }|dk  s||k\  rt        d| d      t        ||| j                  | j                  | j                  ||dz   d|	      \  }}}| j                  |||fd|f| j                  d	      S )
z]Returns a copy of row i of the matrix, as a (1 x n)
        CSR matrix (row vector).
        r   )r   rP   index () out of ranger   Tr8   Fr   r(   r   )r   
IndexErrorrS   r   intr   r   r   r   r?   r(   r   ir!   r"   r   r   r   s          r#   _getrowz_csr_base._getrow   s     99> 71#^!<==<<DJJqM 2<>>zz1Fq5FAq5AFwqc899 1q$++t||TYY1q5!Q!H~~tWf5aV$(JJU  < 	<r%   c                 h   | j                   dk(  rt        d      | j                  \  }}t        |      }|dk  r||z  }|dk  s||k\  rt	        d| d      t        ||| j                  | j                  | j                  d|||dz   	      \  }}}| j                  |||f|df| j                  d      S )zLReturns a copy of column i. A (m x 1) sparse array (column vector).
        r   z4getcol not provided for 1d arrays. Use indexing A[j]r   rm   rn   Fro   )r   r   r   rq   rp   r   r   r   r   r?   r(   rr   s          r#   _getcolz_csr_base._getcol   s     99>STTzz1Fq5FAq5AFwqc899 1q$++t||TYY1aQ!H~~tWf5aV$(JJU  < 	<r%   c                     t        j                  | j                  |k(        }|j                  r| j                  |d      S | j                  j
                  j                  d      S Nr   )rG   flatnonzeror   sizer   r(   ra   )r   idxspots      r#   _get_intz_csr_base._get_int   sL    ~~dllc129999T!W%%yy##A&&r%   c                     |t        d       k(  r| j                         S |j                  dv r2| j                  d|d      }|j	                  |j
                  d         S | j                  |      S )Nr   Nr   Tr8   rP   )slicer   step_get_submatrixrS   r   _minor_slice)r   r{   rets      r#   
_get_slicez_csr_base._get_slice   se    %+99;88y %%a4%8C;;syy}--  %%r%   c                    | j                  | j                        }t        j                  ||      }|j                  dk(  r| j                  g | j                        S d| j                  d   }}t        j                  ||      }t        j                  ||      }t        j                  |j                  | j                        }t        ||| j                  | j                  | j                  |j                  |||	       |j                  d   dkD  r|j                  n|j                  d   f}| j                  |j                  |            S )Nr'   r   r   )rD   r   rG   asarrayrz   r?   r(   r   
zeros_likerH   r   r   r   rS   )	r   r{   rK   r!   r"   rowcolval	new_shapes	            r#   
_get_arrayz_csr_base._get_array   s    ))$,,7	jjI.88q=>>"DJJ>77$**Q-1mmCy1jjI.hhsxxtzz2!QT\\499((Cc	3 "%1!1CII		!	~~ckk)455r%   c                 B    | j                  |      j                  |      S r7   )rt   _minor_index_fancyr   r   r   s      r#   _get_intXarrayz_csr_base._get_intXarray   s    ||C 33C88r%   c                    |j                   dv r| j                  ||d      S | j                  \  }}|j                  |      \  }}}| j                  ||dz    \  }}	| j                  ||	 }
| j
                  ||	 }|dkD  r|
|k\  |
|k  z  }n|
|k  |
|kD  z  }t        |      dkD  r||
|z
  |z  dk(  z  }|
|   |z
  |z  }
||   }t        j                  dt        |
      g      }|dk  r|d d d   }t        |
d d d         }
dt        dt        t        j                  t        ||z
        |z                    f}| j                  ||
|f|| j                  d	      S )
Nr   Tr8   r   r   r   rP   Fro   )r   r   r   r   r   r   absrG   arraylenrE   rq   ceilfloatr?   r(   )r   r   r   r!   r"   r3   stopstrideiijjrow_indicesrow_datar0   
row_indptrr   s                  r#   _get_intXslicez_csr_base._get_intXslice   s   88y &&sCd&;; zz1!kk!ntVSQ'Bll2b)99R#A:%'K$,>?C%'K$,>?Cv;?K%'61Q66C"3'%/F:C=XXq#k"234
A:"~Hk$B$/0KC3rwwuTE\':V'CDEFG~~xjA$(JJU  < 	<r%   c                     |j                   dv r| j                  ||d      S | j                  |      j                  |      S )Nr   Tr8   minor)r   r   _major_slicer   s      r#   _get_sliceXintz_csr_base._get_sliceXint  sE    88y &&sCd&;;  %4434??r%   c                 B    | j                  |      j                  |      S r7   )r   r   r   s      r#   _get_sliceXarrayz_csr_base._get_sliceXarray  s      %88==r%   c                     | j                  |      j                  |      }|j                  dkD  r|j                  |j                        S |S )Nr   r   )_major_index_fancyr   r   rS   r   )r   r   r   ress       r#   _get_arrayXintz_csr_base._get_arrayXint  sC    %%c*999D88a<;;syy))
r%   c                     |j                   dvr@t        j                  |j                  | j                  d          }| j                  ||      S | j                  |      j                  |      S )Nr   r   r   )r   rG   aranger   r   _get_arrayXarrayr   r   r   s      r#   _get_arrayXslicez_csr_base._get_arrayXslice  s_    889$))S[[A78C((c22&&s+:::EEr%   c                 *    | j                  d||       y rx   )	_set_manyr   r{   r^   s      r#   _set_intz_csr_base._set_int!  s    q#q!r%   c                     t        j                  ||j                        }| j                  t        j                  |      ||       y r7   )rG   broadcast_tor   r   r   r   s      r#   
_set_arrayz_csr_base._set_array$  s/    OOAsyy)r}}S)32r%   )NF)F)NT)__name__
__module____qualname___format	_allow_ndr$   r   __doc__r5   r9   r<   rL   rR   staticmethodr_   rk   rt   rv   r}   r   r   r   r   r   r   r   r   r   r   __classcell__)r?   s   @r#   r   r      s    GI
K  ))11I" MM))EM MM))EM MM))EM, MM))EM"H MM))EM  
0<(< '&6 9<B@
>F"3r%   r   c                 "    t        | t              S )a  Is `x` of csr_matrix type?

    .. warning::

       SciPy sparse is shifting from a sparse matrix interface to a sparse
       array interface. In the next few releases we expect to deprecate the
       sparse matrix interface. For documentation of the matrix
       interface, see the :ref:`spmatrix interface docs <spmatrix_api>`.
       For guidance on converting existing code to sparse arrays, see
       :ref:`Migration from spmatrix to sparray <migration_to_sparray>`.

    Parameters
    ----------
    x
        object to check for being a csr matrix

    Returns
    -------
    bool
        True if `x` is a csr matrix, False otherwise

    Examples
    --------
    >>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
    >>> isspmatrix_csr(csr_matrix([[5]]))
    True
    >>> isspmatrix_csr(csr_array([[5]]))
    False
    >>> isspmatrix_csr(coo_matrix([[5]]))
    False
    )rc   r   r]   s    r#   r   r   )  s    @ a$$r%   c                       e Zd ZdZy)r   ab  
    Compressed Sparse Row array.

    This can be instantiated in several ways:
        csr_array(D)
            where D is a 2-D ndarray

        csr_array(S)
            with another sparse array or matrix S (equivalent to S.tocsr())

        csr_array((M, N), [dtype])
            to construct an empty array with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

        csr_array((data, (row_ind, col_ind)), [shape=(M, N)])
            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.

        csr_array((data, indices, indptr), [shape=(M, N)])
            is the standard CSR representation where the column indices for
            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
            If the shape parameter is not supplied, the array dimensions
            are inferred from the index arrays.

    Attributes
    ----------
    data : ndarray
        CSR format data array of the array
    indices : ndarray
        CSR format index array of the array
    indptr : ndarray
        CSR format index pointer array of the array
    has_sorted_indices : bool
        Whether indices are sorted
    has_canonical_format : bool
        Whether indices are sorted and no duplicate entries exist
    dtype : dtype
        Data type of the array
    shape : 2-tuple
        Shape of the array
    ndim : int
        Number of dimensions (this is always 2)
    format : str
        Three letter code for the format of the array storage, e.g. 'csr'
    nnz : int
        Number of values stored in the array
    size : int
        Number of values stored in the array
    T : csr_array
        The transpose of the array
    mT : csr_array
        The matrix transpose of the array

    Notes
    -----

    Sparse arrays can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    Advantages of the CSR format
      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
      - efficient row slicing
      - fast matrix vector products

    Disadvantages of the CSR format
      - slow column slicing operations (consider CSC)
      - changes to the sparsity structure are expensive (consider LIL or DOK)

    Canonical Format
        - Within each row, indices are sorted by column.
        - There are no duplicate entries.

    Examples
    --------

    >>> import numpy as np
    >>> from scipy.sparse import csr_array
    >>> csr_array((3, 4), dtype=np.int8).toarray()
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]], dtype=int8)

    >>> row = np.array([0, 0, 1, 2, 2, 2])
    >>> col = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6])
    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    >>> indptr = np.array([0, 2, 3, 6])
    >>> indices = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6])
    >>> csr_array((data, indices, indptr), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    Duplicate entries are summed together:

    >>> row = np.array([0, 1, 2, 0])
    >>> col = np.array([0, 1, 1, 0])
    >>> data = np.array([1, 2, 4, 8])
    >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
    array([[9, 0, 0],
           [0, 2, 0],
           [0, 4, 0]])

    As an example of how to construct a CSR array incrementally,
    the following snippet builds a term-document array from texts:

    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
    >>> indptr = [0]
    >>> indices = []
    >>> data = []
    >>> vocabulary = {}
    >>> for d in docs:
    ...     for term in d:
    ...         index = vocabulary.setdefault(term, len(vocabulary))
    ...         indices.append(index)
    ...         data.append(1)
    ...     indptr.append(len(indices))
    ...
    >>> csr_array((data, indices, indptr), dtype=int).toarray()
    array([[2, 1, 0, 0],
           [0, 1, 1, 1]])

    Nr   r   r   r   r\   r%   r#   r   r   M  s    @r%   r   c                       e Zd ZdZy)r   a4  
    Compressed Sparse Row matrix.

    .. warning::

       SciPy sparse is shifting from a sparse matrix interface to a sparse
       array interface. In the next few releases we expect to deprecate the
       sparse matrix interface. For documentation of the matrix
       interface, see the :ref:`spmatrix interface docs <spmatrix_api>`.
       For guidance on converting existing code to sparse arrays, see
       :ref:`Migration from spmatrix to sparray <migration_to_sparray>`.

    This can be instantiated in several ways:
        csr_matrix(D)
            where D is a 2-D ndarray

        csr_matrix(S)
            with another sparse array or matrix S (equivalent to S.tocsr())

        csr_matrix((M, N), [dtype])
            to construct an empty matrix with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

        csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
            where ``data``, ``row_ind`` and ``col_ind`` satisfy the
            relationship ``a[row_ind[k], col_ind[k]] = data[k]``.

        csr_matrix((data, indices, indptr), [shape=(M, N)])
            is the standard CSR representation where the column indices for
            row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
            corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
            If the shape parameter is not supplied, the matrix dimensions
            are inferred from the index arrays.

    Attributes
    ----------
    data : ndarray
        CSR format data array of the matrix
    indices : ndarray
        CSR format index array of the matrix
    indptr : ndarray
        CSR format index pointer array of the matrix
    has_sorted_indices : bool
        Whether indices are sorted
    has_canonical_format : bool
        Whether indices are sorted and no duplicate entries exist
    dtype : dtype
        Data type of the matrix
    shape : 2-tuple
        Shape of the matrix
    ndim : int
        Number of dimensions (this is always 2)
    format : str
        Three letter code for the format of the matrix storage, e.g. 'csr'
    nnz : int
        Number of values stored in the matrix
    size : int
        Number of values stored in the matrix
    T : csr_matrix
        The transpose of the matrix
    mT : csr_matrix
        The matrix transpose

    Notes
    -----

    Sparse matrices can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    Advantages of the CSR format
      - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
      - efficient row slicing
      - fast matrix vector products

    Disadvantages of the CSR format
      - slow column slicing operations (consider CSC)
      - changes to the sparsity structure are expensive (consider LIL or DOK)

    Canonical Format
        - Within each row, indices are sorted by column.
        - There are no duplicate entries.

    Examples
    --------

    >>> import numpy as np
    >>> from scipy.sparse import csr_matrix
    >>> csr_matrix((3, 4), dtype=np.int8).toarray()
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]], dtype=int8)

    >>> row = np.array([0, 0, 1, 2, 2, 2])
    >>> col = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6])
    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    >>> indptr = np.array([0, 2, 3, 6])
    >>> indices = np.array([0, 2, 2, 0, 1, 2])
    >>> data = np.array([1, 2, 3, 4, 5, 6])
    >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
    array([[1, 0, 2],
           [0, 0, 3],
           [4, 5, 6]])

    Duplicate entries are summed together:

    >>> row = np.array([0, 1, 2, 0])
    >>> col = np.array([0, 1, 1, 0])
    >>> data = np.array([1, 2, 4, 8])
    >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
    array([[9, 0, 0],
           [0, 2, 0],
           [0, 4, 0]])

    As an example of how to construct a CSR matrix incrementally,
    the following snippet builds a term-document matrix from texts:

    >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
    >>> indptr = [0]
    >>> indices = []
    >>> data = []
    >>> vocabulary = {}
    >>> for d in docs:
    ...     for term in d:
    ...         index = vocabulary.setdefault(term, len(vocabulary))
    ...         indices.append(index)
    ...         data.append(1)
    ...     indptr.append(len(indices))
    ...
    >>> csr_matrix((data, indices, indptr), dtype=int).toarray()
    array([[2, 1, 0, 0],
           [0, 1, 1, 1]])

    Nr   r\   r%   r#   r   r     s    Ir%   r   )r   __docformat____all__numpyrG   _matrixr   _baser   r	   _sparsetoolsr
   r   r   r   r   _sputilsr   _compressedr   r   r   r   r   r\   r%   r#   <module>r      sc    )%
7   #A A  #T3
 T3n %HA	7 AHJ9 Jr%   