B
    &]\p@                 @   s   d Z ddlmZmZmZ dZddgZddlZddl	m
Z
 dd	lmZ dd
lmZmZmZmZmZ ddlmZmZmZmZmZmZ ddlmZ G dd deeZdd ZdS )z#Compressed Sparse Row matrix format    )divisionprint_functionabsolute_importzrestructuredtext en
csr_matrixisspmatrix_csrN)xrange   )spmatrix)	csr_tocsc	csr_tobsrcsr_count_blocksget_csr_submatrixcsr_sample_values)upcast	isintlike
IndexMixin
issequenceget_index_dtypeismatrix)
_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S )#r   aF  
    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 nonzero elements
    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]])

    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 k	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!   /lib/python3.7/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 }}xRt	| jd D ]@}	||	 }
||	d  }||
| 
 ||	< ||
| 
 ||	< qXW |S )Nr   )
lil_matrix)dtyper   )lilr$   r   r%   Zsum_duplicatesr   r   r   rowsr   tolist)r   r   r$   r&   Z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 k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   r   zinvalid blocksize %s)r/   )r%   )r   )Zbsrr7   Zspfuncsr8   tobsrr   reshaper   r   r   r   r   r   r0   r1   r2   zerosr%   r   r3   ravel)r   r9   r   r7   r8   Zarg1RCr   r    Zblksr4   r   r   r   r!   r!   r"   r;      s.    
(


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          
      s  dd  dd  fdd} |\}}t|rt|rJ||S t|tr`||S t|r||jd j}|d d f | S nnt|tr&t|r|j	dkst|tr|j	dkr|j	dkrڈ
||S t|r ||jd j}}|td d d kr||d d f }|| S nt|rt|sFt|tr ||jd	 }| }|td d d krt|S |d d |f S nzt|r t|r t|d	 dkr t|d	 d	 r  |}||d d d	f jd	 }||jd j}	| |	 S t|rt|s$||\}} |} |}|j|jkrJtd
|jdksZtt|}
|
d	krtt|jjdS |jd	  |jd  tj|
jd}tjd	 jd jjj|
| | |	 |jdkrt|S ||jS )Nc             S   sV   y0t | } t| fdd}|| jkr.| |} W n tk
rL   tdY nX | S d S )NT)Zcheck_contentszinvalid index)r1   Zasarrayr   r%   r3   	Exception
IndexError)rA   r4   r!   r!   r"   	asindices   s    

z)csr_matrix.__getitem__.<locals>.asindicesc             S   sT   | j dkrdS |  }||kr*td| |  }|| k rLtd||  ||fS )Nr   )r   r   zindex (%d) out of range)sizer0   rD   min)r   r    max_indxmin_indxr!   r!   r"   check_bounds   s    

z,csr_matrix.__getitem__.<locals>.check_boundsc                s    |   } | |\}}|dk r6| | dk   |7  < tjt| d | jd}tjt| jd}t| |f}t|| |f|jddS )zoReturn a sparse matrix P so that P*self implements
            slicing of the form self[[1,2,3],:]
            r   r   )r%   F)r   r%   r   )r   r1   Zarangelenr%   Zonesr   )r   r    rI   rH   r   r   r   )rE   rJ   r   r!   r"   	extractor  s    z)csr_matrix.__getitem__.<locals>.extractorr   )r   Nr   z'number of row and column indices differ   )r%   )Z_unpack_indexr   Z_get_single_element
isinstanceslice_get_row_slicer   r   Tstep_get_submatrixr   rK   Z_index_to_arraysrD   ndimAssertionErrorr1   rF   r   Z
atleast_2dr%   r2   r   r   r   r   r>   Zasmatrix	__class__r<   )r   keyrL   rowcolPZslicedZ	extractedZP_rowZP_colZnum_samplesvalr!   )rE   rJ   r   r"   __getitem__   sp    






$


zcsr_matrix.__getitem__c             c   s   t jd| jjd}d| jd f}d}xX| jdd  D ]F}|| |d< | j|| }| j|| }t|||f|ddV  |}q4W d S )NrM   )r%   r   r   T)r   r   )r1   r=   r   r%   r   r   r   r   )r   r   r   i0i1r   r   r!   r!   r"   __iter__d  s    zcsr_matrix.__iter__c             C   s   | j \}}t|}|dk r"||7 }|dk s2||kr>td| t| j||d   }| j|  }| j|  }tj	dt
|g| jj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   zindex (%d) out of rangerM   )r%   r   F)r   r%   r   )r   intrD   rO   r   r   r   r   r1   arrayrK   r%   r   )r   ir   r    idxr   r   r   r!   r!   r"   getrowo  s    
zcsr_matrix.getrowc             C   s   |  td|S )zcReturns a copy of column i of the matrix, as a (m x 1)
        CSR matrix (column vector).
        N)rS   rO   )r   rb   r!   r!   r"   getcol  s    zcsr_matrix.getcolc          
   C   s  | j \}}|dk r||7 }|dk s*||kr6td| ||\}}}|dkrxt||| j| j| j||d ||	\}}	}
n| j| j| | j|d   }	| j| j| | j|d   }
|dkr|	|k|	|k @ }n|	|k|	|k@ }t|dkr||	| | dkM }|	| | | }	|
| }
tdt	|	g}|dk rR|
ddd }
t|	ddd }	dt
tt|| | f}t|
|	|f|| jddS )z.Returns a copy of row self[i, cslice]
        r   zindex (%d) out of ranger   Nr:   F)r   r%   r   )r   rD   r   r   r   r   absr1   ra   rK   r`   Zceilfloatr   r%   )r   rb   Zcslicer   r    r+   stopstrideZ
row_indptrZrow_indicesZrow_datar)   r   r!   r!   r"   rP     s4    

zcsr_matrix._get_row_slicec          
   C   s|   dd }| j \}}|||\}}|||\}}	t||| j| j| j||||		\}
}}|| |	| f}| j|||
f|| jddS )z:Return a submatrix of this matrix (new matrix is created).c             S   s   t | tr,| |\}}}|dkr\tdn0t| rT| dk rD| |7 } | | d  }}ntdd|  krp|krn n d|  kr|krn n||kstd||||||f ||fS )Nr   z$slicing with step != 1 not supportedr   zexpected slice or scalarz;index out of bounds: 0 <= %d <= %d, 0 <= %d <= %d, %d <= %d)rN   rO   r   r   r   	TypeErrorrD   )ZslZnumr]   r^   ri   r!   r!   r"   process_slice  s    

8z0csr_matrix._get_submatrix.<locals>.process_sliceF)r   r%   r   )r   r   r   r   r   rV   r%   )r   Z	row_sliceZ	col_slicerk   r   r    r]   r^   Zj0Zj1r   r   r   r   r!   r!   r"   rS     s    
"zcsr_matrix._get_submatrix)NF)F)F)F)NT)__name__
__module____qualname____doc__formatr#   r	   r-   r.   r6   r;   rB   r\   r_   rd   re   rP   rS   r!   r!   r!   r"   r      s&   i








"
x+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
    )rN   r   )rA   r!   r!   r"   r     s    )ro   Z
__future__r   r   r   Z__docformat____all__Znumpyr1   Zscipy._lib.sixr   baser	   Z_sparsetoolsr
   r   r   r   r   Zsputilsr   r   r   r   r   r   Z
compressedr   r   r   r!   r!   r!   r"   <module>   s       >