o
    Ebh                     @   s   d Z g ZddlmZ ddlZddlZddlmZ ddl	m
Z
mZmZ ddlmZmZ ddlmZ dd	lmZmZmZmZmZmZmZmZ dd
lmZ ddlmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) G dd deeeZ*dd Z+dS )z>Base class for sparse matrix formats using compressed storage.    )warnN)_prune_array   )spmatrix
isspmatrixSparseEfficiencyWarning)_data_matrix_minmax_mixin)_sparsetools)get_csr_submatrixcsr_sample_offsetscsr_todensecsr_sample_valuescsr_row_indexcsr_row_slicecsr_column_index1csr_column_index2)
IndexMixin)upcastupcast_char	to_nativeisdenseisshapegetdtypeisscalarlike	isintlikeget_index_dtypedowncast_intp_indexget_sum_dtypecheck_shapeis_pydata_spmatrixc                   @   sZ  e Zd ZdZdyddZdzddZejje_d{dd	Zd|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d  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd}d,d-Zejje_d.d/ Zd0d1 Zejje_d2d3 Zejje_d~d4d5Zejje_dzd6d7Zd8d9 Zd:d; Zd<d= Z d>d? Z!d@dA Z"d{dBdCZ#dDdE Z$d{dFdGZ%dydHdIZ&dJdK Z'dLdM Z(dNdO Z)dPdQ Z*dRdS Z+dTdU Z,dVdW Z-dXdY Z.d|dZd[Z/ej/je/_dd\d]Z0ej0je0_d^d_ Z1d`da Z2dbdc Z3e4e2e3ddZ5dedf Z6dgdh Z7didj Z8e4e7e8ddZ9dkdl Z:dmdn Z;dodp Z<dqdr Z=ej=je=_d|dsdtZ>dudv Z?dwdx Z@dS )
_cs_matrixzBbase matrix class for compressed row- and column-oriented matricesNFc              
   C   sn  t |  t|r"|j| jkr|r| }n|| j}| | nt|trt	|rat
|| _| j\}}tt||d}tdt|td| _td|| _tj| ||fd d |d| _nt|dkrx| | j|||d}| | nlt|dkr|\}	}
}d }|d urt|}t|
|f|d	d
}tj|
||d| _tj|||d| _tj|	||d| _n2td| jzt|}W n ty } z	td| j|d }~ww | | | j||d |d urt
|| _n3| jd u r!zt| jd }| j d }W n ty } ztd|d }~ww t
| ||f| _|d ur/| jj|dd| _| jdd d S )Nmaxvalr   )defaultr   dtype   shaper&      T)r#   Zcheck_contentscopyr&   z(unrecognized {}_matrix constructor usagez!unable to infer matrix dimensionsFr,   
full_check) r   __init__r   formatr,   asformat	_set_self
isinstancetupler   r   _shaper)   r   maxnpzerosr   floatdataindices_swapindptrlen	__class___coo_containerarray
ValueErrorasarray	Exceptionastypecheck_format)selfZarg1r)   r&   r,   MN	idx_dtypeotherr;   r<   r>   r#   e	major_dim	minor_dim rP   :/usr/lib/python3/dist-packages/scipy/sparse/_compressed.pyr0      s   









z_cs_matrix.__init__c                 C   s   |d u rt | jd S |dk r|d7 }| |d| f\}}| | j\}}|dkr4tjt| j|dS |dkr>t| jS t	d)Nr   r'   r   )Z	minlengthzaxis out of bounds)
intr>   r=   r)   r8   Zbincountr   r<   diffrC   )rH   axis_rJ   rP   rP   rQ   getnnzl   s   z_cs_matrix.getnnzc                 C   s4   |r|  }|j| _|j| _|j| _t|j| _dS )z:take the member variables of other and assign them to selfN)r,   r;   r<   r>   r   r)   r6   )rH   rL   r,   rP   rP   rQ   r3   }   s   z_cs_matrix._set_selfTc                 C   s  |  d\}}|  | j\}}| jjjdkr"td| jjjdd | jjjdkr5td| jjjdd t	| j| jf}t
j| j|d| _t
j| j|d| _t| j| _| jj| jj| jjfD ]
}|dkrjtd	q`t| j|d krtd
t| j|d | jd dkrtdt| jt| jkrtd| jd t| jkrtd|   |r| jdkr| j |krtd||| j dk rtd|t
| j dk rtddS dS dS )zcheck whether the matrix format is valid

        Parameters
        ----------
        full_check : bool, optional
            If `True`, rigorous check, O(N) operations. Otherwise
            basic check, O(1) operations (default True).
        )rowcolumniz'indptr array has non-integer dtype ({})r*   
stacklevelz(indices array has non-integer dtype ({})r%   r   z'data, indices, and indptr should be 1-Dz&index pointer size ({}) should be ({})r   z!index pointer should start with 0z*indices and data should have the same sizerR   zQLast value of index pointer should be less than the size of index and data arraysz{} index values must be < {}z{} index values must be >= 0z8index pointer values must form a non-decreasing sequenceN)r=   r)   r>   r&   kindr   r1   namer<   r   r8   rD   r   r;   ndimrC   r?   prunennzr7   minrT   )rH   r/   Z
major_nameZ
minor_namerN   rO   rK   xrP   rP   rQ   rG      sX   

z_cs_matrix.check_formatc                 C   s*   |    | j|| j|dd}|  |S )zScalar version of self._binopt, for cases in which no new nonzeros
        are added. Produces a new spmatrix in canonical form.
        Tr-   )sum_duplicates
_with_datar;   eliminate_zeros)rH   rL   opresrP   rP   rQ   _scalar_binopt   s   z_cs_matrix._scalar_binoptc                 C   s  t |r;t|r| j| jtjdS |dkr4tdtdd | tj| jtjd}| 	|t
j}|| S | 	|t
jS t|rE|  |kS t|rKtS t|rtdtdd | j|jkr^dS | j|jkrj|| j}| |d}| tj| jtjd}|| S dS )	Nr%   r   zOComparing a sparse matrix with 0 using == is inefficient, try using != instead.r*   r[   zHComparing sparse matrices using == is inefficient, try using != instead.F_ne_)r   r8   isnanr@   r)   bool_r   r   onesri   operatorneeqr   todenser    NotImplementedr   r1   r2   _binopt)rH   rL   all_trueinvrh   rP   rP   rQ   __eq__   s8   
z_cs_matrix.__eq__c                 C   s   t |rGt|rtdtdd | tj| jtjd}|S |dkr@tdtdd | jt| jtjd}| 	|t
j}|| S | 	|t
jS t|rQ|  |kS t|rWtS t|ru| j|jkrcdS | j|jkro|| j}| |dS dS )	Nz:Comparing a sparse matrix with nan using != is inefficientr*   r[   r%   r   z^Comparing a sparse matrix with a nonzero scalar using != is inefficient, try using == instead.Trj   )r   r8   rk   r   r   r@   rm   r)   rl   ri   rn   rp   ro   r   rq   r    rr   r   r1   r2   rs   )rH   rL   rt   ru   rP   rP   rQ   __ne__   s4   
z_cs_matrix.__ne__c                 C   s  t |r;d|kr|dv rtd|d|r5t|t tj| jt|d}|| | 	|}| 
||S | ||S t|rF||  |S t|r| j|jkrTtd| j|jkr`|| j}|dvrj| 
||S tdt | 	tj| jtjd}| 
||dkrd	nd
}|| S td)Nr   )_le__ge_z >= and <= don't work with 0.r%   inconsistent shapes)ry   rx   zUComparing sparse matrices using >= and <= is inefficient, using <, >, or !=, instead.rx   _gt__lt_zOperands could not be compared.)r   NotImplementedErrorr   r   r8   emptyr)   Zresult_typefillr@   rs   ri   r   rq   r   rC   r1   r2   rm   rl   )rH   rL   rg   op_nameZbad_scalar_msg	other_arrrt   rh   rP   rP   rQ   _inequality  s4   



z_cs_matrix._inequalityc                 C      |  |tjddS )Nr|   zgComparing a sparse matrix with a scalar greater than zero using < is inefficient, try using >= instead.)r   rn   ltrH   rL   rP   rP   rQ   __lt__?     z_cs_matrix.__lt__c                 C   r   )Nr{   zdComparing a sparse matrix with a scalar less than zero using > is inefficient, try using <= instead.)r   rn   gtr   rP   rP   rQ   __gt__E  r   z_cs_matrix.__gt__c                 C   r   )Nrx   zgComparing a sparse matrix with a scalar greater than zero using <= is inefficient, try using > instead.)r   rn   ler   rP   rP   rQ   __le__K  r   z_cs_matrix.__le__c                 C   r   )Nry   zdComparing a sparse matrix with a scalar less than zero using >= is inefficient, try using < instead.)r   rn   ger   rP   rP   rQ   __ge__Q  r   z_cs_matrix.__ge__c                 C   s   |j | j krtd| j |j t| jj|jj}| dd }tj|||dd}| | j \}}|j	j
r7|n|j}t||| j| j| j| | j|ddS )NzIncompatible shapes ({} and {})ZCFr   T)r&   orderr,   Fr-   )r)   rC   r1   r   r&   charr=   r8   rB   flagsc_contiguousTr   r>   r<   r;   
_container)rH   rL   r&   r   resultrI   rJ   yrP   rP   rQ   
_add_dense[  s   z_cs_matrix._add_densec                 C      |  |dS )NZ_plus_rs   r   rP   rP   rQ   _add_sparseg     z_cs_matrix._add_sparsec                 C   r   )NZ_minus_r   r   rP   rP   rQ   _sub_sparsej  r   z_cs_matrix._sub_sparsec                 C   s&  t |r	| |S t|r| j|jkr| |}| |dS |jdkr-| | d S | jdkr;||  d S | jd dkrP|jd dkrP| | S | jd dkre|jd dkre||  S |jd dkr| jd |jd kr| j	| 
 dgf|jd |jd fd}| |S | jd dkr| jd |jd kr| j	|  
 dgf| jd | jd fd}||S |jd dkr| jd |jd kr| j	| 
 dgf|jd |jd fd}|| S | jd dkr| jd |jd kr| j	|  
 dgf| jd | jd fd}||S tdt|}|jdkr.t|  |S |jdkr<| |jd S | jdkrLt|  d |S |  }| j|jkrft|j||j|jf }n"| jd dkr|jd dkr~t|j|}n|jd | jd krt|j|d	d	|jf }ntdtt|jd t|j}t|j|jd }| j|tj
 ||ff|jd | jd fd
dS | jd dkr@|jd dkrt|jd	d	d	f |}n |jd | jd kr	t|jd	d	d	f ||j }ntdt|j|jd }tt|jd t|j}| j|tj
 ||ff| jd |jd fd
dS |jd dkrd| jd |jd krdt|j|d	d	|jf 
 }n$|jd dkr| jd |jd krt|j||j 
 }ntd|tj
 |_|S )zPPoint-wise multiplication by another matrix, vector, or
        scalar.
        Z_elmul_)r   r   )r   r   r   r   r)   rz   r'   NFr)   r,   )r   Z_mul_scalarr   r)   r@   rs   toarray_mul_sparse_matrixtocscZ_dia_containerravelrC   r8   Z
atleast_2dr_   multiplysizeZflattocoor;   rX   colrepeataranger?   tilerA   viewZndarray)rH   rL   r,   retr;   rX   r   rP   rP   rQ   r   m  s   




"
"
"
&

"&"&z_cs_matrix.multiplyc                 C   sT   | j \}}tj|t| jj|jjd}tt| jd }|||| j	| j
| j|| |S )Nr%   Z_matvec)r)   r8   r9   r   r&   r   getattrr
   r1   r>   r<   r;   )rH   rL   rI   rJ   r   fnrP   rP   rQ   _mul_vector  s   
z_cs_matrix._mul_vectorc              
   C   sl   | j \}}|j d }tj||ft| jj|jjd}tt| jd }||||| j	| j
| j| |  |S )Nr   r%   Z_matvecs)r)   r8   r9   r   r&   r   r   r
   r1   r>   r<   r;   r   )rH   rL   rI   rJ   Zn_vecsr   r   rP   rP   rQ   _mul_multivector  s   


z_cs_matrix._mul_multivectorc                 C   sf  | j \}}|j \}}| ||fd }| |}t| j| j|j|jf}tt| jd }|||t	j
| j|dt	j
| j|dt	j
|j|dt	j
|j|d}	t| j| j|j|jf|	d}t	j|d |d}
t	j|	|d}t	j|	t| j|jd}tt| jd }|||t	j
| j|dt	j
| j|d| jt	j
|j|dt	j
|j|d|j|
|| | j|||
f||fdS )Nr   Z_matmat_maxnnzr%   r"   r   Z_matmatr   )r)   r=   r@   r   r>   r<   r   r
   r1   r8   rD   r~   r   r&   r;   )rH   rL   rI   ZK1ZK2rJ   Z
major_axisrK   r   ra   r>   r<   r;   rP   rP   rQ   r     s@   




z_cs_matrix._mul_sparse_matrixr   c                 C   s   | j \}}|| ks||krtjd| jjdS tt| jd }tjt|t|d |t	|d t
| jd}||| j d | j d | j| j| j| |S )Nr   r%   Z	_diagonalr   )r)   r8   r~   r;   r&   r   r
   r1   rb   r7   r   r>   r<   )rH   kZrowsZcolsr   r   rP   rP   rQ   diagonal  s   
 z_cs_matrix.diagonalc                 C   s   t |rI||r+tdtdd tj| jt|jd}|| | 	|}| 
||S |   || jt|}| j	|| j| jf|j| jd}|S t|rT||  |S t|r^| 
||S td)NzITaking maximum (minimum) with > 0 (< 0) number results to a dense matrix.r*   r[   r%   )r&   r)   zOperands not compatible.)r   r   r   r8   r~   r)   rD   r&   r   r@   rs   rd   r;   r<   r>   r   rq   r   rC   )rH   rL   Znpopr   Zdense_checkr   Znew_dataZmatrP   rP   rQ   _maximum_minimum0  s*   

z_cs_matrix._maximum_minimumc                 C      |  |tjddd S )NZ	_maximum_c                 S   s   t | dkS Nr   r8   rD   rc   rP   rP   rQ   <lambda>I      z$_cs_matrix.maximum.<locals>.<lambda>)r   r8   maximumr   rP   rP   rQ   r   G     
z_cs_matrix.maximumc                 C   r   )NZ	_minimum_c                 S   s   t | dk S r   r   r   rP   rP   rQ   r   O  r   z$_cs_matrix.minimum.<locals>.<lambda>)r   r8   minimumr   rP   rP   rQ   r   M  r   z_cs_matrix.minimumc                 C   s   t | dsO|| dd v rOt| j}tjt| jd |d}| tj	\}}|||< | 
|}|d dkr9|j}|durG|j|jkrGtd|jd	||d
S tj| |||d
S )z~Sum the matrix over the given axis.  If the axis is None, sum
        over both rows and columns, returning a scalar.
        	blocksize))r   rR   )r   r'   r   r   r%   r'   Nzdimensions do not matchrP   )rU   r&   out)hasattrr=   r   r&   r8   r9   r?   r>   _minor_reduceadd_ascontainerr   r)   rC   sumr   )rH   rU   r&   r   Z	res_dtyper   major_indexvaluerP   rP   rQ   r   W  s   


z_cs_matrix.sumc                 C   s>   |du r| j }tt| j}||t| j| }||fS )a  Reduce nonzeros with a ufunc over the minor axis when non-empty

        Can be applied to a function of self.data by supplying data parameter.

        Warning: this does not call sum_duplicates()

        Returns
        -------
        major_index : array of ints
            Major indices where nonzero

        value : array of self.dtype
            Reduce result for nonzeros in each major_index
        N)r;   r8   ZflatnonzerorT   r>   Zreduceatr   )rH   Zufuncr;   r   r   rP   rP   rQ   r   t  s   z_cs_matrix._minor_reducec           
      C   s\   |  | j\}}|  ||f\}}t||| j| j| j||d ||d 	\}}}	|	j| jdS )Nr   r%   )r=   r)   r   r>   r<   r;   r   r&   )
rH   rX   r   rI   rJ   majorminorr>   r<   r;   rP   rP   rQ   _get_intXint  s   
z_cs_matrix._get_intXintc                 C   sF   |  ||f\}}|jdv r|jdv r| j||ddS | ||S )N)r   NTr-   )r=   step_get_submatrix_major_slice_minor_slicerH   rX   r   r   r   rP   rP   rQ   _get_sliceXslice  s   z_cs_matrix._get_sliceXslicec           	   
   C   s   | j j}| | j\}}| ||f\}}tj||d}tj||d}tj|j| jd}t||| j	| j | j
|j| | |	 |jdkrJ| |S | ||jS )Nr%   r   )r<   r&   r=   r)   r8   rD   r~   r   r   r>   r;   r   r_   r   r@   Zreshape)	rH   rX   r   rK   rI   rJ   r   r   valrP   rP   rQ   _get_arrayXarray  s   

z_cs_matrix._get_arrayXarrayc                 C   s"   |  ||f\}}| ||S N)r=   _major_index_fancy_minor_index_fancyr   rP   rP   rQ   _get_columnXarray  s   z_cs_matrix._get_columnXarrayc                 C   s   | j j}tj||d }| | j\}}t|}| ||f}|dkr)| |S | j	|d  | j	|  }| j j}tj
|d |d}	tj||	dd d |	d }
tj|
|d}tj|
| jd}t||| j	| j | j|| | j|||	f|ddS )	zBIndex along the major axis where idx is an array of ints.
        r%   r   r   Nr   rR   Fr   )r<   r&   r8   rD   r   r=   r)   r?   r@   r>   r9   cumsumr~   r   r;   )rH   idxrK   r<   rV   rJ   rI   	new_shaperow_nnz
res_indptrra   res_indicesres_datarP   rP   rQ   r     s(   
z_cs_matrix._major_index_fancyc              	   C   s  |t dkr|r|  S | S | | j\}}||\}}}tt|||}| ||f}|dkr6| |S ||}	}
|dkrE|dkrEd}
|d |d }}| j||| | j|	|
|  }| jj	}t
j|d |d}t
j||dd d |dkrt | j| | j| }t
j| j| |d}t
j| j| |d}n!|d }t
j||d}t
j|| j	d}t|||| j| j| j|| | j|||f|dd	S )
z@Index along the major axis where idx is a slice object.
        Nr   rR   r   r%   r   r-   Fr   )slicer,   r=   r)   r<   r?   ranger@   r>   r&   r8   r9   r   rB   r;   r~   r   )rH   r   r,   rI   rJ   startstopr   r   Zstart0Zstop0Zstart1Zstop1r   rK   r   Zall_idxr   r   ra   rP   rP   rQ   r     s>   

z_cs_matrix._major_slicec              	   C   s   | j j}tj||d }| | j\}}t|}| ||f}|dkr)| |S tj	||d}t
| j}t||||| j| j || t|j|dd}	|d }
tj|
|d}tj|
| jd}t|	|t| j | j | j|| | j|||f|ddS )zBIndex along the minor axis where idx is an array of ints.
        r%   r   Fr-   rR   r   )r<   r&   r8   rD   r   r=   r)   r?   r@   r9   Z
empty_liker>   r   argsortrF   r~   r   r;   )rH   r   rK   rI   rJ   r   r   Zcol_offsetsr   Z	col_orderra   r   r   rP   rP   rQ   r     s,   
z_cs_matrix._minor_index_fancyc                 C   s   |t dkr|r|  S | S | | j\}}||\}}}tt|||}|dkr4| | ||fS |dkr?| j||dS | 	t
|||S )z@Index along the minor axis where idx is a slice object.
        Nr   r   )r   r,   )r   r,   r=   r)   r<   r?   r   r@   r   r   r8   r   )rH   r   r,   rI   rJ   r   r   r   rP   rP   rQ   r     s   z_cs_matrix._minor_slicec              
   C   s   |  | j\}}t||\}}t||\}}	|dkr.|dkr.||kr.|	|kr.|r,|  S | S t||| j| j| j||||		\}
}}|  || |	| f}| j|||
f|| j	ddS )zbReturn a submatrix of this matrix.

        major, minor: None, int, or slice with step 1
        r   F)r)   r&   r,   )
r=   r)   _process_slicer,   r   r>   r<   r;   r@   r&   )rH   r   r   r,   rI   rJ   i0i1Zj0Zj1r>   r<   r;   r)   rP   rP   rQ   r     s    
z_cs_matrix._get_submatrixc                 C   $   |  ||f\}}| ||| d S r   r=   	_set_manyrH   rX   r   rc   rZ   jrP   rP   rQ   _set_intXint1     z_cs_matrix._set_intXintc                 C   r   r   r   r   rP   rP   rQ   _set_arrayXarray5  r   z_cs_matrix._set_arrayXarrayc                 C   s  | j | ||f  |j\}}|dko|jd dk}|dko$|jd dk}|j|j}}	tj|j| jd}|j	dkr<d S |rUt
t|t|}t|	|}	t||}|rnt
||}tt|t|	}	t
||}| |||	f |||	f f\}
}| |
|| d S )Nr   r   r%   )
_zero_manyr=   r)   rX   r   r8   rD   r;   r&   r   r   r   r?   r   r   )rH   rX   r   rc   rI   rJ   Zbroadcast_rowZbroadcast_colrcrZ   r   rP   rP   rQ   _set_arrayXarray_sparse9  s$   

"z"_cs_matrix._set_arrayXarray_sparsec           	      C   s   d| j v rd S | j \}}|jdk}|dk r@|rt|| |}n
t|| |t|}tj|| jjd}tj|| jjd}||8 }n*|rJt||| }n
t||| t|}tj|| jjd}tj|| jjd}||7 }|st|d t| }|| ||f< d S )Nr   r%   )r)   r_   rb   r?   r8   r   r<   r&   )	rH   valuesr   rI   rJ   Z	broadcastZ	max_indexrZ   r   rP   rP   rQ   _setdiagR  s(   



z_cs_matrix._setdiagc                 C   sl   |  | j\}}dd }tj|| jjddd }tj|| jjddd }||| ||| ||||fS )Nc                 S   sF   |   }||krtd||f |  }|| k r!td||f d S )Nzindex (%d) out of range (>= %d)zindex (%d) out of range (< -%d))r7   
IndexErrorrb   )r<   Zboundr   rP   rP   rQ   check_boundss  s   
z1_cs_matrix._prepare_indices.<locals>.check_boundsFr   r&   r,   Zndmin)r=   r)   r8   rB   r<   r&   r   )rH   rZ   r   rI   rJ   r   rP   rP   rQ   _prepare_indicesp  s   


z_cs_matrix._prepare_indicesc           
   	   C   s"  |  ||\}}}}tj|| jddd }|j}tj|| jjd}t||| j	| j||||}|dkrD| 
  t||| j	| j|||| d|vrO|| j|< dS td| jtdd	 |dk}	||	 | j||	 < |	 }	||	 }||d
k   |7  < ||	 }||d
k   |7  < | ||||	  dS )zSets value at each (i, j) to x

        Here (i,j) index major and minor respectively, and must not contain
        duplicate entries.
        Fr   r   r%   rR   NzZChanging the sparsity structure of a {}_matrix is expensive. lil_matrix is more efficient.r*   r[   r   )r   r8   rB   r&   r   r   r~   r<   r   r>   rd   r;   r   r1   r   _insert_many)
rH   rZ   r   rc   rI   rJ   	n_samplesoffsetsr   maskrP   rP   rQ   r     s6   
z_cs_matrix._set_manyc              	   C   s   |  ||\}}}}t|}tj|| jjd}t||| j| j||||}|dkr9|   t||| j| j|||| d| j	||dk < dS )zSets value at each (i, j) to zero, preserving sparsity structure.

        Here (i,j) index major and minor respectively.
        r%   r   r   rR   N)
r   r?   r8   r~   r<   r&   r   r>   rd   r;   )rH   rZ   r   rI   rJ   r   r   r   rP   rP   rQ   r     s   z_cs_matrix._zero_manyc                 C   s  t j|dd}|j|dd}|j|dd}|j|dd}| j}t| j| jf| jd |j d}t j| j|d| _t j| j|d| _t j||d}t j||d}g }g }t j	|dd	\}	}
t 
|
t|}
t |
}d
}tt|	|
|
dd D ]z\}\}}}| j| }| j| }|
| j||  |
| j||  t j	||| ddd dd	\}}t||| kr|
|||  |
|||  n&|
||| ddd |  |
||| ddd |  t|||< |}qw| j| }|
| j|d  |
| j|d  t || _t || _t j| jj|d}|d
|d
< t | j}||	  |7  < ||dd< t j||d| _|rLd| _|   | jdd dS )a:  Inserts new nonzero at each (i, j) with value x

        Here (i,j) index major and minor respectively.
        i, j and x must be non-empty, 1d arrays.
        Inserts each major group (e.g. all entries per row) at a time.
        Maintains has_sorted_indices property.
        Modifies i, j, x in place.
        Z	mergesort)r]   Zclip)moderR   r"   r%   T)Zreturn_indexr   r   Nr   Fr.   )r8   r   Ztakehas_sorted_indicesr   r<   r>   r   rD   uniqueappendr?   rT   	enumeratezipr;   Zconcatenater~   r)   r   sort_indicesrG   )rH   rZ   r   rc   r   Zdo_sortrK   Zindices_partsZ
data_partsZuiZ	ui_indptrZnew_nnzsprevr   iiZjsZjer   r   ZujZ	uj_indptrZnnzsZindptr_diffrP   rP   rQ   r     s\   	
&

$  
z_cs_matrix._insert_manyc                 C   sn   |  | j\}}| j}tjt|| jjd}t|| j	| |  ||f\}}| j
| j||ff| j|| jdS )Nr%   r+   )r=   r)   r<   r8   r~   r?   r&   r
   Z	expandptrr>   rA   r;   )rH   r,   rN   rO   Zminor_indicesZmajor_indicesrX   r   rP   rP   rQ   r   
  s   z_cs_matrix.tocooc                 C   s   |d u r|d u r|  dd }| ||}|jjs!|jjs!td|jjr,|  }|}n|  }|j}| |j	\}}t
|||j|j|j| |S )NZcfr   z&Output array must be C or F contiguous)r=   Z_process_toarray_argsr   r   f_contiguousrC   Ztocsrr   r   r)   r   r>   r<   r;   )rH   r   r   rc   r   rI   rJ   rP   rP   rQ   r     s   z_cs_matrix.toarrayc                 C   s4   |  | j\}}t||| j| j| j |   dS )zVRemove zero entries from the matrix

        This is an *in place* operation.
        N)r=   r)   r
   Zcsr_eliminate_zerosr>   r<   r;   r`   rH   rI   rJ   rP   rP   rQ   rf   /  s
   z_cs_matrix.eliminate_zerosc                 C   sJ   t | ddsd| _| jS t| ds"ttt| jd | j| j| _	| jS )a^  Determine whether the matrix has sorted indices and no duplicates

        Returns
            - True: if the above applies
            - False: otherwise

        has_canonical_format implies has_sorted_indices, so if the latter flag
        is False, so will the former be; if the former is found True, the
        latter flag is also set.
        _has_sorted_indicesTF_has_canonical_formatr   )
r   r  r   boolr
   Zcsr_has_canonical_formatr?   r>   r<   has_canonical_formatrH   rP   rP   rQ   Z__get_has_canonical_format9  s   
z%_cs_matrix.__get_has_canonical_formatc                 C   s   t || _|rd| _d S d S )NT)r  r  r   rH   r   rP   rP   rQ   Z__set_has_canonical_formatO  s   

z%_cs_matrix.__set_has_canonical_format)fgetfsetc                 C   sL   | j rdS |   | | j\}}t||| j| j| j | 	  d| _ dS )zmEliminate duplicate matrix entries by adding them together

        This is an *in place* operation.
        NT)
r  r   r=   r)   r
   Zcsr_sum_duplicatesr>   r<   r;   r`   r  rP   rP   rQ   rd   W  s   
z_cs_matrix.sum_duplicatesc                 C   s2   t | dsttt| jd | j| j| _| jS )zDetermine whether the matrix has sorted indices

        Returns
            - True: if the indices of the matrix are in sorted order
            - False: otherwise

        r  r   )r   r  r
   Zcsr_has_sorted_indicesr?   r>   r<   r  r  rP   rP   rQ   Z__get_sortedg  s   

z_cs_matrix.__get_sortedc                 C   s   t || _d S r   )r  r  r	  rP   rP   rQ   Z__set_sortedw  s   z_cs_matrix.__set_sortedc                 C   s   |   }|  |S )z9Return a copy of this matrix with sorted indices
        )r,   r   )rH   ArP   rP   rQ   sorted_indices|  s   z_cs_matrix.sorted_indicesc                 C   s4   | j stt| jd | j| j| j d| _ dS dS )z3Sort the indices of this matrix *in place*
        r   TN)r   r
   Zcsr_sort_indicesr?   r>   r<   r;   r  rP   rP   rQ   r     s   
z_cs_matrix.sort_indicesc                 C   s   |  | jd }t| j|d krtdt| j| jk r!tdt| j| jk r-tdt| jd| j | _t| jd| j | _dS )z8Remove empty space after all non-zero elements.
        r   r   z index pointer has invalid lengthz)indices array has fewer than nnz elementsz&data array has fewer than nnz elementsN)	r=   r)   r?   r>   rC   r<   ra   r;   r   )rH   rN   rP   rP   rQ   r`     s   z_cs_matrix.prunec                 G   s  t |}t| dr=| j\}}t|d |\}}t|d |\}}|s$|r-td| j|f | jd | | jd | }}	n| |\}}| | j\}}	||k rq| jd | j|  | _| j	d | j|  | _	| jd |d  | _n||krt
| j|d | _| j|d d  | j|  ||	k r| j|k }
t
|
s| j|
 | _| j	|
 | _	| t
j|
\}}| jd || jdd  |< t
j| j| jd || _d S )Nr   r   r   z.shape must be divisible into %s blocks. Got %sr   )r   r   r   divmodrC   r)   r=   r<   r>   r;   r8   resizer   allr   r   r   r6   )rH   r)   ZbmZbnZnew_MZrmZnew_NZrnrI   rJ   r   r   r   rP   rP   rQ   r    s:   

 


z_cs_matrix.resizec                 C   sH   |r| j || j | j f| j|jdS | j || j| jf| j|jdS )zReturns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays
        (i.e. .indptr and .indices) are copied.
        r(   )r@   r<   r,   r>   r)   r&   )rH   r;   r,   rP   rP   rQ   re     s   z_cs_matrix._with_datac                 C   s   |  |}tt| j| | j }| j|j }t| j| j|j|jf|d}tj	| jj
|d}tj	||d}g d}||v rEtj	|tjd}	ntj	|t| j|jd}	|| j
d | j
d tj| j|dtj| j|d| jtj|j|dtj|j|d|j|||	 | j |	||f| j
d}
|
  |
S )z5apply the binary operation fn to two sparse matrices.r"   r%   )rj   r|   r{   rx   ry   r   r   r   )r@   r   r
   r1   ra   r   r>   r<   r8   r~   r)   rl   r   r&   rD   r;   r`   )rH   rL   rg   r   ZmaxnnzrK   r>   r<   Zbool_opsr;   r  rP   rP   rQ   rs     s4   

	z_cs_matrix._binoptc                 C   s   |j | j kr
td| |d}t|jtjrGtj| j | jd}|tj	 |
 \}}d|||f< | }|j||j|jf< | |}|S |}|S )z?
        Divide this matrix by a second sparse matrix.
        rz   Z_eldiv_r%   r   )r)   rC   rs   r8   Z
issubdtyper&   Zinexactr~   r   nanZnonzeror   r;   rX   r   r   )rH   rL   r   r   rX   r   rP   rP   rQ   _divide_sparse  s   
z_cs_matrix._divide_sparse)NNFr   )F)T)r   )NNN)NN)A__name__
__module____qualname____doc__r0   rW   r   r3   rG   ri   rv   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rf   Z$_cs_matrix__get_has_canonical_formatZ$_cs_matrix__set_has_canonical_formatpropertyr  rd   Z_cs_matrix__get_sortedZ_cs_matrix__set_sortedr   r  r   r`   r  re   rs   r  rP   rP   rP   rQ   r!      s    

R


F	$""
s
$






(

'
L



	
"
"r!   c                 C   s   | d u rd|}}||fS t | tr+| |\}}}|dkr"tdt||}||fS t| rS| dk r7| |7 } | | d }}|dk sF||krOtd|||f ||fS td)Nr   r   z$slicing with step != 1 not supportedz'index out of bounds: 0 <= %d < %d <= %dzexpected slice or scalar)r4   r   r<   rC   rb   r   r   	TypeError)slZnumr   r   ZstriderP   rP   rQ   r     s&   


r   ),r  __all__warningsr   rn   Znumpyr8   Zscipy._lib._utilr   Z_baser   r   r   _datar   r	    r
   r   r   r   r   r   r   r   r   Z_indexr   Z_sputilsr   r   r   r   r   r   r   r   r   r   r   r   r    r!   r   rP   rP   rP   rQ   <module>   s0    (<          