a
    aa-                     @   st   d Z dZddgZddlZddlmZ ddlmZm	Z	m
Z
mZ dd	lmZmZ dd
lmZ G dd deZdd ZdS )z#Compressed Sparse Row matrix formatzrestructuredtext en
csr_matrixisspmatrix_csr    N   )spmatrix)	csr_tocsc	csr_tobsrcsr_count_blocksget_csr_submatrix)upcastget_index_dtype)
_cs_matrixc                   @   s   e Zd ZdZdZd$ddZejje_d%ddZejje_d&d	d
Zejje_d'ddZ	ej	je	_d(ddZ
ej
je
_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 d! Zd"d# ZdS ))r   a|  
    Compressed Sparse Row matrix

    This can be instantiated in several ways:
        csr_matrix(D)
            with a dense matrix or rank-2 ndarray D

        csr_matrix(S)
            with another sparse 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
    ----------
    dtype : dtype
        Data type of the matrix
    shape : 2-tuple
        Shape of the matrix
    ndim : int
        Number of dimensions (this is always 2)
    nnz
        Number of stored values, including explicit zeros
    data
        CSR format data array of the matrix
    indices
        CSR format index array of the matrix
    indptr
        CSR format index pointer array of the matrix
    has_sorted_indices
        Whether indices are sorted

    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)

    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]])

    ZcsrNFc                 C   sD   |d urt d| j\}}ddlm} || j| j| jf||f|dS )NzoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.r   
csc_matrixshapecopy)
ValueErrorr   cscr   dataindicesindptr)selfZaxesr   MNr    r   `/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/scipy/sparse/csr.py	transpose   s    

zcsr_matrix.transposec                 C   s   ddl m} || j| jd}|   | j| j| j  }}}|j|j }}t	| jd D ]@}	||	 }
||	d  }||
| 
 ||	< ||
| 
 ||	< qV|S )Nr   )
lil_matrixdtyper   )lilr   r   r   Zsum_duplicatesr   r   r   rowsrangetolist)r   r   r   r    ptrindZdatr!   r   nstartendr   r   r   tolil   s    zcsr_matrix.tolilc                 C   s   |r|   S | S d S Nr   )r   r   r   r   r   tocsr   s    zcsr_matrix.tocsrc              	   C   s   t | j| jft| j| jd d}tj| jd d |d}tj| j|d}tj| jt| j	d}t
| jd | jd | j|| j|| j||| ddlm} ||||f| jd}d|_|S )Nr   maxvalr   r   r   r   T)r   r   r   maxZnnzr   npemptyr
   r   r   astyper   r   r   Zhas_sorted_indices)r   r   	idx_dtyper   r   r   r   Ar   r   r   tocsc   s$    

zcsr_matrix.tocscTc                 C   s^  ddl m} |d u r0ddlm} | j|| dS |dkrb| jddd| j| jf}||| j	|dS |\}}| j	\}}	|dk s|dk s|| dks|	| dkrt
d	| t||	||| j| j}
t| j| jft|	| |
d
}tj|| d |d}tj|
|d}tj|
||f| jd}t||	||| j|| j|| j||| 
 ||||f| j	dS d S )Nr   )
bsr_matrix)estimate_blocksize)	blocksize)r   r   r   r   zinvalid blocksize %sr-   r   r/   )Zbsrr7   Zspfuncsr8   tobsrr   Zreshaper   r   r   r   r   r   r0   r1   r2   zerosr   r   r3   Zravel)r   r9   r   r7   r8   Zarg1RCr   r   Zblksr4   r   r   r   r   r   r   r;      s2    
(



zcsr_matrix.tobsrc                 C   s   |S )zBswap the members of x if this is a column-oriented matrix
        r   )r   xr   r   r   _swap   s    zcsr_matrix._swapc                 c   s~   t jd| jjd}d| jd f}d}| jdd  D ]F}|| |d< | j|| }| j|| }t|||f|ddV  |}q2d S )N   r   r   r   Tr   )r1   r<   r   r   r   r   r   r   )r   r   r   Zi0i1r   r   r   r   r   __iter__   s    zcsr_matrix.__iter__c              
   C   s   | j \}}t|}|dk r"||7 }|dk s2||kr>td| t||| j| j| j||d d|	\}}}t|||fd|f| jddS )z]Returns a copy of row i of the matrix, as a (1 x n)
        CSR matrix (row vector).
        r   index (%d) out of ranger   Fr   r   r   	r   int
IndexErrorr	   r   r   r   r   r   r   ir   r   r   r   r   r   r   r   getrow   s    

zcsr_matrix.getrowc                 C   s   | j \}}t|}|dk r"||7 }|dk s2||kr>td| t||| j| j| jd|||d 	\}}}t|||f|df| jddS )zcReturns a copy of column i of the matrix, as a (m x 1)
        CSR matrix (column vector).
        r   rD   r   FrE   rF   rI   r   r   r   getcol
  s    

zcsr_matrix.getcolc                 C   s   |  ||S r*   )rK   _minor_index_fancyr   rowcolr   r   r   _get_intXarray  s    zcsr_matrix._get_intXarrayc              	   C   s@  |j dv r| j||ddS | j\}}||\}}}| j||d  \}}	| j||	 }
| j||	 }|dkr|
|k|
|k @ }n|
|k|
|k@ }t|dkr||
| | dkM }|
| | | }
|| }tdt	|
g}|dk r|d d d }t|
d d d }
dt
dttt|| | f}t||
|f|| jdd	S )
Nr   NTr+   rA   r   r   r:   FrE   )step_get_submatrixr   r   r   r   absr1   arraylenr0   rG   ceilfloatr   r   )r   rO   rP   r   r   r'   stopZstrideiiZjjZrow_indicesZrow_datar%   Z
row_indptrr   r   r   r   _get_intXslice  s,    


$zcsr_matrix._get_intXslicec                 C   s,   |j dv r| j||ddS | |j|dS )NrR   Tr+   minor)rS   rT   _major_slicerN   r   r   r   _get_sliceXint=  s    
zcsr_matrix._get_sliceXintc                 C   s   |  ||S r*   )r_   rM   rN   r   r   r   _get_sliceXarrayB  s    zcsr_matrix._get_sliceXarrayc                 C   s   |  |j|dS )Nr]   )_major_index_fancyrT   rN   r   r   r   _get_arrayXintE  s    zcsr_matrix._get_arrayXintc                 C   s>   |j dvr,tj|| jd  }| ||S | |j|dS )NrR   r   r]   )rS   r1   Zaranger   r   Z_get_arrayXarrayrb   rT   rN   r   r   r   _get_arrayXsliceH  s    
zcsr_matrix._get_arrayXslice)NF)F)F)F)NT)__name__
__module____qualname____doc__formatr   r   r)   r,   r6   r;   r@   rC   rK   rL   rQ   r\   r`   ra   rc   rd   r   r   r   r   r      s,   s








"
!c                 C   s
   t | tS )a  Is x of csr_matrix type?

    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_matrix, isspmatrix_csr
    >>> isspmatrix_csr(csr_matrix([[5]]))
    True

    >>> from scipy.sparse import csc_matrix, csr_matrix, isspmatrix_csc
    >>> isspmatrix_csr(csc_matrix([[5]]))
    False
    )
isinstancer   )r?   r   r   r   r   O  s    )rh   Z__docformat____all__Znumpyr1   baser   Z_sparsetoolsr   r   r   r	   Zsputilsr
   r   
compressedr   r   r   r   r   r   r   <module>   s     @