o
    EOf3                     @  s   d Z ddlmZ ddlmZ ddlZddlmZ er ddl	mZ
 eejfZdd ZG d	d
 d
ZdddZdd Zdd ZdddZdd Zdd ZdS )z0Indexing mixin for sparse array/matrix classes.
    )annotations)TYPE_CHECKINGN   )	isintlikec                 C  s0   t | |\}}| jj|j_|jj|j_||fS )a   
    Same as np.broadcast_arrays(a, b) but old writeability rules.

    NumPy >= 1.17.0 transitions broadcast_arrays to return
    read-only arrays. Set writeability explicitly to avoid warnings.
    Retain the old writeability rules, as our Cython code assumes
    the old behavior.
    )npZbroadcast_arraysflagsZ	writeable)abxy r   3lib/python3.10/site-packages/scipy/sparse/_index.py_broadcast_arrays   s   	r   c                   @  s   e Zd Z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! Zd"d# Zd$d% Zd&d' Zd(d) Zd*S )+
IndexMixinzS
    This class provides common dispatching and validation logic for indexing.
    c                 C  s"   ddl m} t| |rtddS )zWe do not currently support 1D sparse arrays.

        This function is called each time that a 1D array would
        result, raising an error instead.

        Once 1D sparse arrays are implemented, it should be removed.
        r   )sparrayzcWe have not yet implemented 1D sparse slices; please index using explicit indices, e.g. `x[:, [0]]`N)Zscipy.sparser   
isinstanceNotImplementedError)selfr   r   r   r   _raise_on_1d_array_slice#   s   
z#IndexMixin._raise_on_1d_array_slicec                 C  s  |  |\}}t|trDt|tr| ||S t|tr&|   | ||S |jdkr5|   | ||S |jdkr@| ||S t	dt|trt|trX|   | 
||S t|trq|td krk||krk|  S | ||S |jdkr|| ||S t	d|jdkrt|tr|   | ||S t|tr| ||S n5t|tr| ||S t|trt	d|jd dkr|jdks|jd dkr| |d d df | S t||\}}|j|jkrt	d|jdkr| jt|j| jdS | ||S )Nr      zindex results in >2 dimensionsr   'number of row and column indices differdtype)_validate_indicesr   	INT_TYPES_get_intXintslicer   _get_intXslicendim_get_intXarray
IndexError_get_sliceXintcopy_get_sliceXslice_get_sliceXarray_get_arrayXint_get_arrayXsliceshape_get_columnXarrayZravelr   size	__class__r   Z
atleast_2dr   _get_arrayXarray)r   keyrowcolr   r   r   __getitem__3   sV   













&
zIndexMixin.__getitem__c           
      C  sN  |  |\}}t|tr.t|tr.tj|| jd}|jdkr"td| |||j	d  d S t|t
rEtj|| jd  d d d f }nt|}t|t
rntj|| jd  d d d f }|jdkrm|d d d f }nt|}t||\}}|j|jkrtdddlm} ||r|jdkr|d  }|d  }|jd dko|jd dk}|jd dko|jd dk}	|s|jd |jd kr|	s|jd |jd kstd|jd dks|jd dkrd S |jdd	}|  | ||| d S tj|| jd}| j| jkrt||j}|jdkrd S ||j}| ||| d S )
Nr   r   z&Trying to assign a sequence to an itemr   r   issparsezshape mismatch in assignmentT)r"   )r   r   r   r   asarrayr   r)   
ValueError_set_intXintZflatr   Zarangeindicesr'   Z
atleast_1dr   r   r    _baser1   ZtocooZsum_duplicates_set_arrayXarray_sparseZsqueezeZbroadcast_toZreshape_set_arrayXarray)
r   r,   r
   r-   r.   ijr1   Zbroadcast_rowZbroadcast_colr   r   r   __setitem__e   sV   

$

"


zIndexMixin.__setitem__c           
      C  sp  ddl m} t||tjfr*|jdkr*|jjdkr*|j| jkr#t	d|
 \}}nt|\}}| j\}}ddd}t|rZt|}|| k sK||krQt	d| |dk rY||7 }nt| }d uri|||d}nt|tst| ||}t|rt|}|| k s||krt	d| |dk r||7 }||fS t| }	d ur||	|d}||fS t|ts| ||}||fS )Nr   )_spbaser   r	   z.boolean index shape does not match array shapeidxnpt.NDArray[np.bool_]	axis_sizeint	axis_namestrreturnnpt.NDArray[np.int_]c                 S  s2   t | |krtd| dt |  d| t| S )Nzboolean z index has incorrect length: z instead of )lenr    _boolean_index_to_array)r=   r?   rA   r   r   r   _validate_bool_idx   s   z8IndexMixin._validate_indices.<locals>._validate_bool_idxzrow index (%d) out of ranger   r-   zcolumn index (%d) out of rangecolumn)r=   r>   r?   r@   rA   rB   rC   rD   )r6   r<   r   r   Zndarrayr   r   kindr'   r    nonzero_unpack_indexr   r@   _compatible_boolean_indexr   
_asindices)
r   r,   r<   r-   r.   MNrG   Zbool_rowZbool_colr   r   r   r      sB   



zIndexMixin._validate_indicesc              
   C  s   zt |}W n tttfy } ztd|d}~ww |jdvr%td|jdkr,|S | }||kr:td| |	 }|dk rc|| k rMtd| ||u sU|j
jsY| }||dk   |7  < |S )zConvert `idx` to a valid index for an axis with a given length.

        Subclasses that need special validation can override this method.
        zinvalid indexN)r   r   zIndex dimension must be 1 or 2r   index (%d) out of range)r   r2   r3   	TypeErrorMemoryErrorr    r   r)   maxminr   Zowndatar"   )r   r=   lengthr
   eZmax_indxZmin_indxr   r   r   rM      s*   



zIndexMixin._asindicesc                 C  sP   | j \}}t|}|| k s||krtd| |dk r ||7 }| |tdS )zGReturn a copy of row i of the matrix, as a (1 x n) row vector.
        rP   r   N)r'   r@   r    r   r   r   r9   rN   rO   r   r   r   _getrow      
zIndexMixin._getrowc                 C  sP   | j \}}t|}|| k s||krtd| |dk r ||7 }| td|S )zMReturn a copy of column i of the matrix, as a (m x 1) column vector.
        rP   r   N)r'   r@   r    r!   r   rW   r   r   r   _getcol   rY   zIndexMixin._getcolc                 C     t  Nr   r   r-   r.   r   r   r   r         zIndexMixin._get_intXintc                 C  r[   r\   r]   r^   r   r   r   r      r_   zIndexMixin._get_intXarrayc                 C  r[   r\   r]   r^   r   r   r   r     r_   zIndexMixin._get_intXslicec                 C  r[   r\   r]   r^   r   r   r   r!     r_   zIndexMixin._get_sliceXintc                 C  r[   r\   r]   r^   r   r   r   r#   	  r_   zIndexMixin._get_sliceXslicec                 C  r[   r\   r]   r^   r   r   r   r$     r_   zIndexMixin._get_sliceXarrayc                 C  r[   r\   r]   r^   r   r   r   r%     r_   zIndexMixin._get_arrayXintc                 C  r[   r\   r]   r^   r   r   r   r&     r_   zIndexMixin._get_arrayXslicec                 C  r[   r\   r]   r^   r   r   r   r(     r_   zIndexMixin._get_columnXarrayc                 C  r[   r\   r]   r^   r   r   r   r+     r_   zIndexMixin._get_arrayXarrayc                 C  r[   r\   r]   r   r-   r.   r
   r   r   r   r4     r_   zIndexMixin._set_intXintc                 C  r[   r\   r]   r`   r   r   r   r8     r_   zIndexMixin._set_arrayXarrayc                 C  s4   t j| | jd}t||\}}| ||| d S )Nr   )r   r2   Ztoarrayr   r   r8   )r   r-   r.   r
   _r   r   r   r7   !  s   z"IndexMixin._set_arrayXarray_sparseN)__name__
__module____qualname____doc__r   r/   r;   r   rM   rX   rZ   r   r   r   r!   r#   r$   r%   r&   r(   r+   r4   r8   r7   r   r   r   r   r      s,    240r   rC   ctuple[int | slice | npt.NDArray[np.bool_ | np.int_], int | slice | npt.NDArray[np.bool_ | np.int_]]c                 C  s   t | } t| tr(t| dkr| \}}n8t| dkr$| d td}}n(tdt| }|du r8| td}}n|jdk rC|tdfS |jdkrL| S ddl	m
} ||sZ||r^td||fS )z Parse index. Always return a tuple of the form (row, col).
    Valid type for row/col is integer, slice, array of bool, or array of integers.
    r   r   r   Nzinvalid number of indicesr0   zoIndexing with sparse matrices is not supported except boolean indexing where matrix and index are equal shapes.)_check_ellipsisr   tuplerE   r   r    rL   r   rJ   r6   r1   )indexr-   r.   r=   r1   r   r   r   rK   (  s(   



rK   c                 C  s   | t u rtdtdfS t| ts| S dd t| D }|s | S t|dkr*td|\}tddt|  }| d| tdf|  | |d d  S )z6Process indices with Ellipsis. Returns modified index.Nc                 S  s   g | ]
\}}|t u r|qS r   )Ellipsis).0r9   vr   r   r   
<listcomp>W  s    z#_check_ellipsis.<locals>.<listcomp>r   z0an index can only have a single ellipsis ('...')r      )rj   r   r   rh   	enumeraterE   r    rS   )ri   Zellipsis_indicesr9   Z
num_slicesr   r   r   rg   N  s   
*rg   c                 C  s   t | } | jjdkr| S dS )z8Returns a compatible array if elements are boolean.
    r	   N)r   Z
asanyarrayr   rI   r=   r   r   r   _maybe_bool_ndarrayc  s   
rq   r   c                 C  sP   |dk rdS z	t t| d}W n
 ty   Y dS w t|tr!dS t||d S )zQReturns True if first element of the incompatible
    array type is boolean.
    r   NT)nextiterrQ   r   bool_first_element_bool)r=   Zmax_dimfirstr   r   r   ru   l  s   
ru   c                 C  s   t | ds	t| rt| S dS )ztReturns a boolean index array that can be converted to
    integer array. Returns None if no such array exists.
    r   N)hasattrru   rq   rp   r   r   r   rL   {  s   rL   c                 C  s    | j dkr	tdt| d S )Nr   zinvalid index shaper   )r   r    r   whererp   r   r   r   rF     s   
rF   )rC   rf   )r   )re   Z
__future__r   typingr   Znumpyr   Z_sputilsr   Znumpy.typingZnptr@   Zintegerr   r   r   rK   rg   rq   ru   rL   rF   r   r   r   r   <module>   s$    
  
&
	
