
    9=e7Z                     L   d Z dZg dZddlmZ ddlZddlmZm	Z	 ddl
mZmZ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mZmZmZmZmZmZmZmZ ddl Z  G d dee          Z!d Z" G d de!e          Z#e!j         e#_          G d dee!          Z$ e	e!j                   e$_         dS )z2 A sparse matrix in COOrdinate or 'triplet' formatzrestructuredtext en)	coo_array
coo_matrixisspmatrix_coo    )warnN   )spmatrix_array_doc_to_matrix)	coo_tocsrcoo_todense
coo_matvec)issparseSparseEfficiencyWarning_spbasesparray)_data_matrix_minmax_mixin)	upcastupcast_char	to_nativeisshapegetdtypegetdatadowncast_intp_indexcheck_shapecheck_reshape_kwargsc                      e Zd ZdZdZddZd Zej        j        e_        ddZej        j        e_        d Z	dd	Z
ej
        j        e
_        d
 Zej        j        e_        ddZd dZd dZd dZej        j        e_        d dZej        j        e_        d dZej        j        e_        d!dZej        j        e_        d Zd"dZd Zd Zd Zd Zd Zd ZdS )#	_coo_basea  
    A sparse matrix in COOrdinate format.

    Also known as the 'ijv' or 'triplet' format.

    This can be instantiated in several ways:
        coo_array(D)
            with a dense matrix D

        coo_array(S)
            with another sparse matrix S (equivalent to S.tocoo())

        coo_array((M, N), [dtype])
            to construct an empty matrix with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

        coo_array((data, (i, j)), [shape=(M, N)])
            to construct from three arrays:
                1. data[:]   the entries of the matrix, in any order
                2. i[:]      the row indices of the matrix entries
                3. j[:]      the column indices of the matrix entries

            Where ``A[i[k], j[k]] = data[k]``.  When shape is not
            specified, it is 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
        COO format data array of the matrix
    row
        COO format row index array of the matrix
    col
        COO format column index array of the matrix

    Notes
    -----

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

    Advantages of the COO format
        - facilitates fast conversion among sparse formats
        - permits duplicate entries (see example)
        - very fast conversion to and from CSR/CSC formats

    Disadvantages of the COO format
        - does not directly support:
            + arithmetic operations
            + slicing

    Intended Usage
        - COO is a fast format for constructing sparse matrices
        - Once a matrix has been constructed, convert to CSR or
          CSC format for fast arithmetic and matrix vector operations
        - By default when converting to CSR or CSC format, duplicate (i,j)
          entries will be summed together.  This facilitates efficient
          construction of finite element matrices and the like. (see example)

    Canonical format
        - Entries and indices sorted by row, then column.
        - There are no duplicate entries (i.e. duplicate (i,j) locations)
        - Arrays MAY have explicit zeros.

    Examples
    --------

    >>> # Constructing an empty matrix
    >>> import numpy as np
    >>> from scipy.sparse import coo_array
    >>> coo_array((3, 4), dtype=np.int8).toarray()
    array([[0, 0, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 0]], dtype=int8)

    >>> # Constructing a matrix using ijv format
    >>> row  = np.array([0, 3, 1, 0])
    >>> col  = np.array([0, 3, 1, 2])
    >>> data = np.array([4, 5, 7, 9])
    >>> coo_array((data, (row, col)), shape=(4, 4)).toarray()
    array([[4, 0, 9, 0],
           [0, 7, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 5]])

    >>> # Constructing a matrix with duplicate indices
    >>> row  = np.array([0, 0, 1, 3, 1, 0, 0])
    >>> col  = np.array([0, 2, 1, 3, 1, 0, 0])
    >>> data = np.array([1, 1, 1, 1, 1, 1, 1])
    >>> coo = coo_array((data, (row, col)), shape=(4, 4))
    >>> # Duplicate indices are maintained until implicitly or explicitly summed
    >>> np.max(coo.data)
    1
    >>> coo.toarray()
    array([[3, 0, 1, 0],
           [0, 2, 0, 0],
           [0, 0, 0, 0],
           [0, 0, 0, 1]])

    cooNFc                 N	   t          j        |            t          |t                    r0t	          |          r|\  }}t          ||f          | _        |                     t          ||                    }t          |t                    }t          j        g |          | _        t          j        g |          | _        t          j        g |          | _        d| _        n	 |\  }	\  }
}n)# t"          t$          f$ r}t#          d          |d }~ww xY w|t'          |
          dk    st'          |          dk    rt%          d          t)          j        t          j        |
                    dz   }t)          j        t          j        |                    dz   }t          ||f          | _        n|\  }}t          ||f          | _        |                     |
|ft          | j                  d	          }t          j        |
||
          | _        t          j        |||
          | _        t/          |	||
          | _        d| _        nt1          |          r|j        | j        k    rv|rt|j                                        | _        |j                                        | _        |j                                        | _        t          |j                  | _        nQ|                                }|j        | _        |j        | _        |j        | _        t          |j                  | _        d| _        n$t          j        t          j        |                    }|j        dk    rt#          d          t          |j                  | _        |2t          |          | j        k    rt%          d|d| j                  |                     t          | j                            }|                                \  }
}|
                     |d          | _        |                     |d          | _        || j        | j        f         | _        d| _        |!| j                             |d          | _        | !                                 d S )Nmaxval)defaultdtypeTzinvalid input formatr   z4cannot infer dimensions from zero sized index arraysr   )r!   check_contents)copyr$   F   z'expected dimension <= 2 array or matrixzinconsistent shapes: z != r&   )"r   __init__
isinstancetupler   r   _shape_get_index_dtypemaxr   floatnparrayrowcoldatahas_canonical_format	TypeError
ValueErrorlenoperatorindexshaper   r   formatr&   tocoo
atleast_2dasarrayndimnonzeroastype_check)selfarg1r;   r$   r&   MN	idx_dtype
data_dtypeobjr2   r3   er   index_dtypes                  1lib/python3.11/site-packages/scipy/sparse/_coo.pyr)   z_coo_base.__init__   s   d###dE"" @	1t}} 21)1a&11 11Q1CC	%eU;;;
8Bi8888Bi888HRz:::	,0))C&*OC#ss!:. C C C#$:;;BC =3xx1}}CA( *> ? ? ? rvc{{33a7A rvc{{33a7A"-q!f"5"5DKK !DAq"-q!f"5"5DK 113*S__ei1jj	8Cd)DDD8Cd)DDD#Cd%@@@	,1))~~ 1;$+--$-#x}}DH#x}}DH $	 0 0DI"-dj"9"9DKK**,,C"wDH"wDH #DI"-ci"8"8DK,1)) M"*T"2"2336Q;;#$MNNN)!'22$"5))T[88(j*/%%*> ? ? ?"333t{;K;K3LL99;;S::k:>>::k:>>dh01	,0)	((U(;;DIs   *C3 3DDDc                 N   t          || j                  }t          |          \  }}|| j        k    r|r|                                 S | S | j        \  }}|dk    r||                     |t          d|dz
            z  t          d|dz
            z             }t          j        || j        |          | j	        z   }	t          |	|d                   \  }
}n|dk    r||                     |t          d|dz
            z  t          d|dz
            z             }t          j        || j	        |          | j        z   }	t          |	|d                   \  }}
nt          d          |r| j                                        }n| j        }|                     ||
|ff|d	          S )
NCr   r   r    r#   Fz'order' must be 'C' or 'F'Fr;   r&   )r   r;   r   r&   r-   r.   r0   multiplyr2   r3   divmodr7   r4   	__class__)rD   argskwargsr;   orderr&   nrowsncolsr$   flat_indicesnew_rownew_colnew_datas                rM   reshapez_coo_base.reshape   s   D$*--*622t DJ yy{{"zuC<< ))%#a:K:K2KcRSUZ]^U^N_N_2_)aaE;udheDDDtxOL%lE!H==GWWc\\))%#a:K:K2KcRSUZ]^U^N_N_2_)aaE;udheDDDtxOL%lE!H==GWW9:::  	!y~~''HHyH~~x'7);<$)  7 7 	7    c                 `   |t          | j                  }|t          | j                  k    s|t          | j                  k    rt	          d          | j        j        dk    s | j        j        dk    s| j        j        dk    rt	          d          t          |          S |dk     r|dz  }|dk    r3t          j        t          | j                  | j
        d                   S |dk    r3t          j        t          | j                  | j
        d                   S t	          d          )Nz7row, column, and data array must all be the same lengthr   z(row, column, and data arrays must be 1-Dr   r'   )	minlengthzaxis out of bounds)r8   r4   r2   r3   r7   r@   intr0   bincountr   r;   )rD   axisnnzs      rM   _getnnzz_coo_base._getnnz   s+   <di..Cc$(mm##sc$(mm';';  "/ 0 0 0 y~""dhmq&8&8HMQ&& !KLLLs88O!88AID199;248<<)-A8 8 8 8QYY;248<<)-A8 8 8 8 1222r_   c                    | j         j        j        dk    r!t          d| j         j        j        z             | j        j        j        dk    r!t          d| j        j        j        z             |                     | j         | j        ft          | j                            }t          j
        | j         |          | _         t          j
        | j        |          | _        t          | j                  | _        | j        dk    r| j                                         | j        d         k    rt          d          | j                                        | j        d         k    rt          d	          | j                                         dk     rt          d
          | j                                        dk     rt          d          dS dS )z' Checks data structure for consistency iz,row index array has non-integer dtype (%s)  z+col index array has non-integer dtype (%s) r    r#   r   z#row index exceeds matrix dimensionsr   z&column index exceeds matrix dimensionsznegative row index foundznegative column index foundN)r2   r$   kindr   namer3   r-   r.   r;   r0   r?   r   r4   re   r7   min)rD   rH   s     rM   rC   z_coo_base._check  s    8>#%%?hn)* + + +8>#%%>hn)* + + + ))48TX*>s4:)WW	:dhi888:dhi888di((	8a<<x||~~A.. !FGGGx||~~A.. !IJJJx||~~!! !;<<<x||~~!! !>??? < "!r_   c                     |t          d          | j        \  }}|                     | j        | j        | j        ff||f|          S )NzoSparse matrices do not support an 'axes' parameter because swapping dimensions is the only logical permutation.rQ   )r7   r;   rT   r4   r3   r2   )rD   axesr&   rF   rG   s        rM   	transposez_coo_base.transpose+  sf     L M M M z1~~ty48TX*>?%&F  7 7 	7r_   c                 J   t          |          }|\  }}| j        \  }}||k     s||k     rqt          j        | j        |k     | j        |k               }|                                s6| j        |         | _        | j        |         | _        | j        |         | _        || _        d S N)	r   r;   r0   logical_andr2   r3   allr4   r,   )rD   r;   new_Mnew_NrF   rG   masks          rM   resizez_coo_base.resize7  s    E""uz1199		>$(U"2DHu4DEED88:: ,8D>8D> IdO	r_   c                 ,   |                      ||          }t          |j        j                  }|s|j        j        st          d          | j        \  }}t          ||| j        | j	        | j
        | j        |                    d          |           |S )z(See the docstring for `_spbase.toarray`.z&Output array must be C or F contiguousA)_process_toarray_argsrb   flagsf_contiguousc_contiguousr7   r;   r   re   r2   r3   r4   ravel)rD   rW   outBfortranrF   rG   s          rM   toarrayz_coo_base.toarrayG  s    &&uc22ag*++ 	Gqw3 	GEFFFj!Aq$(DHdh	GGCLL'	+ 	+ 	+r_   c                    | j         dk    r!|                     | j        | j                  S | j        \  }}|                     | j        | j        ft          | j         |                    }| j                            |d          }| j                            |d          }t          j
        |dz   |          }t          j        ||          }t          j        | j        t          | j                            }	t          ||| j         ||| j        |||		  	         |                     |	||f| j                  }
| j        s|
                                 |
S )aK  Convert this matrix to Compressed Sparse Column format

        Duplicate entries will be summed together.

        Examples
        --------
        >>> from numpy import array
        >>> from scipy.sparse import coo_array
        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
        >>> data = array([1, 1, 1, 1, 1, 1, 1])
        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsc()
        >>> A.toarray()
        array([[3, 0, 1, 0],
               [0, 2, 0, 0],
               [0, 0, 0, 0],
               [0, 0, 0, 1]])

        r   r#   r    Fr(   r   r;   )re   _csc_containerr;   r$   r-   r3   r2   r.   rB   r0   empty
empty_liker4   r   r
   r5   sum_duplicatesrD   r&   rF   rG   rH   r2   r3   indptrindicesr4   xs              rM   tocscz_coo_base.tocscR  U   ( 8q==&&tz&DDD*CAa--48$S1-=-= .  I (//)%/88C(//)%/88CXa!e9555FmCy999G=&2D2DEEEDaDHc3	gt- - - ##T7F$;4:#NNA, #  """Hr_   c                    | j         dk    r!|                     | j        | j                  S | j        \  }}|                     | j        | j        ft          | j         |                    }| j                            |d          }| j                            |d          }t          j
        |dz   |          }t          j        ||          }t          j        | j        t          | j                            }	t          ||| j         ||| j        |||		  	         |                     |	||f| j                  }
| j        s|
                                 |
S )aH  Convert this matrix to Compressed Sparse Row format

        Duplicate entries will be summed together.

        Examples
        --------
        >>> from numpy import array
        >>> from scipy.sparse import coo_array
        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
        >>> data = array([1, 1, 1, 1, 1, 1, 1])
        >>> A = coo_array((data, (row, col)), shape=(4, 4)).tocsr()
        >>> A.toarray()
        array([[3, 0, 1, 0],
               [0, 2, 0, 0],
               [0, 0, 0, 0],
               [0, 0, 0, 1]])

        r   r#   r    Fr(   r   r   )re   _csr_containerr;   r$   r-   r2   r3   r.   rB   r0   r   r   r4   r   r
   r5   r   r   s              rM   tocsrz_coo_base.tocsr|  r   r_   c                 2    |r|                                  S | S rp   r(   )rD   r&   s     rM   r=   z_coo_base.tocoo  s     	99;;Kr_   c                 (   |                                   | j        | j        z
  }t          j        |d          \  }}t          |          dk    r%t          dt          |          z  t                     | j        j	        dk    rt          j
        d| j                  }nUt          j
        t          |          | j                                        dz   f| j                  }| j        ||| j        f<   |                     ||f| j        	          S )
NT)return_inversed   z:Constructing a DIA matrix with %d diagonals is inefficientr   )r   r   r#   r   r   )r   r3   r2   r0   uniquer8   r   r   r4   sizezerosr$   r.   _dia_containerr;   )rD   r&   ksdiagsdiag_idxr4   s         rM   todiaz_coo_base.todia  s   X )Bt<<<xu:: "$'JJ/0GI I I 9>Q8F$*555DD8SZZ)9:$*MMMD'+yD48#$""D%=
"CCCr_   c                     |                                   |                     | j        | j                  }|                    t          t          | j        | j                  | j                             |S )Nr#   )	r   _dok_containerr;   r$   _updatezipr2   r3   r4   )rD   r&   doks      rM   todokz_coo_base.todok  sa    !!4:dj!AACDHTX..ty99:::
r_   r   c           
         | j         \  }}|| k    s||k    r t          j        d| j        j                  S t          j        t          |t          |d          z   |t          |d          z
            | j                  }| j        |z   | j	        k    }| j
        r| j        |         }| j        |         }n<|                     | j        |         | j	        |         | j        |                   \  }}}|||t          |d          z   <   |S Nr   r#   )r;   r0   r   r4   r$   r   rk   r.   r2   r3   r5   _sum_duplicates)	rD   krowscolsdiag	diag_maskr2   r4   _s	            rM   diagonalz_coo_base.diagonal  s	   Z
d::d8ATY_5555xD3q!99,dSAYY.>??"j* * *X\dh.	$ 	F(9%C9Y'DD//0C040C04	)0DF FLCD !%S3q!99_r_   c                    | j         \  }}|j        rt          |          sd S | j        j        }| j        | j        z
  |k    }|dk     rt          ||z   |          }|j        rt          |t          |                    }t          j        || j        |k              }t          j	        | | |z   |          }	t          j	        ||          }
nt          |||z
            }|j        rt          |t          |                    }t          j        || j        |k              }t          j	        ||          }	t          j	        |||z   |          }
|j        r|d |         }n"t          j
        || j                  }||d d <   t          j        | j        |         |	f          | _        t          j        | j        |         |
f          | _        t          j        | j        |         |f          | _        d| _        d S )Nr   r#   F)r;   r@   r8   r2   r$   r3   rk   r0   
logical_oraranger   concatenater4   r5   )rD   valuesr   rF   rG   rH   	full_keep	max_indexkeepr[   r\   r]   s               rM   _setdiagz_coo_base._setdiag  s   z1; 	s6{{ 	FHN	 Htx'1,	q55AaCI{ 8	3v;;77	=DH	,ABBDiQBN)DDDGi	;;;GGAqsI{ 8	3v;;77	=DH	,ABBDi	;;;Gi1y=	BBBG ; 	!jyj)HHx	<<<H HQQQK >48D>7";<<>48D>7";<<NDIdOX#>??	$)!!!r_   Tc                    |rT|                      || j                                        | j                                        ff| j        |j                  S |                      || j        | j        ff| j        |j                  S )zReturns a matrix with the same sparsity structure as self,
        but with different data.  By default the index arrays
        (i.e. .row and .col) are copied.
        )r;   r$   )rT   r2   r&   r3   r;   r$   )rD   r4   r&   s      rM   
_with_dataz_coo_base._with_data  s    
  	G>>4$(--//48==??)K"L)-4: " G G G >>4$(DH)=">)-4: " G G Gr_   c                     | j         rdS |                     | j        | j        | j                  }|\  | _        | _        | _        d| _         dS )zlEliminate duplicate matrix entries by adding them together

        This is an *in place* operation
        NT)r5   r   r2   r3   r4   )rD   summeds     rM   r   z_coo_base.sum_duplicates  sQ    
 $ 	F%%dh$)DD(.%$(DI$(!!!r_   c                    t          |          dk    r|||fS t          j        ||f          }||         }||         }||         }|dd          |d d         k    |dd          |d d         k    z  }t          j        d|          }||         }||         }t          j        |          \  }t          j                            ||| j                  }|||fS )Nr   r   Tr#   )r8   r0   lexsortappendrA   addreduceatr$   )rD   r2   r3   r4   rW   unique_maskunique_indss          rM   r   z_coo_base._sum_duplicates  s    t99>>T>! 
C:&&%j%jE{ABB3ss8+ABB3ss8+-ik22++z+..vt[
CCC~r_   c                     | j         dk    }| j         |         | _         | j        |         | _        | j        |         | _        dS )zURemove zero entries from the matrix

        This is an *in place* operation
        r   N)r4   r2   r3   )rD   ru   s     rM   eliminate_zerosz_coo_base.eliminate_zeros1  s:    
 yA~IdO	8D>8D>r_   c                    |j         | j         k    r-t          d                    | j         |j                             t          | j        j        |j        j                  }t          j        ||d          }t          |j	        j
                  }| j         \  }}t          ||| j        | j        | j        | j        |                    d          |           |                     |d          S )NzIncompatible shapes ({} and {})T)r$   r&   rx   Fr(   )r;   r7   r<   r   r$   charr0   r1   rb   rz   r{   r   re   r2   r3   r4   r}   
_container)rD   otherr$   resultr   rF   rG   s          rM   
_add_densez_coo_base._add_dense?  s    ;$*$$>$fTZ==? ? ?DJOU[-=>>%u4888fl/00z1Aq$(DHdh	LL%%w	0 	0 	0vE222r_   c                     t          j        | j        d         t          | j        j        |j        j                            }t          | j        | j        | j	        | j
        ||           |S r   )r0   r   r;   r   r$   r   r   re   r2   r3   r4   )rD   r   r   s      rM   _mul_vectorz_coo_base._mul_vectorK  sd    $*Q-{4:?<AK<L0N 0N O O O48TXtxE6JJJr_   c           
         t          j        |j        d         | j        d         ft          | j        j        |j        j                            }t          |j                  D ]3\  }}t          | j	        | j
        | j        | j        |||                    4|j                            t          |                    S )Nr   r   r#   )type)r0   r   r;   r   r$   r   	enumerateTr   re   r2   r3   r4   viewr   )rD   r   r   rh   r3   s        rM   _mul_multivectorz_coo_base._mul_multivectorR  s    5;q>4:a=9 +DJOU[=M N NP P P(( 	P 	PFAstx48TYVAYOOOOx}}$u++}...r_   )NNFrp   )NF)NN)F)r   )T)__name__
__module____qualname____doc___formatr)   r^   r   rf   rC   rn   rv   r   r   r   r=   r   r   r   r   r   r   r   r   r   r   r   r    r_   rM   r   r      s"       j jV GH H H HT%7 %7 %7N o-GO3 3 3 30 o-GO@ @ @47 7 7 7  )1I   ^+FN	 	 	 	( ( ( (T( ( ( (T    M)EMD D D D& M)EM    M)EM   & $,4H"* "* "*J
G 
G 
G 
G	) 	) 	)  (" " "
3 
3 
3  / / / / /r_   r   c                 ,    t          | t                    S )a  Is `x` of coo_matrix type?

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

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

    Examples
    --------
    >>> from scipy.sparse import coo_array, coo_matrix, csr_matrix, isspmatrix_coo
    >>> isspmatrix_coo(coo_matrix([[5]]))
    True
    >>> isspmatrix_coo(coo_array([[5]]))
    False
    >>> isspmatrix_coo(csr_matrix([[5]]))
    False
    )r*   r   )r   s    rM   r   r   Z  s    . a$$$r_   c                       e Zd ZdS )r   Nr   r   r   r   r_   rM   r   r   u          Dr_   r   c                       e Zd ZdS )r   Nr   r   r_   rM   r   r   z  r   r_   r   )%r   __docformat____all__warningsr   numpyr0   _matrixr   r	   _sparsetoolsr
   r   r   _baser   r   r   r   _datar   r   _sputilsr   r   r   r   r   r   r   r   r   r9   r   r   r   r   r   r_   rM   <module>r      s   8 8%
7
7
7           3 3 3 3 3 3 3 3 < < < < < < < < < < F F F F F F F F F F F F . . . . . . . .: : : : : : : : : : : : : : : : : : : : : : A	/ A	/ A	/ A	/ A	/m A	/ A	/ A	/H% % %6	 	 	 	 		7 	 	 	 %	 	 	 	 	 	9 	 	 	 *))*;<<
   r_   