o
    EOfV                     @   s   d Z dZg d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 dd	l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G dd dee
ZG dd deeZdS )zDictionary Of Keys based matrixzrestructuredtext en)	dok_array
dok_matrixisspmatrix_dok    N   )spmatrix)_spbasesparrayissparse)
IndexMixin)isdensegetdtypeisshape	isintlikeisscalarlikeupcastupcast_scalarcheck_shapec                       sB  e Zd ZdZdwddZdd Zdxdd	Zd
d Zejj	e_	ejj	e_	dd Z
dd Zdxd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dyd)d*Z fd+d,Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Z d;d< Z!d=d> Z"d?d@ Z#dAdB Z$ fdCdDZ%dEdF Z&dGdH Z'dIdJ Z(dKdL Z)dMdN Z*dOdP Z+dQdR Z,dSdT Z-dUdV Z.dWdX Z/dYdZ Z0d[d\ Z1d]d^ Z2dz fd`da	Z3d{dbdcZ4ej4j	e4_	ddde Z5dfdg Z6ej6j	e6_	e7d|didjZ8d}dkdlZ9ej9j	e9_	d}dmdnZ:ej:j	e:_	d}dodpZ;ej;j	e;_	dqdr Z<ej<j	e<_	d~dudvZ=  Z>S )	_dok_basedokNFc              
   C   sl  t |  t| t}t|tr(t||dr(t||d| _i | _t	|t
d| _d S t|r\|j| jkr;|r8| n|}n| }|d urJ|j|dd}|j| _t|j|d| _|j| _d S zt|}W n tyt } ztd|d }~ww |jdkr~td|jdkr|d ur||}d	d
 t|D | _|j| _n| j||d }|j| _|j| _t|j|d| _d S )NZallow_1d)defaultFcopyzInvalid input format.   z(Expected rank <=2 dense array or matrix.r   c                 S   s   i | ]\}}|d kr||qS r    ).0ivr   r   1lib/python3.10/site-packages/scipy/sparse/_dok.py
<dictcomp>4   s    z&_dok_base.__init__.<locals>.<dictcomp>dtype)r   __init__
isinstancer   tupler   r   _shape_dictr   floatr"   r	   formatr   todokastypeshapenpZasarray	Exception	TypeErrorndim	enumerate_coo_container)selfZarg1r,   r"   r   is_arrayedr   r   r   r#      s@   






z_dok_base.__init__c                 C      t d)Nz2Direct update to DOK sparse format is not allowed.)NotImplementedError)r3   valr   r   r   update<   s   z_dok_base.updatec                 C   s   |d urt dt| jS )Nz7_getnnz over an axis is not implemented for DOK format.)r8   lenr'   )r3   Zaxisr   r   r   _getnnz@   s
   
z_dok_base._getnnzc                 C   s   t dd |  D S )Nc                 s   s    | ]}|d kV  qdS r   Nr   )r   xr   r   r   	<genexpr>H   s    z*_dok_base.count_nonzero.<locals>.<genexpr>)sumvaluesr3   r   r   r   count_nonzeroG      z_dok_base.count_nonzeroc                 C   s
   t | jS N)r;   r'   rB   r   r   r   __len__M      
z_dok_base.__len__c                 C   s
   || j v S rE   r'   r3   keyr   r   r   __contains__P   rG   z_dok_base.__contains__c                C   s   | j ||S rE   )r'   
setdefault)r3   rJ   r   r   r   r   rL   S   s   z_dok_base.setdefaultc                C   s   | j |= d S rE   rH   rI   r   r   r   __delitem__V      z_dok_base.__delitem__c                 C   
   | j  S rE   )r'   clearrB   r   r   r   rP   Y   rG   z_dok_base.clearc                G   s   | j j| S rE   )r'   pop)r3   argsr   r   r   rQ   \   rN   z_dok_base.popc                 C   r7   )Nz*reversed is not defined for dok_array type)r/   rB   r   r   r   __reversed___      z_dok_base.__reversed__c                 C   (   t | j dt |j }td| Nz and z unsupported operand type for |: type__name__r/   r3   otherZ
type_namesr   r   r   __or__b      z_dok_base.__or__c                 C   rU   rV   rW   rZ   r   r   r   __ror__f   r]   z_dok_base.__ror__c                 C   rU   rV   rW   rZ   r   r   r   __ior__j   r]   z_dok_base.__ior__c                 C   rO   rE   )r'   popitemrB   r   r   r   r`   n   rG   z_dok_base.popitemc                 C   rO   rE   )r'   itemsrB   r   r   r   ra   q   rG   z_dok_base.itemsc                 C   rO   rE   )r'   keysrB   r   r   r   rb   t   rG   z_dok_base.keysc                 C   rO   rE   )r'   rA   rB   r   r   r   rA   w   rG   z_dok_base.values        c              
   C   s   || j v r
| j | S t|r| jdkr|f}| jt|kr%td| dz|D ]}t|s0J q(W n tttfyF } ztd|d}~ww tdd t	|| j
D }tdd t	|| j
D retd	| jdkrn|d
 }| j ||S )z>This provides dict.get method functionality with type checkingr   zIndex z! length needs to match self.shapez%Index must be or consist of integers.Nc                 s   s(    | ]\}}|d k r|| n|V  qdS r=   r   r   r   Mr   r   r   r?      s   & z _dok_base.get.<locals>.<genexpr>c                 s   s$    | ]\}}|d k p||kV  qdS r=   r   rd   r   r   r   r?         " zIndex out of bounds.r   )r'   r   r0   r;   
IndexErrorAssertionErrorr/   
ValueErrorr%   zipr,   anyget)r3   rJ   r   r   r5   r   r   r   rl   z   s(   



z_dok_base.getc                    s   | j dkrt |S t|trt|dkr|d }ttjf}t||rC|dk r/|| j	d 7 }|dk s:|| j	d kr>t
d| |S t
d)Nr   r   r   index value out of boundsz4array/slice index for 1d dok_array not yet supported)r0   super__getitem__r$   r%   r;   intr-   integerr,   rg   _get_int)r3   rJ   	INT_TYPES	__class__r   r   rp      s   



z_dok_base.__getitem__c                 C   s   | j || jdS Nr   r'   rl   r"   rX   )r3   idxr   r   r   rs      rD   z_dok_base._get_intc                 C   s   | j ||f| jdS rw   rx   r3   rowcolr   r   r   _get_intXint   s   z_dok_base._get_intXintc                 C   s   |  t||d |S Nr   _get_sliceXsliceslicerz   r   r   r   _get_intXslice   rD   z_dok_base._get_intXslicec                 C   s   |  |t||d S r~   r   rz   r   r   r   _get_sliceXint   rD   z_dok_base._get_sliceXintc                 C   s"  | | jd \}}}| | jd \}}}t|||}	t|||}
t|	t|
f}t| d|d  |d  kr>| |	|
S | j|| jd}|  D ]D}tt	|d | |\}}|dksg|dk sg||d krhqJtt	|d | |\}}|dks|dk s||d krqJ| j
| |j
||f< qJ|S )Nr   r   r   r!   )indicesr,   ranger;   _get_columnXarray_dok_containerr"   rb   divmodrq   r'   )r3   r{   r|   Z	row_startZrow_stopZrow_stepZ	col_startZcol_stopZcol_stepZ	row_rangeZ	col_ranger,   newdokrJ   r   ZrijZrjr   r   r   r      s"   z_dok_base._get_sliceXslicec                 C   s   |  }| |g|S rE   Zsqueezer   rz   r   r   r   _get_intXarray      z_dok_base._get_intXarrayc                 C   s   |  }| ||gS rE   r   rz   r   r   r   _get_arrayXint   r   z_dok_base._get_arrayXintc                 C   s$   t t|| jd  }| ||S rw   listr   r   r,   r   rz   r   r   r   _get_sliceXarray      z_dok_base._get_sliceXarrayc                 C   s$   t t|| jd  }| ||S r~   r   rz   r   r   r   _get_arrayXslice   r   z_dok_base._get_arrayXslicec           	      C   sh   | j t|t|f| jd}t|D ]\}}t|D ]\}}| j||fd}|r0||j||f< qq|S )Nr!   r   )r   r;   r"   r1   r'   rl   )	r3   r{   r|   r   r   rr   cr   r   r   r   r      s   z_dok_base._get_columnXarrayc                 C   s|   t tjt||\}}| j|j| jd}tt	|jd t	|jd D ]}| j
|| || fd}|r;||j
|< q%|S )Nr!   r   r   )mapr-   Z
atleast_2dZbroadcast_arraysr   r,   r"   	itertoolsproductr   r'   rl   )r3   r{   r|   r   r   r   rJ   r   r   r   r   _get_arrayXarray   s   $
z_dok_base._get_arrayXarrayc                    s   | j dkrt ||S t|trt|dkr|d }ttjf}t||rE|dk r0|| j	d 7 }|dk s;|| j	d kr?t
d| ||S t
d)Nr   r   r   rm   rn   z-array index for 1d dok_array not yet provided)r0   ro   __setitem__r$   r%   r;   rq   r-   rr   r,   rg   _set_int)r3   rJ   valuert   ru   r   r   r      s   


z_dok_base.__setitem__c                 C   s,   |r	|| j |< d S || j v r| j |= d S d S rE   rH   )r3   ry   r>   r   r   r   r      s
   
z_dok_base._set_intc                 C   s4   ||f}|r|| j |< d S || j v r| j |= d S d S rE   rH   )r3   r{   r|   r>   rJ   r   r   r   _set_intXint  s   
z_dok_base._set_intXintc                 C   s   t tt| }t tt| }| }| jtt||| t|dkd D ]}|| || f}| j| dkr@| j|= q+d S rw   )	r   r   rq   Zravelr'   r:   rj   r-   Znonzero)r3   r{   r|   r>   r   rJ   r   r   r   _set_arrayXarray
  s   z_dok_base._set_arrayXarrayc                    s\  t |r1t| j|}| j| j|d tjdd | jD  D ]}| j|d| }|r.| |< q S t	|r|j| jkr?t
dt| j|j}| j| j|d | j  _|jdkr^| }n| }| jdkrqt|jd |j}n	tt|j |j}tjdd	  j fd
d|D  W d     S 1 sw   Y   S t|r|  |   S tS )Nr!   c                 S   s   g | ]}t |qS r   )r   )r   r6   r   r   r   
<listcomp>  s    z%_dok_base.__add__.<locals>.<listcomp>r   z Matrix dimensions are not equal.r   r   ignore)Zoverc                 3   s$    | ]\}}| | | fV  qd S rE   r   r   kr   newr   r   r?   .  rf   z$_dok_base.__add__.<locals>.<genexpr>)r   r   r"   r   r,   r   r   r'   rl   r	   ri   r   r   r)   ra   tocoor0   rj   coordsdatar-   Zerrstater:   r   ZtodenseNotImplemented)r3   r[   	res_dtyperJ   ZaijZo_itemsr   r   r   __add__  s>   



z_dok_base.__add__c                 C   s   | | S rE   r   r3   r[   r   r   r   __radd__5  rT   z_dok_base.__radd__c                 C   sD   | j jdkr
td| j| j| j d}|jdd |  D  |S )Nbz2Negating a sparse boolean matrix is not supported.r!   c                 s   s    | ]
\}}|| fV  qd S rE   r   r   r   r   r   r?   >  s    z$_dok_base.__neg__.<locals>.<genexpr>)r"   kindr8   r   r,   r'   r:   ra   r3   r   r   r   r   __neg__8  s   z_dok_base.__neg__c                    s>   t | j }| j| j|d}|j fdd|  D  |S )Nr!   c                 3        | ]\}}||  fV  qd S rE   r   r   r[   r   r   r?   E      z(_dok_base._mul_scalar.<locals>.<genexpr>)r   r"   r   r,   r'   r:   ra   r3   r[   r   r   r   r   r   _mul_scalarA  s   z_dok_base._mul_scalarc                    s   t j j}jdkrLt r7 jdkr   @ }n   jd @ }|t fdd|D S t	 rJ|t fdd
 D S tS tjjd |d}
 D ]\\}}}||  | |  7  < qZ|S )Nr   r   r   c                 3   s$    | ]}j |  j |  V  qd S rE   rH   )r   r   r[   r3   r   r   r?   R  rf   z+_dok_base._matmul_vector.<locals>.<genexpr>c                 3   s     | ]\}} | | V  qd S rE   r   r   r   r   r   r?   T  r   r!   )r   r"   r0   r	   r)   rb   r   r   r@   r   ra   r   r-   zerosr,   )r3   r[   r   rb   resultr   r   r   r   r   r   _matmul_vectorH  s   

z_dok_base._matmul_vectorc           	         s   t | j j}| jdkrt fdd| j D S | jd } jdkr'|fn| jd f}tj||d}|  D ]\\}}}||  | |  7  < q9|S )Nr   c                 3   s     | ]\}}| |  V  qd S rE   r   )r   r   r   r   r   r   r?   c  r   z0_dok_base._matmul_multivector.<locals>.<genexpr>r   r!   )	r   r"   r0   r@   r'   ra   r,   r-   r   )	r3   r[   Zresult_dtypere   Z	new_shaper   r   r   r   r   r   r   _matmul_multivector^  s   

z_dok_base._matmul_multivectorc                    .   t  r| j fdd|  D  | S tS )Nc                 3   r   rE   r   r   r   r   r   r?   o  r   z%_dok_base.__imul__.<locals>.<genexpr>r   r'   r:   ra   r   r   r   r   r   __imul__m     z_dok_base.__imul__c                    sR   t  r#t| j }| j| j|d}|j fdd|  D  |S |    S )Nr!   c                 3        | ]\}}||  fV  qd S rE   r   r   r   r   r   r?   w  r   z(_dok_base.__truediv__.<locals>.<genexpr>)	r   r   r"   r   r,   r'   r:   ra   Ztocsrr   r   r   r   __truediv__s  s   z_dok_base.__truediv__c                    r   )Nc                 3   r   rE   r   r   r   r   r   r?   }  r   z)_dok_base.__itruediv__.<locals>.<genexpr>r   r   r   r   r   __itruediv__{  r   z_dok_base.__itruediv__c                 C   s
   t | S rE   )dict
__reduce__rB   r   r   r   r     s   
z_dok_base.__reduce__r   c                    s   | j dkrt |S td)Nr   z diagonal requires two dimensions)r0   ro   diagonalri   )r3   r   ru   r   r   r     s   
z_dok_base.diagonalc                 C   sh   | j dkr	|  S |d ur|dkrtd| j\}}| j||f| j|d}|jdd |  D  |S )Nr   )r   r   zvSparse arrays/matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.)r"   r   c                 s   s$    | ]\\}}}||f|fV  qd S rE   r   r   leftrightr9   r   r   r   r?     rf   z&_dok_base.transpose.<locals>.<genexpr>)	r0   r   ri   r,   r   r"   r'   r:   ra   )r3   Zaxesr   re   Nr   r   r   r   	transpose  s   

z_dok_base.transposec                 C   sX   | j dkr|  }|j |_|S | j\}}| j||f| jd}dd |  D |_|S )zReturn the conjugate transpose.r   r!   c                 S   s$   i | ]\\}}}||ft |qS r   )r-   Zconjr   r   r   r   r      s   $ z(_dok_base.conjtransp.<locals>.<dictcomp>)	r0   r   r   	conjugater,   r   r"   ra   r'   )r3   r   re   r   r   r   r   
conjtransp  s   

z_dok_base.conjtranspc                 C   s$   | j | j| jd}|j| j |S Nr!   )r   r,   r"   r'   r:   r   r   r   r   r     s   z_dok_base.copyr   c                C   s^   t ||}ttt|trtdd t| D }nt|d f}| |t|d}||_	|S )Nc                 s   s    | ]	}t |d  V  qdS )r   N)max)r   ry   r   r   r   r?     s    z%_dok_base.fromkeys.<locals>.<genexpr>r   r!   )
r   fromkeysr$   nextiterr%   rj   r   rX   r'   )clsiterabler   tmpr,   r   r   r   r   r     s   z_dok_base.fromkeysc                    s   | j dkr| j| j| jdS | jt| jd tj|  | jd}| j	dkr/t
|   n|  f}t fdd|D }| j||f| j| jd}d	|_|S )
Nr   r!   )Zmaxvalr"   countr   c                 3   s     | ]}t j| d V  qdS )r   N)r-   fromiter)r   ZixZ	idx_dtypennzr   r   r?     r   z"_dok_base.tocoo.<locals>.<genexpr>)r,   r"   T)r   r2   r,   r"   Z_get_index_dtyper   r-   r   rA   r0   rj   rb   r%   Zhas_canonical_format)r3   r   r   Zindsr   Ar   r   r   r     s    z_dok_base.tocooc                 C   s   |r|   S | S rE   r   r3   r   r   r   r   r*     s   z_dok_base.todokc                 C   s&   | j dkr	td| jddj|dS )Nr   z%tocsr() not valid for 1d sparse arrayFr   )r0   r8   r   tocscr   r   r   r   r     s   
z_dok_base.tocscc           	      G   s   t | t}t||d}t|t| jkrt| jdkr4|d }t| jD ]
}||kr.| j|= q$|| _	d S |\}}| j\}}||k sE||k r^t| 
 D ]\}}||ksW||kr]| j||f= qK|| _	d S )Nr   r   rm   )r$   r   r   r;   r,   r8   r0   r   r'   r&   rb   )	r3   r,   r4   ZnewNr   ZnewMre   r   r   r   r   r   resize  s(   



z_dok_base.resizeunsafeTc                 C   sb   t |}| j|kr)| j| j|d}t jt| j |d}tt	| j||_|S |r/| 
 S | S r   )r-   r"   r   r,   Zarrayr   r'   rA   r   rj   r   )r3   r"   Zcastingr   r   r   r   r   r   r+     s   

z_dok_base.astype)NNFrE   )rc   r   )NF)r   )F)r   T)?rY   
__module____qualname___formatr#   r:   r<   rC   r   __doc__rF   rK   rL   rM   rP   rQ   rS   r\   r^   r_   r`   ra   rb   rA   rl   rp   rs   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   classmethodr   r   r*   r   r   r+   __classcell__r   r   ru   r   r      s    
(




	










r   c                 C   s
   t | tS )a  Is `x` of dok_array type?

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

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

    Examples
    --------
    >>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok
    >>> isspmatrix_dok(dok_matrix([[5]]))
    True
    >>> isspmatrix_dok(dok_array([[5]]))
    False
    >>> isspmatrix_dok(coo_matrix([[5]]))
    False
    )r$   r   )r>   r   r   r   r      s   
r   c                   @   s   e Zd ZdZdS )r   a!  
    Dictionary Of Keys based sparse array.

    This is an efficient structure for constructing sparse
    arrays incrementally.

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

        dok_array(S)
            with another sparse array or matrix S (equivalent to S.todok())

        dok_array((M,N), [dtype])
            create the array with initial shape (M,N)
            dtype is optional, defaulting to dtype='d'

    Attributes
    ----------
    dtype : dtype
        Data type of the array
    shape : 2-tuple
        Shape of the array
    ndim : int
        Number of dimensions (this is always 2)
    nnz
        Number of nonzero elements
    size
    T

    Notes
    -----

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

    - Allows for efficient O(1) access of individual elements.
    - Duplicates are not allowed.
    - Can be efficiently converted to a coo_array once constructed.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import dok_array
    >>> S = dok_array((5, 5), dtype=np.float32)
    >>> for i in range(5):
    ...     for j in range(5):
    ...         S[i, j] = i + j    # Update element

    N)rY   r   r   r   r   r   r   r   r     s    r   c                   @   sL   e Zd ZdZdd Zdd ZeeedZdd Zd	d
 Z	dd Z
dd ZdS )r   a/  
    Dictionary Of Keys based sparse matrix.

    This is an efficient structure for constructing sparse
    matrices incrementally.

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

        dok_matrix(S)
            with another sparse array or matrix S (equivalent to S.todok())

        dok_matrix((M,N), [dtype])
            create the matrix with initial shape (M,N)
            dtype is optional, defaulting to dtype='d'

    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
    size
    T

    Notes
    -----

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

    - Allows for efficient O(1) access of individual elements.
    - Duplicates are not allowed.
    - Can be efficiently converted to a coo_matrix once constructed.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import dok_matrix
    >>> S = dok_matrix((5, 5), dtype=np.float32)
    >>> for i in range(5):
    ...     for j in range(5):
    ...         S[i, j] = i + j    # Update element

    c                 C   s"   | j |dd| j}|j| _d S )NFr   )ZreshapeZasformatr)   __dict__)r3   r,   Z
new_matrixr   r   r   	set_shape  s   zdok_matrix.set_shapec                 C   s   | j S )zGet shape of a sparse matrix.)r&   rB   r   r   r   	get_shape  s   zdok_matrix.get_shape)fgetfsetc                 C   rO   rE   )r'   rS   rB   r   r   r   rS     rG   zdok_matrix.__reversed__c                 C       t |tr| j|jB S | j|B S rE   r$   r   r'   r   r   r   r   r\        

zdok_matrix.__or__c                 C   r   rE   r   r   r   r   r   r^     r   zdok_matrix.__ror__c                 C   s0   t |tr|  j|jO  _| S |  j|O  _| S rE   r   r   r   r   r   r_     s
   
zdok_matrix.__ior__N)rY   r   r   r   r   r   propertyr,   rS   r\   r^   r_   r   r   r   r   r   P  s    3r   )r   Z__docformat____all__r   Znumpyr-   Z_matrixr   Z_baser   r   r	   Z_indexr
   Z_sputilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s     (   r5